text
stringlengths
2
1.04M
meta
dict
#include "config.h" #include "public/platform/WebRTCConfiguration.h" #include "platform/mediastream/RTCConfiguration.h" #include "public/platform/WebString.h" #include "public/platform/WebURL.h" #include "public/platform/WebVector.h" using namespace WebCore; namespace blink { WebRTCICEServer::WebRTCICEServer(const PassRefPtr<RTCIceServer>& iceServer) : m_private(iceServer) { } void WebRTCICEServer::assign(const WebRTCICEServer& other) { m_private = other.m_private; } void WebRTCICEServer::reset() { m_private.reset(); } WebURL WebRTCICEServer::uri() const { ASSERT(!isNull()); return m_private->uri(); } WebString WebRTCICEServer::username() const { ASSERT(!isNull()); return m_private->username(); } WebString WebRTCICEServer::credential() const { ASSERT(!isNull()); return m_private->credential(); } WebRTCConfiguration::WebRTCConfiguration(const PassRefPtr<RTCConfiguration>& configuration) : m_private(configuration) { } void WebRTCConfiguration::assign(const WebRTCConfiguration& other) { m_private = other.m_private; } void WebRTCConfiguration::reset() { m_private.reset(); } size_t WebRTCConfiguration::numberOfServers() const { ASSERT(!isNull()); return m_private->numberOfServers(); } WebRTCICEServer WebRTCConfiguration::server(size_t index) const { ASSERT(!isNull()); return WebRTCICEServer(m_private->server(index)); } } // namespace blink
{ "content_hash": "b165b86e07c6147eb307d214d2022efe", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 91, "avg_line_length": 18.93421052631579, "alnum_prop": 0.7275886031966643, "repo_name": "lordmos/blink", "id": "8aaabdb6f980ac946952f2bc533c8977d10813f3", "size": "3001", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/platform/exported/WebRTCConfiguration.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "6433" }, { "name": "C", "bytes": "753714" }, { "name": "C++", "bytes": "40028043" }, { "name": "CSS", "bytes": "539440" }, { "name": "F#", "bytes": "8755" }, { "name": "Java", "bytes": "18650" }, { "name": "JavaScript", "bytes": "25700387" }, { "name": "Objective-C", "bytes": "426711" }, { "name": "PHP", "bytes": "141755" }, { "name": "Perl", "bytes": "901523" }, { "name": "Python", "bytes": "3748305" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "9635" }, { "name": "XSLT", "bytes": "49328" } ], "symlink_target": "" }
namespace std_msgs { class String : public ros::Msg { public: const char* data; String(): data("") { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_data = strlen(this->data); varToArr(outbuffer + offset, length_data); offset += 4; memcpy(outbuffer + offset, this->data, length_data); offset += length_data; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_data; arrToVar(length_data, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_data; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_data-1]=0; this->data = (char *)(inbuffer + offset-1); offset += length_data; return offset; } const char * getType(){ return "std_msgs/String"; }; const char * getMD5(){ return "992ce8a1687cec8c8bd883ec73ca41d1"; }; }; } #endif
{ "content_hash": "a2ce103574c12e5fbcf505c17dd57d47", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 72, "avg_line_length": 22.47826086956522, "alnum_prop": 0.5802707930367504, "repo_name": "hmalatini/hermes3", "id": "7576c364f8380751435d60b157717167233b04fe", "size": "1179", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/arduino/lib-arduino/ros_lib/std_msgs/String.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "71864" }, { "name": "C++", "bytes": "917780" }, { "name": "CMake", "bytes": "108936" }, { "name": "EmberScript", "bytes": "565" }, { "name": "Makefile", "bytes": "7360" }, { "name": "Processing", "bytes": "40378" }, { "name": "Python", "bytes": "183790" }, { "name": "Shell", "bytes": "143" } ], "symlink_target": "" }
sudo apt-get install -y \ apt-transport-https \ ca-certificates \ curl \ software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" sudo apt-get update sudo apt-get install -y docker-ce sudo usermod -a -G docker $USER # Install jq sudo apt-get install -y jq # Install aws sudo apt-get install -y python-pip pip install awscli --upgrade --user # Configure aws aws configure # Install kubectl sudo apt-get update && sudo apt-get install -y apt-transport-https curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - sudo touch /etc/apt/sources.list.d/kubernetes.list echo "deb http://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list sudo apt-get update sudo apt-get install -y kubectl # Install heptio auth curl -o heptio-authenticator-aws https://amazon-eks.s3-us-west-2.amazonaws.com/1.10.3/2018-06-05/bin/linux/amd64/heptio-authenticator-aws chmod +x ./heptio-authenticator-aws mkdir -p ~/bin cp heptio-authenticator-aws ~/bin echo 'export PATH=$HOME/bin:$PATH' >> ~/.bashrc export PATH=$HOME/bin:$PATH # Install scanner sudo apt-get install -y \ build-essential \ cmake git libgtk2.0-dev pkg-config unzip llvm-5.0-dev clang-5.0 libc++-dev \ libgflags-dev libgtest-dev libssl-dev libcurl3-dev liblzma-dev \ libeigen3-dev libgoogle-glog-dev libatlas-base-dev libsuitesparse-dev \ libgflags-dev libx264-dev libopenjpeg-dev libxvidcore-dev \ libpng-dev libjpeg-dev libbz2-dev wget \ libleveldb-dev libsnappy-dev libhdf5-serial-dev liblmdb-dev python-dev \ python-tk autoconf autogen libtool libtbb-dev libopenblas-dev \ liblapacke-dev swig yasm python3.5 python3-pip cpio automake libass-dev \ libfreetype6-dev libsdl2-dev libtheora-dev libtool \ libva-dev libvdpau-dev libvorbis-dev libxcb1-dev libxcb-shm0-dev \ libxcb-xfixes0-dev mercurial texinfo zlib1g-dev curl libcap-dev \ libboost-all-dev libgnutls-dev libpq-dev postgresql libx265-dev pip3 install numpy git clone https://github.com/scanner-research/scanner.git cd scanner sudo bash ./deps.sh -a --prefix /usr/local mkdir build cd build cmake .. make -j$(nproc) cd .. bash ./build.sh
{ "content_hash": "4591c2c520ed8b2861127ec63faa0b6f", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 137, "avg_line_length": 34.55882352941177, "alnum_prop": 0.7472340425531915, "repo_name": "scanner-research/scanner", "id": "ab840198e192575f377335c6f35e3e88c1b9ff4b", "size": "2367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/apps/aws_kubernetes/build_staging_machine.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "22636" }, { "name": "C++", "bytes": "2033640" }, { "name": "CMake", "bytes": "86682" }, { "name": "Cuda", "bytes": "9853" }, { "name": "GDB", "bytes": "28" }, { "name": "Python", "bytes": "262574" }, { "name": "Shell", "bytes": "52972" } ], "symlink_target": "" }
package com.facebook.buck.cxx; import static com.facebook.buck.cxx.CxxFlavorSanitizer.sanitize; import static java.io.File.pathSeparator; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.oneOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeTrue; import com.facebook.buck.android.AssumeAndroidPlatform; import com.facebook.buck.cli.FakeBuckConfig; import com.facebook.buck.io.ExecutableFinder; import com.facebook.buck.io.MoreFiles; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.rules.BuildRuleStatus; import com.facebook.buck.rules.BuildRuleSuccessType; import com.facebook.buck.testutil.integration.BuckBuildLog; import com.facebook.buck.testutil.integration.InferHelper; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Joiner; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; @RunWith(Parameterized.class) public class CxxBinaryIntegrationTest { @Parameterized.Parameters(name = "sandbox_sources={0}") public static Collection<Object[]> data() { return ImmutableList.of(new Object[] {false}, new Object[] {true}); } @Parameterized.Parameter(0) public boolean sandboxSources; @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Test public void testInferCxxBinaryDepsCaching() throws IOException, InterruptedException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_deps"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()) .getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); for (BuildTarget buildTarget : buildLog.getAllTargets()) { buildLog.assertTargetWasFetchedFromCache(buildTarget.toString()); } /* * Check that if the file in the binary target changes, then all the deps will be fetched * from the cache */ String sourceName = "src_with_deps.c"; workspace.replaceFileContents("foo/" + sourceName, "10", "30"); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget captureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName); // this is flavored, and denotes the analysis step (generates a local report) BuildTarget inferAnalysisTarget = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); // this is the flavored version of the top level target (the one give in input to buck) BuildTarget inferReportTarget = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); BuildTarget aggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); String bt; for (BuildTarget buildTarget : buildLog.getAllTargets()) { bt = buildTarget.toString(); if (buildTarget.getFlavors() .contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR) || buildTarget.getFlavors().contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR) || buildTarget.getFlavors().contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR) || bt.equals(inferAnalysisTarget.toString()) || bt.equals(captureBuildTarget.toString()) || bt.equals(inferReportTarget.toString()) || bt.equals(aggregatedDepsTarget.toString())) { buildLog.assertTargetBuiltLocally(bt); } else { buildLog.assertTargetWasFetchedFromCache(buildTarget.toString()); } } } @Test public void testInferCxxBinaryDepsInvalidateCacheWhenVersionChanges() throws IOException, InterruptedException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build( cxxBuckConfig); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_deps"); final String inputBuildTargetName = inputBuildTarget.withFlavors( CxxInferEnhancer.InferFlavors.INFER.get()).getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); for (BuildTarget buildTarget : buildLog.getAllTargets()) { buildLog.assertTargetWasFetchedFromCache(buildTarget.toString()); } /* * Check that if the version of infer changes, then all the infer-related targets are * recomputed */ workspace.resetBuildLogFile(); workspace.replaceFileContents("fake-infer/fake-bin/infer", "0.12345", "9.9999"); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); String sourceName = "src_with_deps.c"; CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget topCaptureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName); BuildTarget topInferAnalysisTarget = inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); BuildTarget topInferReportTarget = inputBuildTarget.withFlavors( CxxInferEnhancer.InferFlavors.INFER.get()); BuildTarget depOneBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_one"); String depOneSourceName = "dep_one.c"; CxxSourceRuleFactory depOneSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), depOneBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget depOneCaptureBuildTarget = depOneSourceRuleFactory.createInferCaptureBuildTarget(depOneSourceName); BuildTarget depOneInferAnalysisTarget = depOneCaptureBuildTarget.withFlavors( cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); BuildTarget depTwoBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_two"); CxxSourceRuleFactory depTwoSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), depTwoBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget depTwoCaptureBuildTarget = depTwoSourceRuleFactory.createInferCaptureBuildTarget("dep_two.c"); BuildTarget depTwoInferAnalysisTarget = depTwoCaptureBuildTarget.withFlavors( cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); ImmutableSet<String> locallyBuiltTargets = ImmutableSet.of( cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(), topCaptureBuildTarget.toString(), topInferAnalysisTarget.toString(), topInferReportTarget.toString(), depOneSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(), depOneCaptureBuildTarget.toString(), depOneInferAnalysisTarget.toString(), depTwoSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget().toString(), depTwoCaptureBuildTarget.toString(), depTwoInferAnalysisTarget.toString()); // check that infer-related targets are getting rebuilt for (String t : locallyBuiltTargets) { buildLog.assertTargetBuiltLocally(t); } Set<String> builtFromCacheTargets = FluentIterable.from(buildLog.getAllTargets()) // Filter out header symlink tree rules, as they are always built locally. .filter( target -> ( !target.getFlavors() .contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR) && !target.getFlavors() .contains(CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR) && !target.getFlavors() .contains(CxxDescriptionEnhancer.SANDBOX_TREE_FLAVOR))) .transform(Object::toString) // Filter out any rules that are explicitly built locally. .filter(Predicates.not(locallyBuiltTargets::contains)) .toSet(); // check that all the other targets are fetched from the cache for (String t : builtFromCacheTargets) { buildLog.assertTargetWasFetchedFromCache(t); } } @Test public void testInferCxxBinaryWithoutDeps() throws IOException, InterruptedException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()) .getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that all the required build targets have been generated. */ String sourceName = "simple.cpp"; String sourceFull = "foo/" + sourceName; CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig); // this is unflavored, but bounded to the InferCapture build rule BuildTarget captureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName); // this is unflavored, but necessary to run the compiler successfully BuildTarget headerSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( inputBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget sandboxTreeTarget = CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget( inputBuildTarget, cxxPlatform.getFlavor()); // this is flavored, and denotes the analysis step (generates a local report) BuildTarget inferAnalysisTarget = inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); // this is flavored and corresponds to the top level target (the one give in input to buck) BuildTarget inferReportTarget = inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); BuildTarget aggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); ImmutableSortedSet.Builder<BuildTarget> targetsBuilder = ImmutableSortedSet.<BuildTarget>naturalOrder().add( aggregatedDepsTarget, headerSymlinkTreeTarget, captureBuildTarget, inferAnalysisTarget, inferReportTarget); if (sandboxSources) { targetsBuilder.add(sandboxTreeTarget); } BuckBuildLog buildLog = workspace.getBuildLog(); assertThat( buildLog.getAllTargets(), containsInAnyOrder(targetsBuilder.build().toArray())); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(captureBuildTarget.toString()); buildLog.assertTargetBuiltLocally(inferAnalysisTarget.toString()); buildLog.assertTargetBuiltLocally(inferReportTarget.toString()); /* * Check that running a build again results in no builds since nothing has changed. */ workspace.resetBuildLogFile(); // clear for new build workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); assertEquals(ImmutableSet.of(inferReportTarget), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingRuleKey(inferReportTarget.toString()); /* * Check that changing the source file results in running the capture/analysis rules again. */ workspace.resetBuildLogFile(); workspace.replaceFileContents(sourceFull, "*s = 42;", ""); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); targetsBuilder = ImmutableSortedSet.<BuildTarget>naturalOrder().add( aggregatedDepsTarget, captureBuildTarget, inferAnalysisTarget, inferReportTarget); if (sandboxSources) { targetsBuilder.add(headerSymlinkTreeTarget, sandboxTreeTarget); } assertEquals( buildLog.getAllTargets(), targetsBuilder.build()); buildLog.assertTargetBuiltLocally(captureBuildTarget.toString()); buildLog.assertTargetBuiltLocally(inferAnalysisTarget.toString()); if (sandboxSources) { buildLog.assertTargetHadMatchingRuleKey(headerSymlinkTreeTarget.toString()); buildLog.assertTargetHadMatchingInputRuleKey(sandboxTreeTarget.toString()); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); } else { buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString()); } } @Test public void testInferCxxBinaryWithDeps() throws IOException, InterruptedException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build( cxxBuckConfig); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:binary_with_deps"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()) .getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that all the required build targets have been generated. */ String sourceName = "src_with_deps.c"; CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig); // 1. create the targets of binary_with_deps // this is unflavored, but bounded to the InferCapture build rule BuildTarget topCaptureBuildTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget(sourceName); BuildTarget topSandboxTreeTarget = CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget( inputBuildTarget, cxxPlatform.getFlavor()); // this is unflavored, but necessary to run the compiler successfully BuildTarget topHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( inputBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); // this is flavored, and denotes the analysis step (generates a local report) BuildTarget topInferAnalysisTarget = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); // this is flavored and corresponds to the top level target (the one give in input to buck) BuildTarget topInferReportTarget = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); BuildTarget topAggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); // 2. create the targets of dep_one BuildTarget depOneBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_one"); String depOneSourceName = "dep_one.c"; String depOneSourceFull = "foo/" + depOneSourceName; CxxSourceRuleFactory depOneSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), depOneBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget depOneCaptureBuildTarget = depOneSourceRuleFactory.createInferCaptureBuildTarget(depOneSourceName); BuildTarget depOneSandboxTreeTarget = CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget( depOneBuildTarget, cxxPlatform.getFlavor()); BuildTarget depOneHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depOneBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget depOneExportedHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depOneBuildTarget, HeaderVisibility.PUBLIC, CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor()); BuildTarget depOneInferAnalysisTarget = depOneCaptureBuildTarget.withFlavors( cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); BuildTarget depOneAggregatedDepsTarget = depOneSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); // 3. create the targets of dep_two BuildTarget depTwoBuildTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:dep_two"); CxxSourceRuleFactory depTwoSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), depTwoBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget depTwoCaptureBuildTarget = depTwoSourceRuleFactory.createInferCaptureBuildTarget("dep_two.c"); BuildTarget depTwoSandboxTreeTarget = CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget( depTwoBuildTarget, cxxPlatform.getFlavor()); BuildTarget depTwoHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depTwoBuildTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget depTwoExportedHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depTwoBuildTarget, HeaderVisibility.PUBLIC, CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor()); BuildTarget depTwoInferAnalysisTarget = depTwoCaptureBuildTarget.withFlavors( cxxPlatform.getFlavor(), CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()); BuildTarget depTwoAggregatedDepsTarget = depTwoSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); ImmutableSet.Builder<BuildTarget> buildTargets = ImmutableSortedSet.<BuildTarget>naturalOrder().add( topAggregatedDepsTarget, topCaptureBuildTarget, topHeaderSymlinkTreeTarget, topInferAnalysisTarget, topInferReportTarget, depOneAggregatedDepsTarget, depOneCaptureBuildTarget, depOneHeaderSymlinkTreeTarget, depOneExportedHeaderSymlinkTreeTarget, depOneInferAnalysisTarget, depTwoAggregatedDepsTarget, depTwoCaptureBuildTarget, depTwoHeaderSymlinkTreeTarget, depTwoExportedHeaderSymlinkTreeTarget, depTwoInferAnalysisTarget); if (sandboxSources) { buildTargets.add( topSandboxTreeTarget, depOneSandboxTreeTarget, depTwoSandboxTreeTarget); } // Check all the targets are in the buildLog assertEquals( buildTargets.build(), ImmutableSet.copyOf(workspace.getBuildLog().getAllTargets())); /* * Check that running a build again results in no builds since nothing has changed. */ workspace.resetBuildLogFile(); // clear for new build workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); assertEquals(ImmutableSet.of(topInferReportTarget), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingRuleKey(topInferReportTarget.toString()); /* * Check that if a library source file changes then the capture/analysis rules run again on * the main target and on dep_one only. */ workspace.resetBuildLogFile(); workspace.replaceFileContents(depOneSourceFull, "flag > 0", "flag < 0"); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); buildTargets = ImmutableSortedSet.<BuildTarget>naturalOrder().add( topInferAnalysisTarget, // analysis runs again topInferReportTarget, // report runs again topCaptureBuildTarget, // cached depTwoInferAnalysisTarget, // cached depOneAggregatedDepsTarget, depOneCaptureBuildTarget, // capture of the changed file runs again depOneInferAnalysisTarget // analysis of the library runs again ); if (sandboxSources) { buildTargets.add( depOneSandboxTreeTarget, depOneHeaderSymlinkTreeTarget, depOneExportedHeaderSymlinkTreeTarget); } assertEquals( buildTargets.build(), buildLog.getAllTargets() ); buildLog.assertTargetBuiltLocally(topInferAnalysisTarget.toString()); buildLog.assertTargetBuiltLocally(topInferReportTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(topCaptureBuildTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depTwoInferAnalysisTarget.toString()); buildLog.assertTargetBuiltLocally(depOneCaptureBuildTarget.toString()); buildLog.assertTargetBuiltLocally(depOneInferAnalysisTarget.toString()); if (sandboxSources) { buildLog.assertTargetHadMatchingInputRuleKey(depOneSandboxTreeTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depOneHeaderSymlinkTreeTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depOneExportedHeaderSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(depOneAggregatedDepsTarget.toString()); } else { buildLog.assertTargetHadMatchingRuleKey(depOneAggregatedDepsTarget.toString()); } } @Test public void testInferCxxBinaryWithDepsEmitsAllTheDependenciesResultsDirs() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); // Build the given target and check that it succeeds. workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); assertTrue( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")))); String loggedDeps = workspace.getFileContents( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")); String sanitizedChainDepOne = sanitize("chain_dep_one.c.o"); String sanitizedTopChain = sanitize("top_chain.c.o"); String sanitizedChainDepTwo = sanitize("chain_dep_two.c.o"); BuildTarget analyzeTopChainTarget = BuildTargetFactory.newInstance( "//foo:binary_with_chain_deps#infer-analyze"); BuildTarget captureTopChainTarget = BuildTargetFactory.newInstance( "//foo:binary_with_chain_deps#default,infer-capture-" + sanitizedTopChain); BuildTarget analyzeChainDepOneTarget = BuildTargetFactory.newInstance( "//foo:chain_dep_one#default,infer-analyze"); BuildTarget captureChainDepOneTarget = BuildTargetFactory.newInstance( "//foo:chain_dep_one#default,infer-capture-" + sanitizedChainDepOne); BuildTarget analyzeChainDepTwoTarget = BuildTargetFactory.newInstance( "//foo:chain_dep_two#default,infer-analyze"); BuildTarget captureChainDepTwoTarget = BuildTargetFactory.newInstance( "//foo:chain_dep_two#default,infer-capture-" + sanitizedChainDepTwo); Path basePath = filesystem.getRootPath().toRealPath(); String expectedOutput = Joiner.on('\n').join( ImmutableList.of( analyzeTopChainTarget.getFullyQualifiedName() + "\t" + "[infer-analyze]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, analyzeTopChainTarget, "infer-analysis-%s")), captureTopChainTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedTopChain + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, captureTopChainTarget, "infer-out-%s")), analyzeChainDepOneTarget.getFullyQualifiedName() + "\t" + "[default, infer-analyze]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, analyzeChainDepOneTarget, "infer-analysis-%s")), captureChainDepOneTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedChainDepOne + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, captureChainDepOneTarget, "infer-out-%s")), analyzeChainDepTwoTarget.getFullyQualifiedName() + "\t" + "[default, infer-analyze]\t" + basePath.resolve( BuildTargets.getGenPath( filesystem, analyzeChainDepTwoTarget, "infer-analysis-%s")), captureChainDepTwoTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedChainDepTwo + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, captureChainDepTwoTarget, "infer-out-%s")))); assertEquals(expectedOutput + "\n", loggedDeps); } private static void registerCell( ProjectWorkspace cellToModifyConfigOf, String cellName, ProjectWorkspace cellToRegisterAsCellName) throws IOException { TestDataHelper.overrideBuckconfig( cellToModifyConfigOf, ImmutableMap.of( "repositories", ImmutableMap.of( cellName, cellToRegisterAsCellName.getPath(".").normalize().toString()))); } @Test public void inferShouldBeAbleToUseMultipleXCell() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); final Path rootWorkspacePath = tmp.getRoot(); // create infertest workspace ProjectWorkspace root = InferHelper.setupWorkspace(this, rootWorkspacePath, "infertest"); root.setupCxxSandboxing(sandboxSources); // create infertest/inter-cell/multi-cell/primary sub-workspace as infer-configured one Path primaryRootPath = tmp.newFolder().toRealPath().normalize(); ProjectWorkspace primary = InferHelper.setupCxxInferWorkspace( this, primaryRootPath, Optional.empty(), "infertest/inter-cell/multi-cell/primary", Optional.of(rootWorkspacePath.resolve("fake-infer"))); primary.setupCxxSandboxing(sandboxSources); // create infertest/inter-cell/multi-cell/secondary sub-workspace Path secondaryRootPath = tmp.newFolder().toRealPath().normalize(); ProjectWorkspace secondary = InferHelper.setupWorkspace( this, secondaryRootPath, "infertest/inter-cell/multi-cell/secondary"); secondary.setupCxxSandboxing(sandboxSources); // register cells registerCell(primary, "secondary", secondary); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//:cxxbinary") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); // run from primary workspace ProjectWorkspace.ProcessResult result = primary.runBuckBuild( InferHelper.getCxxCLIConfigurationArgs( rootWorkspacePath.resolve("fake-infer"), Optional.empty(), inputBuildTarget)); result.assertSuccess(); ProjectFilesystem filesystem = new ProjectFilesystem(primary.getDestPath()); String reportPath = BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/report.json").toString(); List<Object> bugs = InferHelper.loadInferReport(primary, reportPath); Assert.assertThat( "2 bugs expected in " + reportPath + " not found", bugs.size(), Matchers.equalTo(2)); } @Test public void testInferCxxBinaryWithDiamondDepsEmitsAllBuildRulesInvolvedWhenCacheHit() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); String buildTargetName = inputBuildTarget.getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", buildTargetName).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", buildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); ImmutableSet<BuildTarget> allInvolvedTargets = buildLog.getAllTargets(); assertEquals(1, allInvolvedTargets.size()); // Only main target should be fetched from cache for (BuildTarget bt : allInvolvedTargets) { buildLog.assertTargetWasFetchedFromCache(bt.toString()); } assertTrue( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")))); String loggedDeps = workspace.getFileContents( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")); BuildTarget analyzeMainTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps#infer-analyze"); BuildTarget analyzeDepOneTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_one#default,infer-analyze"); BuildTarget analyzeDepTwoTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_two#default,infer-analyze"); BuildTarget analyzeSimpleLibTarget = BuildTargetFactory.newInstance( "//foo:simple_lib#default,infer-analyze"); String sanitizedSimpleCpp = sanitize("simple.cpp.o"); String sanitizedDepOne = sanitize("dep_one.c.o"); String sanitizedDepTwo = sanitize("dep_two.c.o"); String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o"); BuildTarget simpleCppTarget = BuildTargetFactory.newInstance( "//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp); BuildTarget depOneTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne); BuildTarget depTwoTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo); BuildTarget srcWithDepsTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps); Path basePath = filesystem.getRootPath().toRealPath(); String expectedOutput = Joiner.on('\n').join( ImmutableList.of( InferLogLine.fromBuildTarget(analyzeMainTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, analyzeMainTarget, "infer-analysis-%s"))).toString(), InferLogLine.fromBuildTarget(srcWithDepsTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, srcWithDepsTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(analyzeDepOneTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, analyzeDepOneTarget, "infer-analysis-%s"))).toString(), InferLogLine.fromBuildTarget(depOneTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, depOneTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(analyzeDepTwoTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, analyzeDepTwoTarget, "infer-analysis-%s"))).toString(), InferLogLine.fromBuildTarget(depTwoTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, depTwoTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(analyzeSimpleLibTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, analyzeSimpleLibTarget, "infer-analysis-%s"))).toString(), InferLogLine.fromBuildTarget(simpleCppTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, simpleCppTarget, "infer-out-%s"))).toString())); assertEquals(expectedOutput + "\n", loggedDeps); } @Test public void testInferCaptureAllCxxBinaryWithDiamondDepsEmitsAllBuildRulesInvolvedWhenCacheHit() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get()); String buildTargetName = inputBuildTarget.getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", buildTargetName).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", buildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); ImmutableSet<BuildTarget> allInvolvedTargets = buildLog.getAllTargets(); for (BuildTarget bt : allInvolvedTargets) { buildLog.assertTargetWasFetchedFromCache(bt.toString()); } assertTrue( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")))); String loggedDeps = workspace.getFileContents( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")); String sanitizedSimpleCpp = sanitize("simple.cpp.o"); String sanitizedDepOne = sanitize("dep_one.c.o"); String sanitizedDepTwo = sanitize("dep_two.c.o"); String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o"); BuildTarget simpleCppTarget = BuildTargetFactory.newInstance( "//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp); BuildTarget depOneTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne); BuildTarget depTwoTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo); BuildTarget srcWithDepsTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps); Path basePath = filesystem.getRootPath().toRealPath(); String expectedOutput = Joiner.on('\n').join( ImmutableList.of( InferLogLine.fromBuildTarget(srcWithDepsTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, srcWithDepsTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(depOneTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, depOneTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(depTwoTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, depTwoTarget, "infer-out-%s"))).toString(), InferLogLine.fromBuildTarget(simpleCppTarget, basePath.resolve( BuildTargets.getGenPath( filesystem, simpleCppTarget, "infer-out-%s"))).toString())); assertEquals(expectedOutput + "\n", loggedDeps); } @Test public void testInferCxxBinaryWithDiamondDepsHasRuntimeDepsOfAllCaptureRulesWhenCacheHits( ) throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get()) .getFullyQualifiedName(); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); for (BuildTarget buildTarget : buildLog.getAllTargets()) { buildLog.assertTargetWasFetchedFromCache(buildTarget.toString()); } /* * Check that runtime deps have been fetched from cache as well */ assertTrue( "This file was expected to exist because it's declared as runtime dep", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:simple_lib#default,infer-capture-" + sanitize("simple.cpp.o")), "infer-out-%s") .resolve("captured/simple.cpp_captured/simple.cpp.cfg")))); assertTrue( "This file was expected to exist because it's declared as runtime dep", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:diamond_dep_one#default,infer-capture-" + sanitize("dep_one.c.o")), "infer-out-%s") .resolve("captured/dep_one.c_captured/dep_one.c.cfg")))); assertTrue( "This file was expected to exist because it's declared as runtime dep", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:diamond_dep_two#default,infer-capture-" + sanitize("dep_two.c.o")), "infer-out-%s") .resolve("captured/dep_two.c_captured/dep_two.c.cfg")))); assertTrue( "This file was expected to exist because it's declared as runtime dep", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps#default,infer-capture-" + sanitize("src_with_deps.c.o")), "infer-out-%s") .resolve("captured/src_with_deps.c_captured/src_with_deps.c.cfg")))); } @Test public void testInferCxxBinaryWithUnusedDepsDoesNotRebuildWhenUnusedHeaderChanges( ) throws IOException, InterruptedException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance( "//foo:binary_with_unused_header"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get()) .getFullyQualifiedName(); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build( cxxBuckConfig); CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), inputBuildTarget, cxxPlatform, cxxBuckConfig); BuildTarget simpleOneCppCaptureTarget = cxxSourceRuleFactory.createInferCaptureBuildTarget("simple_one.cpp"); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); /* * Check that when the unused-header is changed, no builds are triggered */ workspace.resetBuildLogFile(); workspace.replaceFileContents("foo/unused_header.h", "int* input", "int* input, int* input2"); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); BuckBuildLog.BuildLogEntry simpleOnceCppCaptureTargetEntry = buildLog.getLogEntry( simpleOneCppCaptureTarget); assertThat( simpleOnceCppCaptureTargetEntry.getSuccessType(), Matchers.equalTo(Optional.of(BuildRuleSuccessType.FETCHED_FROM_CACHE_MANIFEST_BASED))); /* * Check that when the used-header is changed, then a build is triggered */ workspace.resetBuildLogFile(); workspace.replaceFileContents("foo/used_header.h", "int* input", "int* input, int* input2"); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally(simpleOneCppCaptureTarget.toString()); } @Test public void testInferCxxBinaryWithDiamondDepsEmitsAllTransitiveCaptureRulesOnce( ) throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER_CAPTURE_ALL.get()); // Build the given target and check that it succeeds. workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); assertTrue( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")))); String loggedDeps = workspace.getFileContents( BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/infer-deps.txt")); String sanitizedSimpleCpp = sanitize("simple.cpp.o"); String sanitizedDepOne = sanitize("dep_one.c.o"); String sanitizedDepTwo = sanitize("dep_two.c.o"); String sanitizedSrcWithDeps = sanitize("src_with_deps.c.o"); BuildTarget simpleCppTarget = BuildTargetFactory.newInstance( "//foo:simple_lib#default,infer-capture-" + sanitizedSimpleCpp); BuildTarget depOneTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_one#default,infer-capture-" + sanitizedDepOne); BuildTarget depTwoTarget = BuildTargetFactory.newInstance( "//foo:diamond_dep_two#default,infer-capture-" + sanitizedDepTwo); BuildTarget srcWithDepsTarget = BuildTargetFactory.newInstance( "//foo:binary_with_diamond_deps#default,infer-capture-" + sanitizedSrcWithDeps); Path basePath = filesystem.getRootPath().toRealPath(); String expectedOutput = Joiner.on('\n').join( ImmutableList.of( srcWithDepsTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedSrcWithDeps + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, srcWithDepsTarget, "infer-out-%s")), depOneTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedDepOne + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, depOneTarget, "infer-out-%s")), depTwoTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedDepTwo + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, depTwoTarget, "infer-out-%s")), simpleCppTarget.getFullyQualifiedName() + "\t" + "[default, infer-capture-" + sanitizedSimpleCpp + "]\t" + basePath.resolve( BuildTargets.getGenPath(filesystem, simpleCppTarget, "infer-out-%s")))); assertEquals(expectedOutput + "\n", loggedDeps); } @Test public void testInferCxxBinarySkipsBlacklistedFiles() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.of(".*one\\.c")); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()) .getFullyQualifiedName(); // Build the given target and check that it succeeds. workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); // Check that the cfg associated with chain_dep_one.c does not exist assertFalse( "Cfg file for chain_dep_one.c should not exist", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:chain_dep_one#default,infer-capture-" + sanitize("chain_dep_one.c.o")), "infer-out-%s") .resolve("captured/chain_dep_one.c_captured/chain_dep_one.c.cfg")))); // Check that the remaining files still have their cfgs assertTrue( "Expected cfg for chain_dep_two.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:chain_dep_two#default,infer-capture-" + sanitize("chain_dep_two.c.o")), "infer-out-%s") .resolve("captured/chain_dep_two.c_captured/chain_dep_two.c.cfg")))); assertTrue( "Expected cfg for top_chain.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:binary_with_chain_deps#infer-analyze"), "infer-analysis-%s") .resolve("captured/top_chain.c_captured/top_chain.c.cfg")))); } @Test public void testInferCxxBinaryRunsOnAllFilesWhenBlacklistIsNotSpecified() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps"); String inputBuildTargetName = inputBuildTarget .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()) .getFullyQualifiedName(); // Build the given target and check that it succeeds. workspace.runBuckCommand("build", inputBuildTargetName).assertSuccess(); // Check that all cfgs have been created assertTrue( "Expected cfg for chain_dep_one.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:chain_dep_one#default,infer-capture-" + sanitize("chain_dep_one.c.o")), "infer-out-%s") .resolve("captured/chain_dep_one.c_captured/chain_dep_one.c.cfg")))); assertTrue( "Expected cfg for chain_dep_two.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:chain_dep_two#default,infer-capture-" + sanitize("chain_dep_two.c.o")), "infer-out-%s") .resolve("captured/chain_dep_two.c_captured/chain_dep_two.c.cfg")))); assertTrue( "Expected cfg for top_chain.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( filesystem, "//foo:binary_with_chain_deps#infer-analyze"), "infer-analysis-%s") .resolve("captured/top_chain.c_captured/top_chain.c.cfg")))); } @Test public void testInferCxxBinaryWithCachedDepsGetsAllItsTransitiveDeps() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); for (BuildTarget buildTarget : buildLog.getAllTargets()) { buildLog.assertTargetWasFetchedFromCache(buildTarget.toString()); } /* * Check that if the file in the top target changes, then all the transitive deps will be * fetched from the cache (even those that are not direct dependencies). * Make sure there's the specs file of the dependency that has distance 2 from * the binary target. */ String sourceName = "top_chain.c"; workspace.replaceFileContents("foo/" + sourceName, "*p += 1", "*p += 10"); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); // Check all the buildrules were fetched from the cache (and there's the specs file) assertTrue( "Expected specs file for func_ret_null() in chain_dep_two.c not found", Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, BuildTargetFactory.newInstance( "//foo:chain_dep_two#default,infer-analyze"), "infer-analysis-%s/specs/mockedSpec.specs")))); } @Test public void testInferCxxBinaryMergesAllReportsOfDependencies() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); /* * Build the given target and check that it succeeds. */ workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); String reportPath = BuildTargets.getGenPath(filesystem, inputBuildTarget, "infer-%s/report.json").toString(); List<Object> bugs = InferHelper.loadInferReport(workspace, reportPath); // check that the merge step has merged a total of 3 bugs, one for each target // (chain_dep_two, chain_dep_one, binary_with_chain_deps) Assert.assertThat( "3 bugs expected in " + reportPath + " not found", bugs.size(), Matchers.equalTo(3)); } @Test public void testInferCxxBinaryWritesSpecsListFilesOfTransitiveDependencies() throws IOException { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = InferHelper.setupCxxInferWorkspace( this, tmp, Optional.empty()); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget inputBuildTarget = BuildTargetFactory.newInstance("//foo:binary_with_chain_deps") .withFlavors(CxxInferEnhancer.InferFlavors.INFER.get()); //Build the given target and check that it succeeds. workspace.runBuckCommand("build", inputBuildTarget.getFullyQualifiedName()).assertSuccess(); String specsPathList = BuildTargets .getGenPath( filesystem, inputBuildTarget.withFlavors(CxxInferEnhancer.InferFlavors.INFER_ANALYZE.get()), "infer-analysis-%s/specs_path_list.txt") .toString(); String out = workspace.getFileContents(specsPathList); ImmutableList<Path> paths = FluentIterable.from(out.split("\n")).transform( input -> new File(input).toPath()).toList(); assertSame("There must be 2 paths in total", paths.size(), 2); for (Path path : paths) { assertTrue("Path must be absolute", path.isAbsolute()); assertTrue("Path must exist", Files.exists(path)); } } @Test public void testChangingCompilerPathForcesRebuild() throws Exception { assumeTrue(Platform.detect() != Platform.WINDOWS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget target = BuildTargetFactory.newInstance("//foo:simple"); BuildTarget linkTarget = CxxDescriptionEnhancer.createCxxLinkTarget(target, Optional.empty()); // Get the real location of the compiler executable. String executable = Platform.detect() == Platform.MACOS ? "clang++" : "g++"; Path executableLocation = new ExecutableFinder() .getOptionalExecutable(Paths.get(executable), ImmutableMap.copyOf(System.getenv())) .orElse(Paths.get("/usr/bin", executable)); // Write script as faux clang++/g++ binary Path firstCompilerPath = tmp.newFolder("path1"); Path firstCompiler = firstCompilerPath.resolve(executable); filesystem.writeContentsToPath( "#!/bin/sh\n" + "exec " + executableLocation.toString() + " \"$@\"\n", firstCompiler); // Write script as slightly different faux clang++/g++ binary Path secondCompilerPath = tmp.newFolder("path2"); Path secondCompiler = secondCompilerPath.resolve(executable); filesystem.writeContentsToPath( "#!/bin/sh\n" + "exec " + executableLocation.toString() + " \"$@\"\n" + "# Comment to make hash different.\n", secondCompiler); // Make the second faux clang++/g++ binary executable MoreFiles.makeExecutable(secondCompiler); // Run two builds, each with different compiler "binaries". In the first // instance, both binaries are in the PATH but the first binary is not // marked executable so is not picked up. workspace.runBuckCommandWithEnvironmentOverridesAndContext( workspace.getDestPath(), Optional.empty(), ImmutableMap.of("PATH", firstCompilerPath.toString() + pathSeparator + secondCompilerPath.toString() + pathSeparator + System.getenv("PATH")), "build", target.getFullyQualifiedName()).assertSuccess(); workspace.resetBuildLogFile(); // Now, make the first faux clang++/g++ binary executable. In this second // instance, both binaries are still in the PATH but the first binary is // now marked executable and so is picked up; causing a rebuild. MoreFiles.makeExecutable(firstCompiler); workspace.runBuckCommandWithEnvironmentOverridesAndContext( workspace.getDestPath(), Optional.empty(), ImmutableMap.of("PATH", firstCompilerPath.toString() + pathSeparator + secondCompilerPath.toString() + pathSeparator + System.getenv("PATH")), "build", target.getFullyQualifiedName()).assertSuccess(); // Make sure the binary change caused a rebuild. workspace.getBuildLog().assertTargetBuiltLocally(linkTarget.toString()); } @Test public void testLinkMapIsCached() throws Exception { // Currently we only support Apple platforms for generating link maps. assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); BuildTarget target = BuildTargetFactory.newInstance("//foo:simple"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); /* * Check that building after clean will use the cache */ workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", target.toString()).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); buildLog.assertTargetWasFetchedFromCache(target.toString()); assertThat(Files.exists(Paths.get(outputPath.toString() + "-LinkMap.txt")), is(true)); } @Test public void testSimpleCxxBinaryBuilds() throws Exception { Assume.assumeFalse("Test should be modified for sandboxing", sandboxSources); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig); BuildTarget target = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple"); CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig ); BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget( target, Optional.<LinkerMapMode>empty()); String sourceName = "simple.cpp"; String sourceFull = "foo/" + sourceName; BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName); BuildTarget headerSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget aggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); // Do a clean build, verify that it succeeds, and check that all expected targets built // successfully. workspace.runBuckCommand("build", target.toString()).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.<BuildTarget>builder() .add( aggregatedDepsTarget, headerSymlinkTreeTarget, compileTarget, binaryTarget, target) .build(), buildLog.getAllTargets()); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); buildLog.assertTargetBuiltLocally(binaryTarget.toString()); buildLog.assertTargetBuiltLocally(target.toString()); // Clear for new build. workspace.resetBuildLogFile(); // Check that running a build again results in no builds since everything is up to // date. workspace.runBuckCommand("build", target.toString()).assertSuccess(); buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.of(target, binaryTarget), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingRuleKey(binaryTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(target.toString()); // Clear for new build. workspace.resetBuildLogFile(); // Update the source file. workspace.replaceFileContents(sourceFull, "{}", "{ return 0; }"); // Check that running a build again makes the source get recompiled and the binary // re-linked, but does not cause the header rules to re-run. workspace.runBuckCommand("build", target.toString()).assertSuccess(); buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.<BuildTarget>builder() .add( aggregatedDepsTarget, compileTarget, binaryTarget, target) .build(), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); assertThat( buildLog.getLogEntry(binaryTarget).getSuccessType().get(), Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY))); // Clear for new build. workspace.resetBuildLogFile(); // Update the source file. workspace.replaceFileContents(sourceFull, "{ return 0; }", "won't compile"); // Check that running a build again makes the source get recompiled and the binary // re-linked, but does not cause the header rules to re-run. workspace.runBuckCommand("build", target.toString()).assertFailure(); buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.<BuildTarget>builder() .add( aggregatedDepsTarget, compileTarget, binaryTarget, target) .build(), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingRuleKey(aggregatedDepsTarget.toString()); assertThat( buildLog.getLogEntry(binaryTarget).getStatus(), Matchers.equalTo(BuildRuleStatus.CANCELED)); assertThat( buildLog.getLogEntry(target).getStatus(), Matchers.equalTo(BuildRuleStatus.CANCELED)); } @Test public void testSimpleCxxBinaryWithoutHeader() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckCommand("build", "//foo:simple_without_header").assertFailure(); } @Test public void testSimpleCxxBinaryWithHeader() throws IOException, InterruptedException { Assume.assumeFalse("Test should be modified for sandboxing", sandboxSources); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig); BuildTarget target = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:simple_with_header"); CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig); BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget( target, Optional.<LinkerMapMode>empty()); String sourceName = "simple_with_header.cpp"; String headerName = "simple_with_header.h"; String headerFull = "foo/" + headerName; BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName); BuildTarget headerSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget aggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); // Do a clean build, verify that it succeeds, and check that all expected targets built // successfully. workspace.runBuckCommand("build", target.toString()).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.of( aggregatedDepsTarget, headerSymlinkTreeTarget, compileTarget, binaryTarget, target), buildLog.getAllTargets()); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); buildLog.assertTargetBuiltLocally(binaryTarget.toString()); buildLog.assertTargetBuiltLocally(target.toString()); // Clear for new build. workspace.resetBuildLogFile(); // Update the source file. workspace.replaceFileContents(headerFull, "blah = 5", "blah = 6"); // Check that running a build again makes the source get recompiled and the binary // re-linked, but does not cause the header rules to re-run. workspace.runBuckCommand("build", target.toString()).assertSuccess(); buildLog = workspace.getBuildLog(); assertEquals( ImmutableSet.of( headerSymlinkTreeTarget, aggregatedDepsTarget, compileTarget, binaryTarget, target), buildLog.getAllTargets()); buildLog.assertTargetHadMatchingInputRuleKey(headerSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); assertThat( buildLog.getLogEntry(binaryTarget).getSuccessType().get(), Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY))); } @Test public void testSimpleCxxBinaryMissingDependencyOnCxxLibraryWithHeader() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckCommand("build", "//foo:binary_without_dep").assertFailure(); } @Test public void testSimpleCxxBinaryWithDependencyOnCxxLibraryWithHeader() throws IOException, InterruptedException { Assume.assumeFalse("Test should be modified for sandboxing", sandboxSources); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); // Setup variables pointing to the sources and targets of the top-level binary rule. CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(workspace.asCell().getBuckConfig()); CxxPlatform cxxPlatform = CxxPlatformUtils.build(cxxBuckConfig); BuildTarget target = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:binary_with_dep"); CxxSourceRuleFactory cxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), target, cxxPlatform, cxxBuckConfig); BuildTarget binaryTarget = CxxDescriptionEnhancer.createCxxLinkTarget( target, Optional.<LinkerMapMode>empty()); String sourceName = "foo.cpp"; BuildTarget compileTarget = cxxSourceRuleFactory.createCompileBuildTarget(sourceName); BuildTarget headerSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( target, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget aggregatedDepsTarget = cxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); // Setup variables pointing to the sources and targets of the library dep. BuildTarget depTarget = BuildTargetFactory.newInstance(workspace.getDestPath(), "//foo:library_with_header"); CxxSourceRuleFactory depCxxSourceRuleFactory = CxxSourceRuleFactoryHelper.of( workspace.getDestPath(), depTarget, cxxPlatform, cxxBuckConfig); String depSourceName = "bar.cpp"; String depSourceFull = "foo/" + depSourceName; String depHeaderName = "bar.h"; String depHeaderFull = "foo/" + depHeaderName; BuildTarget depCompileTarget = depCxxSourceRuleFactory.createCompileBuildTarget(depSourceName); BuildTarget depHeaderSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depTarget, HeaderVisibility.PRIVATE, cxxPlatform.getFlavor()); BuildTarget depHeaderExportedSymlinkTreeTarget = CxxDescriptionEnhancer.createHeaderSymlinkTreeTarget( depTarget, HeaderVisibility.PUBLIC, CxxPlatformUtils.getHeaderModeForDefaultPlatform(tmp.getRoot()).getFlavor()); BuildTarget depSandboxTarget = CxxDescriptionEnhancer.createSandboxSymlinkTreeTarget( depTarget, cxxPlatform.getFlavor() ); BuildTarget depArchiveTarget = CxxDescriptionEnhancer.createStaticLibraryBuildTarget( depTarget, cxxPlatform.getFlavor(), CxxSourceRuleFactory.PicType.PDC); BuildTarget depAggregatedDepsTarget = depCxxSourceRuleFactory.createAggregatedPreprocessDepsBuildTarget(); ImmutableList.Builder<BuildTarget> builder = ImmutableList.builder(); builder.add( depAggregatedDepsTarget, depHeaderSymlinkTreeTarget, depHeaderExportedSymlinkTreeTarget, depCompileTarget, depArchiveTarget, depTarget, aggregatedDepsTarget, headerSymlinkTreeTarget, compileTarget, binaryTarget, target); if (cxxBuckConfig.sandboxSources()) { builder.add(depSandboxTarget); } // Do a clean build, verify that it succeeds, and check that all expected targets built // successfully. workspace.runBuckCommand("build", target.toString()).assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); assertThat( buildLog.getAllTargets(), containsInAnyOrder(builder.build().toArray(new BuildTarget[]{}))); buildLog.assertTargetBuiltLocally(depHeaderSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(depCompileTarget.toString()); buildLog.assertTargetBuiltLocally(depArchiveTarget.toString()); buildLog.assertTargetBuiltLocally(depTarget.toString()); buildLog.assertTargetBuiltLocally(headerSymlinkTreeTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); buildLog.assertTargetBuiltLocally(binaryTarget.toString()); buildLog.assertTargetBuiltLocally(target.toString()); // Clear for new build. workspace.resetBuildLogFile(); // Update the source file. workspace.replaceFileContents(depHeaderFull, "int x", "int y"); // Check that running a build again makes the source get recompiled and the binary // re-linked, but does not cause the header rules to re-run. workspace.runBuckCommand("build", target.toString()).assertSuccess(); buildLog = workspace.getBuildLog(); builder = ImmutableList.builder(); builder.add( depAggregatedDepsTarget, depCompileTarget, depArchiveTarget, depTarget, depHeaderSymlinkTreeTarget, depHeaderExportedSymlinkTreeTarget, headerSymlinkTreeTarget, aggregatedDepsTarget, compileTarget, binaryTarget, target); if (cxxBuckConfig.sandboxSources()) { builder.add(depSandboxTarget); } assertThat( buildLog.getAllTargets(), containsInAnyOrder(builder.build().toArray(new BuildTarget[]{}))); buildLog.assertTargetBuiltLocally(depAggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(depCompileTarget.toString()); buildLog.assertTargetHadMatchingInputRuleKey(depArchiveTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depHeaderSymlinkTreeTarget.toString()); buildLog.assertTargetHadMatchingInputRuleKey(depHeaderExportedSymlinkTreeTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(headerSymlinkTreeTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depTarget.toString()); buildLog.assertTargetBuiltLocally(aggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(compileTarget.toString()); assertThat( buildLog.getLogEntry(binaryTarget).getSuccessType().get(), Matchers.not(Matchers.equalTo(BuildRuleSuccessType.MATCHING_RULE_KEY))); // Clear for new build. workspace.resetBuildLogFile(); // Update the source file. workspace.replaceFileContents(depSourceFull, "x + 5", "x + 6"); // Check that running a build again makes the source get recompiled and the binary // re-linked, but does not cause the header rules to re-run. workspace.runBuckCommand("build", target.toString()).assertSuccess(); buildLog = workspace.getBuildLog(); builder = ImmutableList.builder(); builder.add( depAggregatedDepsTarget, depCompileTarget, depArchiveTarget, depTarget, compileTarget, binaryTarget, target); if (cxxBuckConfig.sandboxSources()) { builder.add(depSandboxTarget); } assertThat( buildLog.getAllTargets(), containsInAnyOrder(builder.build().toArray(new BuildTarget[]{}))); buildLog.assertTargetHadMatchingRuleKey(depAggregatedDepsTarget.toString()); buildLog.assertTargetBuiltLocally(depCompileTarget.toString()); buildLog.assertTargetBuiltLocally(depArchiveTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(depTarget.toString()); buildLog.assertTargetHadMatchingRuleKey(compileTarget.toString()); buildLog.assertTargetBuiltLocally(binaryTarget.toString()); } @Test public void testCxxBinaryDepfileBuildWithChangedHeader() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "cxx_binary_depfile_build_with_changed_header", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", "//:bin"); result.assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally("//:bin#binary"); buildLog.assertTargetBuiltLocally("//:bin#compile-" + sanitize("bin.c.o") + ",default"); buildLog.assertTargetBuiltLocally("//:lib1#default,static"); workspace.resetBuildLogFile(); workspace.replaceFileContents("lib2.h", "hello", "world"); result = workspace.runBuckCommand("build", "//:bin"); result.assertSuccess(); buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally("//:bin#binary"); buildLog.assertTargetHadMatchingDepfileRuleKey( "//:bin#compile-" + sanitize("bin.c.o") + ",default"); buildLog.assertTargetBuiltLocally("//:lib1#default,static"); } @Test public void testCxxBinaryDepfileBuildWithAddedHeader() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "cxx_binary_depfile_build_with_added_header", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", "//:bin"); result.assertSuccess(); BuckBuildLog buildLog = workspace.getBuildLog(); buildLog.assertTargetBuiltLocally("//:bin#binary"); buildLog.assertTargetBuiltLocally("//:bin#compile-" + sanitize("bin.c.o") + ",default"); buildLog.assertTargetBuiltLocally("//:lib1#default,static"); workspace.resetBuildLogFile(); workspace.replaceFileContents("BUCK", "['lib1.h']", "['lib1.h', 'lib2.h']"); result = workspace.runBuckCommand("build", "//:bin"); result.assertSuccess(); buildLog = workspace.getBuildLog(); buildLog.assertTargetHadMatchingInputRuleKey("//:bin#binary"); buildLog.assertTargetHadMatchingDepfileRuleKey( "//:bin#compile-" + sanitize("bin.c.o") + ",default"); buildLog.assertTargetHadMatchingInputRuleKey("//:lib1#default,static"); } @Test public void testCxxBinaryWithGeneratedSourceAndHeader() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckCommand("build", "//foo:binary_without_dep").assertFailure(); } @Test public void testHeaderNamespace() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "header_namespace", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckCommand("build", "//:test").assertSuccess(); } @Test public void resolveHeadersBehindSymlinkTreesInError() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "resolved", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); workspace.writeContentsToPath("#invalid_pragma", "lib2.h"); BuildTarget target = BuildTargetFactory.newInstance("//:bin"); ProjectWorkspace.ProcessResult result = workspace.runBuckCommand("build", target.toString()); result.assertFailure(); // Verify that the preprocessed source contains no references to the symlink tree used to // setup the headers. String error = result.getStderr(); assertThat( error, Matchers.not( Matchers.containsString(filesystem.getBuckPaths().getScratchDir().toString()))); assertThat( error, Matchers.not(Matchers.containsString(filesystem.getBuckPaths().getGenDir().toString()))); assertThat(error, Matchers.containsString("In file included from lib1.h:1")); assertThat(error, Matchers.containsString("from bin.h:1")); assertThat(error, Matchers.containsString("from bin.cpp:1:")); assertThat(error, Matchers.containsString("lib2.h:1:2: error: invalid preprocessing")); } @Test public void ndkCxxPlatforms() throws IOException { AssumeAndroidPlatform.assumeNdkIsAvailable(); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.writeContentsToPath( "[ndk]\n" + " gcc_version = 4.9\n" + " cpu_abis = arm, armv7, arm64, x86\n" + " app_platform = android-21\n", ".buckconfig"); workspace.runBuckCommand("build", "//foo:simple#android-arm").assertSuccess(); workspace.runBuckCommand("build", "//foo:simple#android-armv7").assertSuccess(); workspace.runBuckCommand("build", "//foo:simple#android-arm64").assertSuccess(); workspace.runBuckCommand("build", "//foo:simple#android-x86").assertSuccess(); } @Test public void linkerFlags() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "linker_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild("//:binary_with_linker_flag").assertFailure("--bad-flag"); workspace.runBuckBuild("//:binary_with_library_dep").assertSuccess(); workspace.runBuckBuild("//:binary_with_exported_flags_library_dep").assertFailure("--bad-flag"); workspace.runBuckBuild("//:binary_with_prebuilt_library_dep").assertFailure("--bad-flag"); // Build binary that has unresolved symbols. Normally this would fail, but should work // with the proper linker flag. switch (Platform.detect()) { case MACOS: workspace.runBuckBuild("//:binary_with_unresolved_symbols_macos").assertSuccess(); break; case LINUX: workspace.runBuckBuild("//:binary_with_unresolved_symbols_linux").assertSuccess(); break; // $CASES-OMITTED$ default: break; } } private void platformLinkerFlags(ProjectWorkspace workspace, String target) throws IOException { workspace.runBuckBuild("//:binary_matches_default_exactly_" + target).assertSuccess(); workspace.runBuckBuild("//:binary_matches_default_" + target).assertSuccess(); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary_no_match_" + target); result.assertFailure(); assertThat(result.getStderr(), Matchers.containsString("reference")); workspace.runBuckBuild("//:binary_with_library_matches_default_" + target).assertSuccess(); workspace.runBuckBuild("//:binary_with_prebuilt_library_matches_default_" + target) .assertSuccess(); } @Test public void platformLinkerFlags() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "platform_linker_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); // Build binary that has unresolved symbols. Normally this would fail, but should work // with the proper linker flag. switch (Platform.detect()) { case MACOS: platformLinkerFlags(workspace, "macos"); break; case LINUX: platformLinkerFlags(workspace, "linux"); break; // $CASES-OMITTED$ default: break; } } @Test public void perFileFlagsUsedForPreprocessing() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "preprocessing_per_file_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:bin"); result.assertSuccess(); } @Test public void correctPerFileFlagsUsedForCompilation() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "compiling_per_file_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:working-bin"); result.assertSuccess(); } @Test public void incorrectPerFileFlagsUsedForCompilation() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "compiling_per_file_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:broken-bin"); result.assertFailure(); } @Test public void platformPreprocessorFlags() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "platform_preprocessor_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess(); workspace.runBuckBuild("//:binary_matches_default").assertSuccess(); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary_no_match"); result.assertFailure(); assertThat(result.getStderr(), Matchers.containsString("#error")); workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess(); } @Test public void platformCompilerFlags() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "platform_compiler_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig"); workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess(); workspace.runBuckBuild("//:binary_matches_default").assertSuccess(); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary_no_match"); result.assertFailure(); assertThat( result.getStderr(), Matchers.allOf( Matchers.containsString("non-void"), Matchers.containsString("function"))); workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess(); } @Test public void platformHeaders() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "platform_headers", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig"); workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess(); workspace.runBuckBuild("//:binary_matches_default").assertSuccess(); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary_no_match"); result.assertFailure(); assertThat(result.getStderr(), Matchers.containsString("header.hpp")); workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess(); } @Test public void platformSources() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "platform_sources", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.writeContentsToPath("[cxx]\n cxxflags = -Wall -Werror", ".buckconfig"); workspace.runBuckBuild("//:binary_matches_default_exactly").assertSuccess(); workspace.runBuckBuild("//:binary_matches_default").assertSuccess(); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary_no_match"); result.assertFailure(); assertThat(result.getStderr(), Matchers.containsString("answer()")); workspace.runBuckBuild("//:binary_with_library_matches_default").assertSuccess(); } @Test public void buildABinaryIfACxxLibraryDepOnlyDeclaresHeaders() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "cxx_binary_headers_only", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary"); result.assertSuccess(); } @Test public void buildABinaryIfACxxBinaryTransitivelyDepOnlyDeclaresHeaders() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "cxx_binary_headers_only", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:transitive"); System.out.println(result.getStdout()); System.err.println(result.getStderr()); result.assertSuccess(); } @Test public void buildBinaryWithSharedDependencies() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "shared_library", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary"); result.assertSuccess(); } @Test public void buildBinaryWithPerFileFlags() throws IOException { assumeThat(Platform.detect(), is(Platform.MACOS)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "per_file_flags", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult result = workspace.runBuckBuild("//:binary"); result.assertSuccess(); } @Test public void runBinaryUsingSharedLinkStyle() throws IOException { assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "shared_link_style", tmp); workspace.setUp(); workspace.runBuckCommand("run", "//:bar").assertSuccess(); } @Test public void genruleUsingBinaryUsingSharedLinkStyle() throws IOException { assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "shared_link_style", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild("//:gen").assertSuccess(); } @Test public void shBinaryAsLinker() throws IOException { assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "step_test", tmp); workspace.setUp(); workspace.runBuckBuild("-c", "cxx.ld=//:cxx", "//:binary_with_unused_header").assertSuccess(); } @Test public void buildBinaryUsingStaticPicLinkStyle() throws IOException { assumeThat(Platform.detect(), oneOf(Platform.LINUX, Platform.MACOS)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "static_pic_link_style", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckCommand( "build", // This should only work (on some architectures) if PIC was used to build all included // object files. "--config", "cxx.cxxldflags=-shared", "//:bar") .assertSuccess(); } @Test public void testStrippedBinaryProducesBothUnstrippedAndStrippedOutputs() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); BuildTarget unstrippedTarget = BuildTargetFactory.newInstance("//:test"); BuildTarget strippedTarget = unstrippedTarget.withAppendedFlavors( StripStyle.DEBUGGING_SYMBOLS.getFlavor()); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "header_namespace", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); workspace.runBuckCommand( "build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName()).assertSuccess(); Path strippedPath = workspace.getPath(BuildTargets.getGenPath( filesystem, strippedTarget.withAppendedFlavors(CxxStrip.RULE_FLAVOR), "%s")); Path unstrippedPath = workspace.getPath(BuildTargets.getGenPath( filesystem, unstrippedTarget, "%s")); String strippedOut = workspace.runCommand("dsymutil", "-s", strippedPath.toString()) .getStdout().orElse(""); String unstrippedOut = workspace.runCommand("dsymutil", "-s", unstrippedPath.toString()) .getStdout().orElse(""); assertThat(strippedOut, Matchers.containsStringIgnoringCase("dyld_stub_binder")); assertThat(unstrippedOut, Matchers.containsStringIgnoringCase("dyld_stub_binder")); assertThat(strippedOut, Matchers.not(Matchers.containsStringIgnoringCase("test.cpp"))); assertThat(unstrippedOut, Matchers.containsStringIgnoringCase("test.cpp")); } @Test public void testStrippedBinaryCanBeFetchedFromCacheAlone() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); BuildTarget strippedTarget = BuildTargetFactory.newInstance("//:test") .withFlavors(StripStyle.DEBUGGING_SYMBOLS.getFlavor()); BuildTarget unstrippedTarget = strippedTarget.withoutFlavors( StripStyle.FLAVOR_DOMAIN.getFlavors()); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "header_namespace", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); workspace.runBuckCommand( "build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName()).assertSuccess(); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand( "build", "--config", "cxx.cxxflags=-g", strippedTarget.getFullyQualifiedName()).assertSuccess(); Path strippedPath = workspace.getPath(BuildTargets.getGenPath( filesystem, strippedTarget.withAppendedFlavors(CxxStrip.RULE_FLAVOR), "%s")); Path unstrippedPath = workspace.getPath(BuildTargets.getGenPath(filesystem, unstrippedTarget, "%s")); assertThat(Files.exists(strippedPath), Matchers.equalTo(true)); assertThat(Files.exists(unstrippedPath), Matchers.equalTo(false)); } @Test public void testStrippedBinaryOutputDiffersFromUnstripped() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); BuildTarget unstrippedTarget = BuildTargetFactory.newInstance("//:test"); BuildTarget strippedTarget = unstrippedTarget.withFlavors( StripStyle.DEBUGGING_SYMBOLS.getFlavor()); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "header_namespace", tmp); workspace.setUp(); workspace.setupCxxSandboxing(sandboxSources); ProjectWorkspace.ProcessResult strippedResult = workspace.runBuckCommand( "targets", "--show-output", strippedTarget.getFullyQualifiedName()); strippedResult.assertSuccess(); ProjectWorkspace.ProcessResult unstrippedResult = workspace.runBuckCommand( "targets", "--show-output", unstrippedTarget.getFullyQualifiedName()); unstrippedResult.assertSuccess(); String strippedOutput = strippedResult.getStdout().split(" ")[1]; String unstrippedOutput = unstrippedResult.getStdout().split(" ")[1]; assertThat(strippedOutput, Matchers.not(Matchers.equalTo(unstrippedOutput))); } @Test public void testBuildingWithAndWithoutLinkerMap() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); BuildTarget target = BuildTargetFactory.newInstance("//:test"); BuildTarget withoutLinkerMapTarget = target .withAppendedFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor()); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "header_namespace", tmp); workspace.setUp(); ProjectFilesystem filesystem = new ProjectFilesystem(workspace.getDestPath()); workspace.runBuckCommand( "build", "--config", "cxx.cxxflags=-g", target.getFullyQualifiedName()).assertSuccess(); BuildTarget binaryWithLinkerMap = target; Path binaryWithLinkerMapPath = workspace.getPath( BuildTargets.getGenPath( filesystem, binaryWithLinkerMap, "%s")); Path linkerMapPath = workspace.getPath( BuildTargets.getGenPath( filesystem, binaryWithLinkerMap, "%s-LinkMap.txt")); assertThat(Files.exists(binaryWithLinkerMapPath), Matchers.equalTo(true)); assertThat(Files.exists(linkerMapPath), Matchers.equalTo(true)); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand( "build", "--config", "cxx.cxxflags=-g", withoutLinkerMapTarget.getFullyQualifiedName()).assertSuccess(); BuildTarget binaryWithoutLinkerMap = withoutLinkerMapTarget; Path binaryWithoutLinkerMapPath = workspace.getPath( BuildTargets.getGenPath( filesystem, binaryWithoutLinkerMap, "%s")); linkerMapPath = workspace.getPath( BuildTargets.getGenPath( filesystem, binaryWithoutLinkerMap, "%s-LinkMap.txt")); assertThat(Files.exists(binaryWithoutLinkerMapPath), Matchers.equalTo(true)); assertThat(Files.exists(linkerMapPath), Matchers.equalTo(false)); } @Test public void testDisablingLinkCaching() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild("-c", "cxx.cache_links=false", "//foo:simple").assertSuccess(); workspace.runBuckCommand("clean"); workspace.runBuckBuild("-c", "cxx.cache_links=false", "//foo:simple").assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally( CxxDescriptionEnhancer.createCxxLinkTarget( BuildTargetFactory.newInstance("//foo:simple"), Optional.<LinkerMapMode>empty()) .toString()); } @Test public void testThinArchives() throws IOException { CxxPlatform cxxPlatform = CxxPlatformUtils.build(new CxxBuckConfig(FakeBuckConfig.builder().build())); assumeTrue(cxxPlatform.getAr().supportsThinArchives()); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "simple", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild( "-c", "cxx.cache_links=false", "-c", "cxx.archive_contents=thin", "//foo:binary_with_dep") .assertSuccess(); ImmutableSortedSet<Path> initialObjects = findFiles( tmp.getRoot(), tmp.getRoot().getFileSystem().getPathMatcher("glob:**/*.o")); workspace.runBuckCommand("clean"); workspace.runBuckBuild( "-c", "cxx.cache_links=false", "-c", "cxx.archive_contents=thin", "//foo:binary_with_dep") .assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally( CxxDescriptionEnhancer .createCxxLinkTarget( BuildTargetFactory.newInstance("//foo:binary_with_dep"), Optional.<LinkerMapMode>empty()) .toString()); ImmutableSortedSet<Path> subsequentObjects = findFiles( tmp.getRoot(), tmp.getRoot().getFileSystem().getPathMatcher("glob:**/*.o")); assertThat(initialObjects, Matchers.equalTo(subsequentObjects)); } /** * Tests that, if a file has to be rebuilt, but its header dependencies do not, that the header * tree is still generated into the correct location. */ @Test public void headersShouldBeSetUpCorrectlyOnRebuild() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "cxx_binary_dep_header_tree_materialize", tmp); workspace.setUp(); workspace.enableDirCache(); workspace.setupCxxSandboxing(sandboxSources); workspace.runBuckBuild("//:bin").assertSuccess(); workspace.runBuckCommand("clean"); workspace.copyFile("bin.c.new", "bin.c"); workspace.runBuckBuild("//:bin").assertSuccess(); BuckBuildLog log = workspace.getBuildLog(); log.assertTargetBuiltLocally("//:bin#binary"); } private ImmutableSortedSet<Path> findFiles(Path root, final PathMatcher matcher) throws IOException { final ImmutableSortedSet.Builder<Path> files = ImmutableSortedSet.naturalOrder(); Files.walkFileTree( root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (matcher.matches(file)) { files.add(file); } return FileVisitResult.CONTINUE; } }); return files.build(); } }
{ "content_hash": "de8a4de2fe5bf0f033ba0a3b41e3ff48", "timestamp": "", "source": "github", "line_count": 2509, "max_line_length": 100, "avg_line_length": 42.30769230769231, "alnum_prop": 0.6973151201130475, "repo_name": "darkforestzero/buck", "id": "c07f7ea0fa1aa3bf3de53b07bd8e904cb5fc0dbd", "size": "106755", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/com/facebook/buck/cxx/CxxBinaryIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "579" }, { "name": "Batchfile", "bytes": "2093" }, { "name": "C", "bytes": "252516" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "10341" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "15018" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "6372" }, { "name": "Haskell", "bytes": "895" }, { "name": "IDL", "bytes": "128" }, { "name": "Java", "bytes": "18604983" }, { "name": "JavaScript", "bytes": "934679" }, { "name": "Kotlin", "bytes": "2079" }, { "name": "Lex", "bytes": "2595" }, { "name": "Makefile", "bytes": "1816" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "4384" }, { "name": "Objective-C", "bytes": "1171361" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Python", "bytes": "580037" }, { "name": "Roff", "bytes": "1109" }, { "name": "Rust", "bytes": "3542" }, { "name": "Scala", "bytes": "4906" }, { "name": "Shell", "bytes": "48705" }, { "name": "Smalltalk", "bytes": "4920" }, { "name": "Standard ML", "bytes": "15" }, { "name": "Swift", "bytes": "6897" }, { "name": "Thrift", "bytes": "19820" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
package channel import ( "bytes" "fmt" "reflect" "strconv" "sync" "sync/atomic" "time" proto "github.com/hyperledger/fabric-protos-go/gossip" common_utils "github.com/hyperledger/fabric/common/util" "github.com/hyperledger/fabric/gossip/api" "github.com/hyperledger/fabric/gossip/comm" "github.com/hyperledger/fabric/gossip/common" "github.com/hyperledger/fabric/gossip/discovery" "github.com/hyperledger/fabric/gossip/election" "github.com/hyperledger/fabric/gossip/filter" "github.com/hyperledger/fabric/gossip/gossip/algo" "github.com/hyperledger/fabric/gossip/gossip/msgstore" "github.com/hyperledger/fabric/gossip/gossip/pull" "github.com/hyperledger/fabric/gossip/metrics" "github.com/hyperledger/fabric/gossip/protoext" "github.com/hyperledger/fabric/gossip/util" "github.com/hyperledger/fabric/protoutil" ) const DefMsgExpirationTimeout = election.DefLeaderAliveThreshold * 10 // Config is a configuration item // of the channel store type Config struct { ID string PublishStateInfoInterval time.Duration MaxBlockCountToStore int PullPeerNum int PullInterval time.Duration RequestStateInfoInterval time.Duration BlockExpirationInterval time.Duration StateInfoCacheSweepInterval time.Duration TimeForMembershipTracker time.Duration DigestWaitTime time.Duration RequestWaitTime time.Duration ResponseWaitTime time.Duration MsgExpirationTimeout time.Duration } // GossipChannel defines an object that deals with all channel-related messages type GossipChannel interface { // Self returns a StateInfoMessage about the peer Self() *protoext.SignedGossipMessage // GetPeers returns a list of peers with metadata as published by them GetPeers() []discovery.NetworkMember // PeerFilter receives a SubChannelSelectionCriteria and returns a RoutingFilter that selects // only peer identities that match the given criteria PeerFilter(api.SubChannelSelectionCriteria) filter.RoutingFilter // IsMemberInChan checks whether the given member is eligible to be in the channel IsMemberInChan(member discovery.NetworkMember) bool // UpdateLedgerHeight updates the ledger height the peer // publishes to other peers in the channel UpdateLedgerHeight(height uint64) // UpdateChaincodes updates the chaincodes the peer publishes // to other peers in the channel UpdateChaincodes(chaincode []*proto.Chaincode) // IsOrgInChannel returns whether the given organization is in the channel IsOrgInChannel(membersOrg api.OrgIdentityType) bool // EligibleForChannel returns whether the given member should get blocks // for this channel EligibleForChannel(member discovery.NetworkMember) bool // HandleMessage processes a message sent by a remote peer HandleMessage(protoext.ReceivedMessage) // AddToMsgStore adds a given GossipMessage to the message store AddToMsgStore(msg *protoext.SignedGossipMessage) // ConfigureChannel (re)configures the list of organizations // that are eligible to be in the channel ConfigureChannel(joinMsg api.JoinChannelMessage) // LeaveChannel makes the peer leave the channel LeaveChannel() // Stop stops the channel's activity Stop() } // Adapter enables the gossipChannel // to communicate with gossipServiceImpl. type Adapter interface { Sign(msg *proto.GossipMessage) (*protoext.SignedGossipMessage, error) // GetConf returns the configuration that this GossipChannel will posses GetConf() Config // Gossip gossips a message in the channel Gossip(message *protoext.SignedGossipMessage) // Forward sends a message to the next hops Forward(message protoext.ReceivedMessage) // DeMultiplex de-multiplexes an item to subscribers DeMultiplex(interface{}) // GetMembership returns the known alive peers and their information GetMembership() []discovery.NetworkMember // Lookup returns a network member, or nil if not found Lookup(PKIID common.PKIidType) *discovery.NetworkMember // Send sends a message to a list of peers Send(msg *protoext.SignedGossipMessage, peers ...*comm.RemotePeer) // ValidateStateInfoMessage returns an error if a message // hasn't been signed correctly, nil otherwise. ValidateStateInfoMessage(message *protoext.SignedGossipMessage) error // GetOrgOfPeer returns the organization ID of a given peer PKI-ID GetOrgOfPeer(pkiID common.PKIidType) api.OrgIdentityType // GetIdentityByPKIID returns an identity of a peer with a certain // pkiID, or nil if not found GetIdentityByPKIID(pkiID common.PKIidType) api.PeerIdentityType } type gossipChannel struct { Adapter sync.RWMutex shouldGossipStateInfo int32 mcs api.MessageCryptoService pkiID common.PKIidType selfOrg api.OrgIdentityType stopChan chan struct{} selfStateInfoMsg *proto.GossipMessage selfStateInfoSignedMsg *protoext.SignedGossipMessage orgs []api.OrgIdentityType joinMsg api.JoinChannelMessage blockMsgStore msgstore.MessageStore stateInfoMsgStore *stateInfoCache leaderMsgStore msgstore.MessageStore chainID common.ChannelID blocksPuller pull.Mediator logger util.Logger stateInfoPublishScheduler *time.Ticker stateInfoRequestScheduler *time.Ticker memFilter *membershipFilter ledgerHeight uint64 incTime uint64 leftChannel int32 membershipTracker *membershipTracker } type membershipFilter struct { adapter Adapter *gossipChannel } // GetMembership returns the known alive peers and their information func (mf *membershipFilter) GetMembership() []discovery.NetworkMember { if mf.hasLeftChannel() { return nil } var members []discovery.NetworkMember for _, mem := range mf.adapter.GetMembership() { if mf.eligibleForChannelAndSameOrg(mem) { members = append(members, mem) } } return members } // NewGossipChannel creates a new GossipChannel func NewGossipChannel(pkiID common.PKIidType, org api.OrgIdentityType, mcs api.MessageCryptoService, channelID common.ChannelID, adapter Adapter, joinMsg api.JoinChannelMessage, metrics *metrics.MembershipMetrics, logger util.Logger) GossipChannel { gc := &gossipChannel{ incTime: uint64(time.Now().UnixNano()), selfOrg: org, pkiID: pkiID, mcs: mcs, Adapter: adapter, stopChan: make(chan struct{}, 1), shouldGossipStateInfo: int32(0), stateInfoPublishScheduler: time.NewTicker(adapter.GetConf().PublishStateInfoInterval), stateInfoRequestScheduler: time.NewTicker(adapter.GetConf().RequestStateInfoInterval), orgs: []api.OrgIdentityType{}, chainID: channelID, } if logger == nil { gc.logger = util.GetLogger(util.ChannelLogger, adapter.GetConf().ID) } else { gc.logger = logger } gc.memFilter = &membershipFilter{adapter: gc.Adapter, gossipChannel: gc} comparator := protoext.NewGossipMessageComparator(adapter.GetConf().MaxBlockCountToStore) gc.blocksPuller = gc.createBlockPuller() seqNumFromMsg := func(m interface{}) string { return fmt.Sprintf("%d", m.(*protoext.SignedGossipMessage).GetDataMsg().Payload.SeqNum) } gc.blockMsgStore = msgstore.NewMessageStoreExpirable(comparator, func(m interface{}) { gc.logger.Debugf("Removing %s from the message store", seqNumFromMsg(m)) gc.blocksPuller.Remove(seqNumFromMsg(m)) }, gc.GetConf().BlockExpirationInterval, nil, nil, func(m interface{}) { gc.logger.Debugf("Removing %s from the message store", seqNumFromMsg(m)) gc.blocksPuller.Remove(seqNumFromMsg(m)) }) hashPeerExpiredInMembership := func(o interface{}) bool { pkiID := o.(*protoext.SignedGossipMessage).GetStateInfo().PkiId return gc.Lookup(pkiID) == nil } verifyStateInfoMsg := func(msg *protoext.SignedGossipMessage, orgs ...api.OrgIdentityType) bool { si := msg.GetStateInfo() // No point in verifying ourselves if bytes.Equal(gc.pkiID, si.PkiId) { return true } peerIdentity := adapter.GetIdentityByPKIID(si.PkiId) if len(peerIdentity) == 0 { gc.logger.Warning("Identity for peer", si.PkiId, "doesn't exist") return false } isOrgInChan := func(org api.OrgIdentityType) bool { if len(orgs) == 0 { if !gc.IsOrgInChannel(org) { return false } } else { found := false for _, chanMember := range orgs { if bytes.Equal(chanMember, org) { found = true break } } if !found { return false } } return true } org := gc.GetOrgOfPeer(si.PkiId) if !isOrgInChan(org) { gc.logger.Warning("peer", peerIdentity, "'s organization(", string(org), ") isn't in the channel", string(channelID)) return false } if err := gc.mcs.VerifyByChannel(channelID, peerIdentity, msg.Signature, msg.Payload); err != nil { gc.logger.Warningf("Peer %v isn't eligible for channel %s : %+v", peerIdentity, string(channelID), err) return false } return true } gc.stateInfoMsgStore = newStateInfoCache(gc.GetConf().StateInfoCacheSweepInterval, hashPeerExpiredInMembership, verifyStateInfoMsg) // Setup a plain state info message at startup, just to have all required fields populated // when this gossip channel is created gc.updateProperties(1, nil, false) gc.setupSignedStateInfoMessage() ttl := adapter.GetConf().MsgExpirationTimeout pol := protoext.NewGossipMessageComparator(0) gc.leaderMsgStore = msgstore.NewMessageStoreExpirable(pol, msgstore.Noop, ttl, nil, nil, nil) gc.ConfigureChannel(joinMsg) // Periodically publish state info go gc.periodicalInvocation(gc.publishStateInfo, gc.stateInfoPublishScheduler.C) // Periodically request state info go gc.periodicalInvocation(gc.requestStateInfo, gc.stateInfoRequestScheduler.C) ticker := time.NewTicker(gc.GetConf().TimeForMembershipTracker) gc.membershipTracker = &membershipTracker{ getPeersToTrack: gc.GetPeers, report: gc.reportMembershipChanges, stopChan: make(chan struct{}, 1), tickerChannel: ticker.C, metrics: metrics, chainID: channelID, } go gc.membershipTracker.trackMembershipChanges() return gc } func (gc *gossipChannel) reportMembershipChanges(input ...interface{}) { args := []interface{}{fmt.Sprintf("[%s]", string(gc.chainID))} args = append(args, input...) gc.logger.Info(args) } // Stop stop the channel operations func (gc *gossipChannel) Stop() { close(gc.stopChan) close(gc.membershipTracker.stopChan) gc.blocksPuller.Stop() gc.stateInfoPublishScheduler.Stop() gc.stateInfoRequestScheduler.Stop() gc.leaderMsgStore.Stop() gc.stateInfoMsgStore.Stop() gc.blockMsgStore.Stop() } func (gc *gossipChannel) periodicalInvocation(fn func(), c <-chan time.Time) { for { select { case <-c: fn() case <-gc.stopChan: return } } } // Self returns a StateInfoMessage about the peer func (gc *gossipChannel) Self() *protoext.SignedGossipMessage { gc.RLock() defer gc.RUnlock() return gc.selfStateInfoSignedMsg } // LeaveChannel makes the peer leave the channel func (gc *gossipChannel) LeaveChannel() { gc.Lock() defer gc.Unlock() atomic.StoreInt32(&gc.leftChannel, 1) var chaincodes []*proto.Chaincode var height uint64 if prevMsg := gc.selfStateInfoMsg; prevMsg != nil { chaincodes = prevMsg.GetStateInfo().Properties.Chaincodes height = prevMsg.GetStateInfo().Properties.LedgerHeight } gc.updateProperties(height, chaincodes, true) atomic.StoreInt32(&gc.shouldGossipStateInfo, int32(1)) } func (gc *gossipChannel) hasLeftChannel() bool { return atomic.LoadInt32(&gc.leftChannel) == 1 } // GetPeers returns a list of peers with metadata as published by them func (gc *gossipChannel) GetPeers() []discovery.NetworkMember { var members []discovery.NetworkMember if gc.hasLeftChannel() { return members } for _, member := range gc.GetMembership() { if !gc.EligibleForChannel(member) { continue } stateInf := gc.stateInfoMsgStore.MsgByID(member.PKIid) if stateInf == nil { continue } props := stateInf.GetStateInfo().Properties if props != nil && props.LeftChannel { continue } member.Properties = stateInf.GetStateInfo().Properties member.Envelope = stateInf.Envelope members = append(members, member) } return members } func (gc *gossipChannel) requestStateInfo() { req, err := gc.createStateInfoRequest() if err != nil { gc.logger.Warningf("Failed creating SignedGossipMessage: %+v", err) return } endpoints := filter.SelectPeers(gc.GetConf().PullPeerNum, gc.GetMembership(), gc.IsMemberInChan) gc.Send(req, endpoints...) } func (gc *gossipChannel) eligibleForChannelAndSameOrg(member discovery.NetworkMember) bool { sameOrg := func(networkMember discovery.NetworkMember) bool { return bytes.Equal(gc.GetOrgOfPeer(networkMember.PKIid), gc.selfOrg) } return filter.CombineRoutingFilters(gc.EligibleForChannel, sameOrg)(member) } func (gc *gossipChannel) publishStateInfo() { if atomic.LoadInt32(&gc.shouldGossipStateInfo) == int32(0) { return } if len(gc.GetMembership()) == 0 { gc.logger.Debugf("Empty membership, no one to publish state info to") return } gc.publishSignedStateInfoMessage() atomic.StoreInt32(&gc.shouldGossipStateInfo, int32(0)) } func (gc *gossipChannel) publishSignedStateInfoMessage() { stateInfoMsg, err := gc.setupSignedStateInfoMessage() if err != nil { gc.logger.Errorf("Failed creating signed state info message: %v", err) return } gc.stateInfoMsgStore.Add(stateInfoMsg) gc.Gossip(stateInfoMsg) } func (gc *gossipChannel) setupSignedStateInfoMessage() (*protoext.SignedGossipMessage, error) { gc.RLock() msg := gc.selfStateInfoMsg gc.RUnlock() stateInfoMsg, err := gc.Sign(msg) if err != nil { gc.logger.Error("Failed signing message:", err) return nil, err } gc.Lock() gc.selfStateInfoSignedMsg = stateInfoMsg gc.Unlock() return stateInfoMsg, nil } func (gc *gossipChannel) createBlockPuller() pull.Mediator { conf := pull.Config{ MsgType: proto.PullMsgType_BLOCK_MSG, Channel: []byte(gc.chainID), ID: gc.GetConf().ID, PeerCountToSelect: gc.GetConf().PullPeerNum, PullInterval: gc.GetConf().PullInterval, Tag: proto.GossipMessage_CHAN_AND_ORG, PullEngineConfig: algo.PullEngineConfig{ DigestWaitTime: gc.GetConf().DigestWaitTime, RequestWaitTime: gc.GetConf().RequestWaitTime, ResponseWaitTime: gc.GetConf().ResponseWaitTime, }, } seqNumFromMsg := func(msg *protoext.SignedGossipMessage) string { dataMsg := msg.GetDataMsg() if dataMsg == nil || dataMsg.Payload == nil { gc.logger.Warning("Non-data block or with no payload") return "" } return fmt.Sprintf("%d", dataMsg.Payload.SeqNum) } adapter := &pull.PullAdapter{ Sndr: gc, MemSvc: gc.memFilter, IdExtractor: seqNumFromMsg, MsgCons: func(msg *protoext.SignedGossipMessage) { gc.DeMultiplex(msg) }, } adapter.IngressDigFilter = func(digestMsg *proto.DataDigest) *proto.DataDigest { gc.RLock() height := gc.ledgerHeight gc.RUnlock() digests := digestMsg.Digests digestMsg.Digests = nil for i := range digests { seqNum, err := strconv.ParseUint(string(digests[i]), 10, 64) if err != nil { gc.logger.Warningf("Can't parse digest %s : %+v", digests[i], err) continue } if seqNum >= height { digestMsg.Digests = append(digestMsg.Digests, digests[i]) } } return digestMsg } return pull.NewPullMediator(conf, adapter) } // IsMemberInChan checks whether the given member is eligible to be in the channel func (gc *gossipChannel) IsMemberInChan(member discovery.NetworkMember) bool { org := gc.GetOrgOfPeer(member.PKIid) if org == nil { return false } return gc.IsOrgInChannel(org) } // PeerFilter receives a SubChannelSelectionCriteria and returns a RoutingFilter that selects // only peer identities that match the given criteria func (gc *gossipChannel) PeerFilter(messagePredicate api.SubChannelSelectionCriteria) filter.RoutingFilter { return func(member discovery.NetworkMember) bool { peerIdentity := gc.GetIdentityByPKIID(member.PKIid) if len(peerIdentity) == 0 { return false } msg := gc.stateInfoMsgStore.MembershipStore.MsgByID(member.PKIid) if msg == nil { return false } return messagePredicate(api.PeerSignature{ Message: msg.Payload, Signature: msg.Signature, PeerIdentity: peerIdentity, }) } } // IsOrgInChannel returns whether the given organization is in the channel func (gc *gossipChannel) IsOrgInChannel(membersOrg api.OrgIdentityType) bool { gc.RLock() defer gc.RUnlock() for _, orgOfChan := range gc.orgs { if bytes.Equal(orgOfChan, membersOrg) { return true } } return false } // EligibleForChannel returns whether the given member should get blocks // for this channel func (gc *gossipChannel) EligibleForChannel(member discovery.NetworkMember) bool { peerIdentity := gc.GetIdentityByPKIID(member.PKIid) if len(peerIdentity) == 0 { gc.logger.Warning("Identity for peer", member.PKIid, "doesn't exist") return false } msg := gc.stateInfoMsgStore.MsgByID(member.PKIid) return msg != nil } // AddToMsgStore adds a given GossipMessage to the message store func (gc *gossipChannel) AddToMsgStore(msg *protoext.SignedGossipMessage) { if protoext.IsDataMsg(msg.GossipMessage) { gc.Lock() defer gc.Unlock() added := gc.blockMsgStore.Add(msg) if added { gc.logger.Debugf("Adding %v to the block puller", msg) gc.blocksPuller.Add(msg) } } if protoext.IsStateInfoMsg(msg.GossipMessage) { gc.stateInfoMsgStore.Add(msg) } } // ConfigureChannel (re)configures the list of organizations // that are eligible to be in the channel func (gc *gossipChannel) ConfigureChannel(joinMsg api.JoinChannelMessage) { gc.Lock() defer gc.Unlock() if len(joinMsg.Members()) == 0 { gc.logger.Warning("Received join channel message with empty set of members") return } if gc.joinMsg == nil { gc.joinMsg = joinMsg } if gc.joinMsg.SequenceNumber() > (joinMsg.SequenceNumber()) { gc.logger.Warning("Already have a more updated JoinChannel message(", gc.joinMsg.SequenceNumber(), ") than", joinMsg.SequenceNumber()) return } gc.orgs = joinMsg.Members() gc.joinMsg = joinMsg gc.stateInfoMsgStore.validate(joinMsg.Members()) } // HandleMessage processes a message sent by a remote peer func (gc *gossipChannel) HandleMessage(msg protoext.ReceivedMessage) { if !gc.verifyMsg(msg) { gc.logger.Warning("Failed verifying message:", msg.GetGossipMessage().GossipMessage) return } m := msg.GetGossipMessage() if !protoext.IsChannelRestricted(m.GossipMessage) { gc.logger.Warning("Got message", msg.GetGossipMessage(), "but it's not a per-channel message, discarding it") return } orgID := gc.GetOrgOfPeer(msg.GetConnectionInfo().ID) if len(orgID) == 0 { gc.logger.Debug("Couldn't find org identity of peer", msg.GetConnectionInfo()) return } if !gc.IsOrgInChannel(orgID) { gc.logger.Warning("Point to point message came from", msg.GetConnectionInfo(), ", org(", string(orgID), ") but it's not eligible for the channel", string(gc.chainID)) return } if protoext.IsStateInfoPullRequestMsg(m.GossipMessage) { msg.Respond(gc.createStateInfoSnapshot(orgID)) return } if protoext.IsStateInfoSnapshot(m.GossipMessage) { gc.handleStateInfSnapshot(m.GossipMessage, msg.GetConnectionInfo().ID) return } if protoext.IsDataMsg(m.GossipMessage) || protoext.IsStateInfoMsg(m.GossipMessage) { added := false if protoext.IsDataMsg(m.GossipMessage) { if m.GetDataMsg().Payload == nil { gc.logger.Warning("Payload is empty, got it from", msg.GetConnectionInfo().ID) return } // Would this block go into the message store if it was verified? if !gc.blockMsgStore.CheckValid(msg.GetGossipMessage()) { return } if !gc.verifyBlock(m.GossipMessage, msg.GetConnectionInfo().ID) { gc.logger.Warning("Failed verifying block", m.GetDataMsg().Payload.SeqNum) return } gc.Lock() added = gc.blockMsgStore.Add(msg.GetGossipMessage()) if added { gc.logger.Debugf("Adding %v to the block puller", msg.GetGossipMessage()) gc.blocksPuller.Add(msg.GetGossipMessage()) } gc.Unlock() } else { // StateInfoMsg verification should be handled in a layer above // since we don't have access to the id mapper here added = gc.stateInfoMsgStore.Add(msg.GetGossipMessage()) } if added { // Forward the message gc.Forward(msg) // DeMultiplex to local subscribers gc.DeMultiplex(m) } return } if protoext.IsPullMsg(m.GossipMessage) && protoext.GetPullMsgType(m.GossipMessage) == proto.PullMsgType_BLOCK_MSG { if gc.hasLeftChannel() { gc.logger.Info("Received Pull message from", msg.GetConnectionInfo().Endpoint, "but left the channel", string(gc.chainID)) return } // If we don't have a StateInfo message from the peer, // no way of validating its eligibility in the channel. if gc.stateInfoMsgStore.MsgByID(msg.GetConnectionInfo().ID) == nil { gc.logger.Debug("Don't have StateInfo message of peer", msg.GetConnectionInfo()) return } if !gc.eligibleForChannelAndSameOrg(discovery.NetworkMember{PKIid: msg.GetConnectionInfo().ID}) { gc.logger.Warning(msg.GetConnectionInfo(), "isn't eligible for pulling blocks of", string(gc.chainID)) return } if protoext.IsDataUpdate(m.GossipMessage) { // Iterate over the envelopes, and filter out blocks // that we already have in the blockMsgStore, or blocks that // are too far in the past. var msgs []*protoext.SignedGossipMessage var items []*proto.Envelope filteredEnvelopes := []*proto.Envelope{} for _, item := range m.GetDataUpdate().Data { gMsg, err := protoext.EnvelopeToGossipMessage(item) if err != nil { gc.logger.Warningf("Data update contains an invalid message: %+v", err) return } if !bytes.Equal(gMsg.Channel, []byte(gc.chainID)) { gc.logger.Warning("DataUpdate message contains item with channel", gMsg.Channel, "but should be", gc.chainID) return } // Would this block go into the message store if it was verified? if !gc.blockMsgStore.CheckValid(gMsg) { continue } if !gc.verifyBlock(gMsg.GossipMessage, msg.GetConnectionInfo().ID) { return } msgs = append(msgs, gMsg) items = append(items, item) } gc.Lock() defer gc.Unlock() for i, gMsg := range msgs { item := items[i] added := gc.blockMsgStore.Add(gMsg) if !added { // If this block doesn't need to be added, it means it either already // exists in memory or that it is too far in the past continue } filteredEnvelopes = append(filteredEnvelopes, item) } // Replace the update message with just the blocks that should be processed m.GetDataUpdate().Data = filteredEnvelopes } gc.blocksPuller.HandleMessage(msg) } if protoext.IsLeadershipMsg(m.GossipMessage) { connInfo := msg.GetConnectionInfo() senderOrg := gc.GetOrgOfPeer(connInfo.ID) if !bytes.Equal(gc.selfOrg, senderOrg) { gc.logger.Warningf("Received leadership message from %s that belongs to a foreign organization %s", connInfo.Endpoint, string(senderOrg)) return } msgCreatorOrg := gc.GetOrgOfPeer(m.GetLeadershipMsg().PkiId) if !bytes.Equal(gc.selfOrg, msgCreatorOrg) { gc.logger.Warningf("Received leadership message created by a foreign organization %s", string(msgCreatorOrg)) return } // Handling leadership message added := gc.leaderMsgStore.Add(m) if added { gc.DeMultiplex(m) } } } func (gc *gossipChannel) handleStateInfSnapshot(m *proto.GossipMessage, sender common.PKIidType) { chanName := string(gc.chainID) for _, envelope := range m.GetStateSnapshot().Elements { stateInf, err := protoext.EnvelopeToGossipMessage(envelope) if err != nil { gc.logger.Warningf("Channel %s : StateInfo snapshot contains an invalid message: %+v", chanName, err) return } if !protoext.IsStateInfoMsg(stateInf.GossipMessage) { gc.logger.Warning("Channel", chanName, ": Element of StateInfoSnapshot isn't a StateInfoMessage:", stateInf, "message sent from", sender) return } si := stateInf.GetStateInfo() orgID := gc.GetOrgOfPeer(si.PkiId) if orgID == nil { gc.logger.Debug("Channel", chanName, ": Couldn't find org identity of peer", string(si.PkiId), "message sent from", string(sender)) return } if !gc.IsOrgInChannel(orgID) { gc.logger.Warning("Channel", chanName, ": Peer", stateInf.GetStateInfo().PkiId, "is not in an eligible org, can't process a stateInfo from it, sent from", sender) return } expectedMAC := GenerateMAC(si.PkiId, gc.chainID) if !bytes.Equal(si.Channel_MAC, expectedMAC) { gc.logger.Warning("Channel", chanName, ": StateInfo message", stateInf, ", has an invalid MAC. Expected", expectedMAC, ", got", si.Channel_MAC, ", sent from", sender) return } err = gc.ValidateStateInfoMessage(stateInf) if err != nil { gc.logger.Warningf("Channel %s: Failed validating state info message: %v sent from %v : %+v", chanName, stateInf, sender, err) return } if gc.Lookup(si.PkiId) == nil { // Skip StateInfo messages that belong to peers // that have been expired continue } gc.stateInfoMsgStore.Add(stateInf) } } func (gc *gossipChannel) verifyBlock(msg *proto.GossipMessage, sender common.PKIidType) bool { if !protoext.IsDataMsg(msg) { gc.logger.Warning("Received from ", sender, "a DataUpdate message that contains a non-block GossipMessage:", msg) return false } payload := msg.GetDataMsg().Payload if payload == nil { gc.logger.Warning("Received empty payload from", sender) return false } seqNum := payload.SeqNum rawBlock := payload.Data block, err := protoutil.UnmarshalBlock(rawBlock) if err != nil { gc.logger.Warningf("Received improperly encoded block from %v in DataUpdate: %+v", sender, err) return false } err = gc.mcs.VerifyBlock(msg.Channel, seqNum, block) if err != nil { gc.logger.Warningf("Received fabricated block from %v in DataUpdate: %+v", sender, err) return false } return true } func (gc *gossipChannel) createStateInfoSnapshot(requestersOrg api.OrgIdentityType) *proto.GossipMessage { sameOrg := bytes.Equal(gc.selfOrg, requestersOrg) rawElements := gc.stateInfoMsgStore.Get() elements := []*proto.Envelope{} for _, rawEl := range rawElements { msg := rawEl.(*protoext.SignedGossipMessage) orgOfCurrentMsg := gc.GetOrgOfPeer(msg.GetStateInfo().PkiId) // If we're in the same org as the requester, or the message belongs to a foreign org // don't do any filtering if sameOrg || !bytes.Equal(orgOfCurrentMsg, gc.selfOrg) { elements = append(elements, msg.Envelope) continue } // Else, the requester is in a different org, so disclose only StateInfo messages that their // corresponding AliveMessages have external endpoints if netMember := gc.Lookup(msg.GetStateInfo().PkiId); netMember == nil || netMember.Endpoint == "" { continue } elements = append(elements, msg.Envelope) } return &proto.GossipMessage{ Channel: gc.chainID, Tag: proto.GossipMessage_CHAN_OR_ORG, Nonce: 0, Content: &proto.GossipMessage_StateSnapshot{ StateSnapshot: &proto.StateInfoSnapshot{ Elements: elements, }, }, } } func (gc *gossipChannel) verifyMsg(msg protoext.ReceivedMessage) bool { if msg == nil { gc.logger.Warning("Messsage is nil") return false } m := msg.GetGossipMessage() if m == nil { gc.logger.Warning("Message content is empty") return false } if msg.GetConnectionInfo().ID == nil { gc.logger.Warning("Message has nil PKI-ID") return false } if protoext.IsStateInfoMsg(m.GossipMessage) { si := m.GetStateInfo() expectedMAC := GenerateMAC(si.PkiId, gc.chainID) if !bytes.Equal(expectedMAC, si.Channel_MAC) { gc.logger.Warning("Message contains wrong channel MAC(", si.Channel_MAC, "), expected", expectedMAC) return false } return true } if protoext.IsStateInfoPullRequestMsg(m.GossipMessage) { sipr := m.GetStateInfoPullReq() expectedMAC := GenerateMAC(msg.GetConnectionInfo().ID, gc.chainID) if !bytes.Equal(expectedMAC, sipr.Channel_MAC) { gc.logger.Warning("Message contains wrong channel MAC(", sipr.Channel_MAC, "), expected", expectedMAC) return false } return true } if !bytes.Equal(m.Channel, []byte(gc.chainID)) { gc.logger.Warning("Message contains wrong channel(", m.Channel, "), expected", gc.chainID) return false } return true } func (gc *gossipChannel) createStateInfoRequest() (*protoext.SignedGossipMessage, error) { return protoext.NoopSign(&proto.GossipMessage{ Tag: proto.GossipMessage_CHAN_OR_ORG, Nonce: 0, Content: &proto.GossipMessage_StateInfoPullReq{ StateInfoPullReq: &proto.StateInfoPullRequest{ Channel_MAC: GenerateMAC(gc.pkiID, gc.chainID), }, }, }) } // UpdateLedgerHeight updates the ledger height the peer // publishes to other peers in the channel func (gc *gossipChannel) UpdateLedgerHeight(height uint64) { gc.Lock() defer gc.Unlock() var chaincodes []*proto.Chaincode var leftChannel bool if prevMsg := gc.selfStateInfoMsg; prevMsg != nil { leftChannel = prevMsg.GetStateInfo().Properties.LeftChannel chaincodes = prevMsg.GetStateInfo().Properties.Chaincodes } gc.updateProperties(height, chaincodes, leftChannel) atomic.StoreInt32(&gc.shouldGossipStateInfo, int32(1)) } // UpdateChaincodes updates the chaincodes the peer publishes // to other peers in the channel func (gc *gossipChannel) UpdateChaincodes(chaincodes []*proto.Chaincode) { // Always publish the signed state info message regardless. // We do this because we have to update our data structures // with the new chaincodes installed/instantiated, to be able to // respond to discovery requests, no matter if we see other peers // in the membership, or do not see them. defer gc.publishSignedStateInfoMessage() gc.Lock() defer gc.Unlock() var ledgerHeight uint64 = 1 var leftChannel bool if prevMsg := gc.selfStateInfoMsg; prevMsg != nil { ledgerHeight = prevMsg.GetStateInfo().Properties.LedgerHeight leftChannel = prevMsg.GetStateInfo().Properties.LeftChannel } gc.updateProperties(ledgerHeight, chaincodes, leftChannel) atomic.StoreInt32(&gc.shouldGossipStateInfo, int32(1)) } // UpdateStateInfo updates this channel's StateInfo message // that is periodically published func (gc *gossipChannel) updateStateInfo(msg *proto.GossipMessage) { gc.ledgerHeight = msg.GetStateInfo().Properties.LedgerHeight gc.selfStateInfoMsg = msg } func (gc *gossipChannel) updateProperties(ledgerHeight uint64, chaincodes []*proto.Chaincode, leftChannel bool) { stateInfMsg := &proto.StateInfo{ Channel_MAC: GenerateMAC(gc.pkiID, gc.chainID), PkiId: gc.pkiID, Timestamp: &proto.PeerTime{ IncNum: gc.incTime, SeqNum: uint64(time.Now().UnixNano()), }, Properties: &proto.Properties{ LeftChannel: leftChannel, LedgerHeight: ledgerHeight, Chaincodes: chaincodes, }, } m := &proto.GossipMessage{ Nonce: 0, Tag: proto.GossipMessage_CHAN_OR_ORG, Content: &proto.GossipMessage_StateInfo{ StateInfo: stateInfMsg, }, } gc.updateStateInfo(m) } func newStateInfoCache(sweepInterval time.Duration, hasExpired func(interface{}) bool, verifyFunc membershipPredicate) *stateInfoCache { membershipStore := util.NewMembershipStore() pol := protoext.NewGossipMessageComparator(0) s := &stateInfoCache{ verify: verifyFunc, MembershipStore: membershipStore, stopChan: make(chan struct{}), } invalidationTrigger := func(m interface{}) { pkiID := m.(*protoext.SignedGossipMessage).GetStateInfo().PkiId membershipStore.Remove(pkiID) } s.MessageStore = msgstore.NewMessageStore(pol, invalidationTrigger) go func() { for { select { case <-s.stopChan: return case <-time.After(sweepInterval): s.Purge(hasExpired) } } }() return s } // membershipPredicate receives a StateInfoMessage and optionally a slice of organization identifiers // and returns whether the peer that signed the given StateInfoMessage is eligible // to the channel or not type membershipPredicate func(msg *protoext.SignedGossipMessage, orgs ...api.OrgIdentityType) bool // stateInfoCache is actually a messageStore // that also indexes messages that are added // so that they could be extracted later type stateInfoCache struct { verify membershipPredicate *util.MembershipStore msgstore.MessageStore stopChan chan struct{} } func (cache *stateInfoCache) validate(orgs []api.OrgIdentityType) { for _, m := range cache.Get() { msg := m.(*protoext.SignedGossipMessage) if !cache.verify(msg, orgs...) { cache.delete(msg) } } } // Add attempts to add the given message to the stateInfoCache, // and if the message was added, also indexes it. // Message must be a StateInfo message. func (cache *stateInfoCache) Add(msg *protoext.SignedGossipMessage) bool { if !cache.MessageStore.CheckValid(msg) { return false } if !cache.verify(msg) { return false } added := cache.MessageStore.Add(msg) if added { pkiID := msg.GetStateInfo().PkiId cache.MembershipStore.Put(pkiID, msg) } return added } func (cache *stateInfoCache) delete(msg *protoext.SignedGossipMessage) { cache.Purge(func(o interface{}) bool { pkiID := o.(*protoext.SignedGossipMessage).GetStateInfo().PkiId return bytes.Equal(pkiID, msg.GetStateInfo().PkiId) }) cache.Remove(msg.GetStateInfo().PkiId) } func (cache *stateInfoCache) Stop() { cache.stopChan <- struct{}{} } // GenerateMAC returns a byte slice that is derived from the peer's PKI-ID // and a channel name func GenerateMAC(pkiID common.PKIidType, channelID common.ChannelID) []byte { // Hash is computed on (PKI-ID || channel ID) var preImage []byte preImage = append(preImage, []byte(pkiID)...) preImage = append(preImage, []byte(channelID)...) return common_utils.ComputeSHA256(preImage) } // membershipTracker is a struct for tracking changes in peers of the channel type membershipTracker struct { getPeersToTrack func() []discovery.NetworkMember report func(...interface{}) stopChan chan struct{} tickerChannel <-chan time.Time metrics *metrics.MembershipMetrics chainID common.ChannelID } // endpoints return all peers by their endpoints func endpoints(members discovery.Members) [][]string { var currView [][]string for _, member := range members { ep := member.Endpoint epi := member.InternalEndpoint var endPoints []string if ep != epi { endPoints = append(endPoints, ep, epi) } else { endPoints = append(endPoints, ep) } currView = append(currView, endPoints) } return currView } // checkIfPeersChanged checks which peers are offline and which are online for channel func (mt *membershipTracker) checkIfPeersChanged(prevPeers discovery.Members, currPeers discovery.Members, prevSetPeers map[string]struct{}, currSetPeers map[string]struct{}) { var currView [][]string wereInPrev := endpoints(prevPeers.Filter(func(member discovery.NetworkMember) bool { _, exists := currSetPeers[string(member.PKIid)] return !exists })) newInCurr := endpoints(currPeers.Filter(func(member discovery.NetworkMember) bool { _, exists := prevSetPeers[string(member.PKIid)] return !exists })) currView = endpoints(currPeers) if !reflect.DeepEqual(wereInPrev, newInCurr) { if len(wereInPrev) == 0 { mt.report("Membership view has changed. peers went online: ", newInCurr, ", current view: ", currView) } else if len(newInCurr) == 0 { mt.report("Membership view has changed. peers went offline: ", wereInPrev, ", current view: ", currView) } else { mt.report("Membership view has changed. peers went offline: ", wereInPrev, ", peers went online: ", newInCurr, ", current view: ", currView) } } } func (mt *membershipTracker) createSetOfPeers(peersToMakeSet []discovery.NetworkMember) map[string]struct{} { setPeers := make(map[string]struct{}) for _, prevPeer := range peersToMakeSet { prevPeerID := string(prevPeer.PKIid) setPeers[prevPeerID] = struct{}{} } return setPeers } func (mt *membershipTracker) trackMembershipChanges() { prev := mt.getPeersToTrack() prevSetPeers := mt.createSetOfPeers(prev) for { // timeout to check changes in peers select { case <-mt.stopChan: return case <-mt.tickerChannel: currPeers := mt.getPeersToTrack() mt.metrics.Total.With("channel", string(mt.chainID)).Set(float64(len(currPeers))) currSetPeers := mt.createSetOfPeers(currPeers) mt.checkIfPeersChanged(prev, currPeers, prevSetPeers, currSetPeers) prev = currPeers prevSetPeers = mt.createSetOfPeers(prev) } } }
{ "content_hash": "b85009cce94d07fe763112fc54bee2a5", "timestamp": "", "source": "github", "line_count": 1155, "max_line_length": 143, "avg_line_length": 31.943722943722943, "alnum_prop": 0.7251660116546957, "repo_name": "jimthematrix/fabric", "id": "78ebd8c3c40e2105d9ebfb462d97aba0152e7aa4", "size": "36978", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "gossip/gossip/channel/channel.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "4104" }, { "name": "Go", "bytes": "11991272" }, { "name": "Makefile", "bytes": "15840" }, { "name": "Shell", "bytes": "66599" } ], "symlink_target": "" }
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> #include "regproc.h" static const char *usage = "Usage:\n" " regedit filename\n" " regedit /E filename [regpath]\n" " regedit /D regpath\n" "\n" "filename - registry file name\n" "regpath - name of the registry key\n" "\n" "When called without any switches, adds the content of the specified\n" "file to the registry\n" "\n" "Switches:\n" " /E - exports contents of the specified registry key to the specified\n" " file. Exports the whole registry if no key is specified.\n" " /D - deletes specified registry key\n" " /S - silent execution, can be used with any other switch.\n" " Default. The only existing mode, exists for compatibility with Windows regedit.\n" " /V - advanced mode, can be used with any other switch.\n" " Ignored, exists for compatibility with Windows regedit.\n" " /L - location of system.dat file. Can be used with any other switch.\n" " Ignored. Exists for compatibility with Windows regedit.\n" " /R - location of user.dat file. Can be used with any other switch.\n" " Ignored. Exists for compatibility with Windows regedit.\n" " /? - print this help. Any other switches are ignored.\n" " /C - create registry from file. Not implemented.\n" "\n" "The switches are case-insensitive, can be prefixed either by '-' or '/'.\n" "This program is command-line compatible with Microsoft Windows\n" "regedit.\n"; typedef enum { ACTION_UNDEF, ACTION_ADD, ACTION_EXPORT, ACTION_DELETE } REGEDIT_ACTION; const CHAR *getAppName(void) { return "regedit"; } /****************************************************************************** * Copies file name from command line string to the buffer. * Rewinds the command line string pointer to the next non-space character * after the file name. * Buffer contains an empty string if no filename was found; * * params: * command_line - command line current position pointer * where *s[0] is the first symbol of the file name. * file_name - buffer to write the file name to. */ static void get_file_name(CHAR **command_line, CHAR *file_name) { CHAR *s = *command_line; int pos = 0; /* position of pointer "s" in *command_line */ file_name[0] = 0; if (!s[0]) { return; } if (s[0] == '"') { s++; (*command_line)++; while(s[0] != '"') { if (!s[0]) { fprintf(stderr,"%s: Unexpected end of file name!\n", getAppName()); exit(1); } s++; pos++; } } else { while(s[0] && !isspace(s[0])) { s++; pos++; } } memcpy(file_name, *command_line, pos * sizeof((*command_line)[0])); /* remove the last backslash */ if (file_name[pos - 1] == '\\') { file_name[pos - 1] = '\0'; } else { file_name[pos] = '\0'; } if (s[0]) { s++; pos++; } while(s[0] && isspace(s[0])) { s++; pos++; } (*command_line) += pos; } static BOOL PerformRegAction(REGEDIT_ACTION action, LPSTR s) { switch (action) { case ACTION_ADD: { CHAR filename[MAX_PATH]; FILE *reg_file; get_file_name(&s, filename); if (!filename[0]) { fprintf(stderr,"%s: No file name was specified\n", getAppName()); fprintf(stderr,usage); exit(1); } while(filename[0]) { char* realname = NULL; if (strcmp(filename, "-") == 0) { reg_file = stdin; } else { int size; size = SearchPathA(NULL, filename, NULL, 0, NULL, NULL); if (size > 0) { realname = HeapAlloc(GetProcessHeap(), 0, size); size = SearchPathA(NULL, filename, NULL, size, realname, NULL); } if (size == 0) { fprintf(stderr, "%s: File not found \"%s\" (%d)\n", getAppName(), filename, GetLastError()); exit(1); } reg_file = fopen(realname, "rb"); if (reg_file == NULL) { perror(""); fprintf(stderr, "%s: Can't open file \"%s\"\n", getAppName(), filename); exit(1); } } import_registry_file(reg_file); if (realname) { HeapFree(GetProcessHeap(),0,realname); fclose(reg_file); } get_file_name(&s, filename); } break; } case ACTION_DELETE: { CHAR reg_key_name[KEY_MAX_LEN]; get_file_name(&s, reg_key_name); if (!reg_key_name[0]) { fprintf(stderr,"%s: No registry key was specified for removal\n", getAppName()); fprintf(stderr,usage); exit(1); } else { WCHAR* reg_key_nameW = GetWideString(reg_key_name); delete_registry_key(reg_key_nameW); HeapFree(GetProcessHeap(), 0, reg_key_nameW); } break; } case ACTION_EXPORT: { CHAR filename[MAX_PATH]; WCHAR* filenameW; filename[0] = '\0'; get_file_name(&s, filename); if (!filename[0]) { fprintf(stderr,"%s: No file name was specified\n", getAppName()); fprintf(stderr,usage); exit(1); } filenameW = GetWideString(filename); if (s[0]) { CHAR reg_key_name[KEY_MAX_LEN]; WCHAR* reg_key_nameW; get_file_name(&s, reg_key_name); reg_key_nameW = GetWideString(reg_key_name); export_registry_key(filenameW, reg_key_nameW, REG_FORMAT_4); HeapFree(GetProcessHeap(), 0, reg_key_nameW); } else { export_registry_key(filenameW, NULL, REG_FORMAT_4); } HeapFree(GetProcessHeap(), 0, filenameW); break; } default: fprintf(stderr,"%s: Unhandled action!\n", getAppName()); exit(1); break; } return TRUE; } /** * Process unknown switch. * * Params: * chu - the switch character in upper-case. * s - the command line string where s points to the switch character. */ static void error_unknown_switch(char chu, char *s) { if (isalpha(chu)) { fprintf(stderr,"%s: Undefined switch /%c!\n", getAppName(), chu); } else { fprintf(stderr,"%s: Alphabetic character is expected after '%c' " "in switch specification\n", getAppName(), *(s - 1)); } exit(1); } BOOL ProcessCmdLine(LPSTR lpCmdLine) { REGEDIT_ACTION action = ACTION_UNDEF; LPSTR s = lpCmdLine; /* command line pointer */ CHAR ch = *s; /* current character */ while (ch && ((ch == '-') || (ch == '/'))) { char chu; char ch2; s++; ch = *s; if (!ch || isspace(ch)) { /* '-' is a file name. It indicates we should use stdin */ s--; break; } ch2 = *(s+1); chu = toupper(ch); if (!ch2 || isspace(ch2)) { if (chu == 'S' || chu == 'V') { /* ignore these switches */ } else { switch (chu) { case 'D': action = ACTION_DELETE; break; case 'E': action = ACTION_EXPORT; break; case '?': fprintf(stderr,usage); exit(0); break; default: error_unknown_switch(chu, s); break; } } s++; } else { if (ch2 == ':') { switch (chu) { case 'L': /* fall through */ case 'R': s += 2; while (*s && !isspace(*s)) { s++; } break; default: error_unknown_switch(chu, s); break; } } else { /* this is a file name, starting from '/' */ s--; break; } } /* skip spaces to the next parameter */ ch = *s; while (ch && isspace(ch)) { s++; ch = *s; } } if (*s && action == ACTION_UNDEF) action = ACTION_ADD; if (action == ACTION_UNDEF) return FALSE; return PerformRegAction(action, s); }
{ "content_hash": "2eda120c7e595a45ce6e89a0f9cbc112", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 96, "avg_line_length": 30.216129032258063, "alnum_prop": 0.45137183730116365, "repo_name": "howard5888/wine", "id": "acff7010719b676e25070aad5f11925e63c8b9d3", "size": "10207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wine-1.7.7/programs/regedit/regedit.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": "" }
Interest = new Meteor.Collection( 'interest' ); Interest.allow({ insert: () => true, update: () => true, remove: () => false }); let InterestSchema = new SimpleSchema({ "user_id": { type: String, label: "The ID of the user who has these interests." }, "interests": { type: [String], label: "Array of interests of the user." } }); Interest.attachSchema( InterestSchema );
{ "content_hash": "1527f9869d916b9478f8a50275c66051", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 56, "avg_line_length": 20.2, "alnum_prop": 0.6163366336633663, "repo_name": "archembald/avajo", "id": "dbf6b3f60b42b980b1c418ace7045c540f3c945a", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "collections/interests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "674" }, { "name": "HTML", "bytes": "7677" }, { "name": "JavaScript", "bytes": "19236" } ], "symlink_target": "" }
package kaka.android.dn; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
{ "content_hash": "a332cc558300cc212d8804482b3b4a97", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 93, "avg_line_length": 26.615384615384617, "alnum_prop": 0.7456647398843931, "repo_name": "kaka/dn-rss", "id": "a3a91c6dac50468b967424bab92abadd4d1eb959", "size": "346", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/androidTest/java/kaka/android/dn/ApplicationTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "1029" }, { "name": "Java", "bytes": "44050" }, { "name": "Prolog", "bytes": "663" } ], "symlink_target": "" }
from ..controller.basecontroller import _BaseController class Tag(_BaseController): tooltip = "Own tag" def __init__(self, name, index=None, controller=None): self.name = name self.controller = controller self._index = index def set_index(self, index): self._index = index def is_empty(self): return self.name is None def __eq__(self, other): return self.name == other.name and self._index == other._index def __ne__(self, other): return not (self == other) def __str__(self): return self.name def choose(self, mapping): return mapping[self.__class__] def delete(self): self.controller.remove(str(self.name)) if type(self) is Tag and len(self.controller._tags.value) == 0: if len(self.controller.parent.default_tags.value) > 0: self.controller.set_value("") else: self.controller.clear() class ForcedTag(Tag): @property def tooltip(self): return u'Force tag from suite {0}'.format( self.controller.datafile_controller.name) class DefaultTag(Tag): @property def tooltip(self): return u'Default tag from suite {0}'.format( self.controller.datafile_controller.name)
{ "content_hash": "8bd08760f67063403ed54599802eb6e4", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 71, "avg_line_length": 25.28846153846154, "alnum_prop": 0.5984790874524715, "repo_name": "HelioGuilherme66/RIDE", "id": "5a7106d2cca3b200455244aea86b9e6807320f73", "size": "1959", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/robotide/controller/tags.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31131" }, { "name": "HTML", "bytes": "96342" }, { "name": "JavaScript", "bytes": "42656" }, { "name": "Python", "bytes": "3703410" }, { "name": "RobotFramework", "bytes": "378004" }, { "name": "Shell", "bytes": "1873" } ], "symlink_target": "" }
require 'rss' class Rss::ImportWeatherXmlJob < Rss::ImportBase def initialize(*args) super set_model Rss::WeatherXmlPage end private def before_import(file, *args) @weather_xml_page = nil super @cur_file = Rss::TempFile.with_repl_master.where(site_id: site.id, id: file).first return unless @cur_file @items = Rss::Wrappers.parse(@cur_file) @imported_pages = [] end def after_import execute_weather_xml_filters super gc_rss_tempfile end def gc_rss_tempfile return if rand(100) >= 20 Rss::TempFile.with_repl_master.lt(updated: 2.weeks.ago).destroy_all end def import_rss_item(*args) page = super return page if page.nil? || page.invalid? content = download(page.rss_link) return page if content.nil? page.event_id = extract_event_id(content) rescue nil page.xml = content page.save! if content.include?('<InfoKind>震度速報</InfoKind>') process_earthquake(page) end @imported_pages << page page end def download(url) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' req = Net::HTTP::Get.new(uri.path) res = http.request(req) return nil if res.code != '200' res.body.force_encoding('UTF-8') rescue => e Rails.logger.warn("#{e.class} (#{e.message}):\n #{e.backtrace.join("\n ")}") end def extract_event_id(xml) xmldoc = REXML::Document.new(xml) REXML::XPath.first(xmldoc, '/Report/Head/EventID/text()').to_s.strip end def process_earthquake(page) parse_xml(page) if @region_eq_infos.blank? Rails.logger.info('no earthquake found inside target region') return end max_int = @region_eq_infos.max_by { |item| item[:area_max_int] } max_int = max_int[:area_max_int] if max_int.present? if compare_intensity(max_int, node.earthquake_intensity) < 0 Rails.logger.info("actual intensity #{max_int} is lower than #{node.earthquake_intensity}") return end # send anpi mail send_earthquake_info_mail(page) end def parse_xml(page) @region_eq_infos = [] return if node.my_anpi_post.blank? return if node.anpi_mail.blank? xmldoc = REXML::Document.new(page.xml) status = REXML::XPath.first(xmldoc, '/Report/Control/Status/text()').to_s.strip return if status != Jmaxml::Status::NORMAL info_kind = REXML::XPath.first(xmldoc, '/Report/Head/InfoKind/text()').to_s.strip return if info_kind != '震度速報' @report_datetime = REXML::XPath.first(xmldoc, '/Report/Head/ReportDateTime/text()').to_s.strip if @report_datetime.present? @report_datetime = Time.zone.parse(@report_datetime.to_s) rescue nil end @target_datetime = REXML::XPath.first(xmldoc, '/Report/Head/TargetDateTime/text()').to_s.strip if @target_datetime.present? @target_datetime = Time.zone.parse(@target_datetime.to_s) rescue nil end diff = Time.zone.now - @report_datetime return if diff.abs > 1.hour REXML::XPath.match(xmldoc, '/Report/Body/Intensity/Observation/Pref').each do |pref| pref_name = pref.elements['Name'].text pref_code = pref.elements['Code'].text REXML::XPath.match(pref, 'Area').each do |area| area_name = area.elements['Name'].text area_code = area.elements['Code'].text area_max_int = area.elements['MaxInt'].text region = Jmaxml::QuakeRegion.site(site).where(code: area_code).first next if region.blank? next unless node.target_region_ids.include?(region.id) @region_eq_infos << { pref_name: pref_name, pref_code: pref_code, area_name: area_name, area_code: area_code, area_max_int: area_max_int, } end end end # send anpi mail def send_earthquake_info_mail(page) renderer = Rss::Renderer::AnpiMail.new( cur_site: site, cur_node: node, cur_page: page, cur_infos: { infos: @region_eq_infos, target_time: @target_datetime }) name = renderer.render_template(node.title_mail_text) text = renderer.render ezine_page = Ezine::Page.new( cur_site: site, cur_node: node.anpi_mail, cur_user: user, name: name, text: text ) unless ezine_page.save Rails.logger.warn("failed to save ezine/page:\n#{ezine_page.errors.full_messages.join("\n")}") return end Ezine::DeliverJob.bind(site_id: site, node_id: node, page_id: ezine_page).perform_now end def compare_intensity(lhs, rhs) normalize_intensity(lhs) <=> normalize_intensity(rhs) end def normalize_intensity(int) ret = int.to_s[0].to_i * 10 ret += 1 if int[1] == '-' ret += 9 if int[1] == '+' ret end def execute_weather_xml_filters return if @imported_pages.blank? Rss::ExecuteWeatherXmlFiltersJob.bind(site_id: site.id, node_id: node.id).perform_later(@imported_pages.map(&:id)) end end
{ "content_hash": "2a30475d09bba7d8fa546c1fc85ad031", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 118, "avg_line_length": 27.854748603351954, "alnum_prop": 0.6399919775371039, "repo_name": "MasakiInaya/shirasagi", "id": "45378ed50d8456d318ca7a4c48cd79b54d4f31ef", "size": "5002", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/jobs/rss/import_weather_xml_job.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "528135" }, { "name": "HTML", "bytes": "2985497" }, { "name": "JavaScript", "bytes": "4946932" }, { "name": "Ruby", "bytes": "7064536" }, { "name": "Shell", "bytes": "20886" } ], "symlink_target": "" }
require 'dfp_api' API_VERSION = :v201602 def create_users() # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') # Get the UserService. user_service = dfp.service(:UserService, API_VERSION) # Set the user's email addresses and names. emails_and_names = [ {:name => 'INSERT_NAME_HERE', :email => 'INSERT_EMAIL_ADDRESS_HERE'}, {:name => 'INSERT_NAME_HERE', :email => 'INSERT_EMAIL_ADDRESS_HERE'} ] # Set the role ID for new users. role_id = 'INSERT_ROLE_ID_HERE'.to_i # Create an array to store local user objects. users = emails_and_names.map do |email_and_name| email_and_name.merge({:role_id => role_id, :preferred_locale => 'en_US'}) end # Create the users on the server. return_users = user_service.create_users(users) if return_users return_users.each do |user| puts "User with ID: %d, name: %s and email: %s was created." % [user[:id], user[:name], user[:email]] end else raise 'No users were created.' end end if __FILE__ == $0 begin create_users() # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
{ "content_hash": "a248e360d52c6e89944697bfba66cc78", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 77, "avg_line_length": 26.125, "alnum_prop": 0.6255980861244019, "repo_name": "Tei1988/google-api-ads-ruby", "id": "538b457a488a84dc5de57d2418cc8703557b397e", "size": "2566", "binary": false, "copies": "1", "ref": "refs/heads/apply-erb-to-config", "path": "dfp_api/examples/v201602/user_service/create_users.rb", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1319" }, { "name": "HTML", "bytes": "7882" }, { "name": "JavaScript", "bytes": "757" }, { "name": "Python", "bytes": "187" }, { "name": "Ruby", "bytes": "9849343" } ], "symlink_target": "" }
import os import contextlib import unittest import warnings import flask import flask_dotenv as dotenv @contextlib.contextmanager def capture(): import sys from io import StringIO oldout, olderr = sys.stdout, sys.stderr try: out = [StringIO(), StringIO()] sys.stdout, sys.stderr = out yield out finally: sys.stdout, sys.stderr = oldout, olderr out[0] = out[0].getvalue() out[1] = out[1].getvalue() class DotEnvTestCase(unittest.TestCase): def setUp(self): self.app = flask.Flask(__name__) self.env = dotenv.DotEnv() def tearDown(self): config_keys = [ 'FOO', 'SECRET_KEY', 'DEVELOPMENT_DATABASE_URL', 'TEST_DATABASE_URL', 'BAR' ] for key in config_keys: if key in self.app.config: del self.app.config[key] def test_warning_if_env_file_is_missing(self): with warnings.catch_warnings(record=True) as w: self.env.init_app(self.app, "/does/not/exist/.env") self.assertEqual( "can't read /does/not/exist/.env - it doesn't exist", str(w[0].message) ) self.assertFalse('FOO' in self.app.config) def test_read_default_env_file(self): self.env.init_app(self.app) self.assertTrue('FOO' in self.app.config) def test_read_specified_env_file(self): root_dir = os.path.dirname(os.path.abspath(__file__)) self.env.init_app(self.app, os.path.join(root_dir, '.env.min')) self.assertTrue('BAR' in self.app.config) def test_loaded_value_dose_not_contain_double_quote(self): self.env.init_app(self.app) self.assertEqual( 'postgresql://postgres:postgres@localhost/development', self.app.config['DEVELOPMENT_DATABASE_URL']) def test_loaded_value_dose_not_contain_single_quote(self): self.env.init_app(self.app) self.assertEqual( 'postgresql://postgres:postgres@localhost/test', self.app.config['TEST_DATABASE_URL']) def test_overwrite_an_existing_config_var(self): # flask has secret_key in default self.assertEqual(None, self.app.config['SECRET_KEY']) self.env.init_app(self.app) self.assertEqual(':)', self.app.config['SECRET_KEY']) def test_alias_sets_it_as_same_value(self): self.env.init_app(self.app) self.env.alias(maps={ 'TEST_DATABASE_URL': 'SQLALCHEMY_DATABASE_URL' }) self.assertEqual( 'postgresql://postgres:postgres@localhost/test', self.app.config['SQLALCHEMY_DATABASE_URL'] ) def test_init_app_assigns_app(self): self.env.init_app(self.app) self.assertEqual(self.app, self.env.app) def test_init_app_assigns_default_verbose_mode(self): self.env.init_app(self.app) self.assertFalse(self.env.verbose_mode) def test_import_vars_raises_in_env_file_does_not_exist(self): with self.assertRaises(FileNotFoundError) as e: self.env._DotEnv__import_vars('/does/not/exist/.env') self.assertEqual(e.exception.strerror, 'No such file or directory') def test_import_vars_will_output_logs_in_vobose_mode(self): with capture() as out: self.env.app = self.app self.env.verbose_mode = True root_dir = os.path.dirname(os.path.abspath(__file__)) self.env._DotEnv__import_vars(os.path.join(root_dir, '.env.min')) # flask has secret_key in default self.assertIn( ' * Setting an entirely new config var: BAR\n' ' * Overwriting an existing config var: SECRET_KEY\n', out ) def test_alias_will_output_log_in_vobose_mode(self): with capture() as out: self.env.init_app(self.app) self.env.verbose_mode = True self.env.alias(maps={ 'TEST_DATABASE_URL': 'SQLALCHEMY_DATABASE_URL' }) self.assertIn( ' * Mapping a specified var as a alias:' ' SQLALCHEMY_DATABASE_URL => TEST_DATABASE_URL\n', out ) if __name__ == '__main__': unittest.main()
{ "content_hash": "8e7ea22ccab92a249937a1dbe2131bd0", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 77, "avg_line_length": 33.515625, "alnum_prop": 0.5913752913752913, "repo_name": "mawuli/flask-dotenv", "id": "390ebb224257643feee709e18986011ac431d836", "size": "4290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/tests.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "6918" } ], "symlink_target": "" }
enum ExprResultType { LLIR_REGISTER, INTEGER_CONSTANT, FLOAT_CONSTANT, }; typedef struct ExprResult ExprResult; struct ExprResult { union { long int_value; double float_value; long ssa_register; }; int type; // enum ExprResultType }; void visit_file (AST *root); //void visit_global_var_decl (AST *ast); ExprResult visit_stat (AST *stat); ExprResult visit_return_stat (AST *assign); void visit_assign_stat (AST *assign); void visit_var_decl (AST *ast); void visit_function_decl (AST *ast); ExprResult visit_stat_block (AST *stat_block, AST *params, int return_type); ExprResult visit_expr (AST *expr); ExprResult visit_add (AST *expr); ExprResult visit_sub (AST *expr); ExprResult visit_mul (AST *expr); ExprResult visit_div (AST *expr); ExprResult visit_mod (AST *expr); ExprResult visit_id (AST *ast); ExprResult visit_literal (AST *ast); ExprResult visit_unary_minus (AST *ast); ExprResult visit_function_call (AST *ast); #endif // VISITOR_HEADER
{ "content_hash": "bb95b2cde8226b0476312af589a9b0e0", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 76, "avg_line_length": 26.805555555555557, "alnum_prop": 0.7326424870466322, "repo_name": "damorim/compilers-cin", "id": "744212b6b6ebba4a3a2a2144a9b9099e224daef8", "size": "1030", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "antigo/mini-projeto/compiler/include/visitor.h", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "11266" }, { "name": "C", "bytes": "118657" }, { "name": "C++", "bytes": "13919" }, { "name": "Java", "bytes": "137247" }, { "name": "Makefile", "bytes": "8093" }, { "name": "Python", "bytes": "930934" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2015 Red Hat, Inc. and/or its affiliates. ~ ~ Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 --> <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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.wildfly.swarm</groupId> <artifactId>testsuite</artifactId> <version>2017.3.0-SNAPSHOT</version> <relativePath>../</relativePath> </parent> <groupId>org.wildfly.swarm</groupId> <artifactId>testsuite-ee</artifactId> <name>Test Suite: EE</name> <description>Test Suite: EE</description> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.wildfly.swarm</groupId> <artifactId>ee</artifactId> </dependency> <dependency> <groupId>org.wildfly.swarm</groupId> <artifactId>arquillian</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.arquillian.junit</groupId> <artifactId>arquillian-junit-container</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "6de5d5c377e069cc01fce12c3fffc37f", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 204, "avg_line_length": 31.023809523809526, "alnum_prop": 0.681504221028396, "repo_name": "emag/wildfly-swarm", "id": "a1708bb30bbf902cbca20b71008fe51d345768a7", "size": "1303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testsuite/testsuite-ee/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5821" }, { "name": "HTML", "bytes": "7184" }, { "name": "Java", "bytes": "2166370" }, { "name": "JavaScript", "bytes": "13143" }, { "name": "Ruby", "bytes": "5349" }, { "name": "Shell", "bytes": "8275" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server.remotetask; import com.facebook.airlift.concurrent.SetThreadName; import com.facebook.airlift.http.client.HttpClient; import com.facebook.airlift.http.client.Request; import com.facebook.airlift.http.client.ResponseHandler; import com.facebook.airlift.log.Logger; import com.facebook.presto.execution.StateMachine; import com.facebook.presto.execution.TaskId; import com.facebook.presto.execution.TaskStatus; import com.facebook.presto.server.smile.BaseResponse; import com.facebook.presto.server.smile.Codec; import com.facebook.presto.server.smile.SmileCodec; import com.facebook.presto.spi.HostAddress; import com.facebook.presto.spi.PrestoException; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.airlift.units.Duration; import javax.annotation.concurrent.GuardedBy; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import static com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom; import static com.facebook.airlift.http.client.Request.Builder.prepareGet; import static com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE; import static com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT; import static com.facebook.presto.server.RequestHelpers.setContentTypeHeaders; import static com.facebook.presto.server.smile.AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler; import static com.facebook.presto.server.smile.FullSmileResponseHandler.createFullSmileResponseHandler; import static com.facebook.presto.server.smile.JsonCodecWrapper.unwrapJsonCodec; import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_MISMATCH; import static com.facebook.presto.util.Failures.REMOTE_TASK_MISMATCH_ERROR; import static com.google.common.base.Strings.isNullOrEmpty; import static io.airlift.units.Duration.nanosSince; import static java.lang.String.format; import static java.util.Objects.requireNonNull; class ContinuousTaskStatusFetcher implements SimpleHttpResponseCallback<TaskStatus> { private static final Logger log = Logger.get(ContinuousTaskStatusFetcher.class); private final TaskId taskId; private final Consumer<Throwable> onFail; private final StateMachine<TaskStatus> taskStatus; private final Codec<TaskStatus> taskStatusCodec; private final Duration refreshMaxWait; private final Executor executor; private final HttpClient httpClient; private final RequestErrorTracker errorTracker; private final RemoteTaskStats stats; private final boolean isBinaryTransportEnabled; private final AtomicLong currentRequestStartNanos = new AtomicLong(); @GuardedBy("this") private boolean running; @GuardedBy("this") private ListenableFuture<BaseResponse<TaskStatus>> future; public ContinuousTaskStatusFetcher( Consumer<Throwable> onFail, TaskStatus initialTaskStatus, Duration refreshMaxWait, Codec<TaskStatus> taskStatusCodec, Executor executor, HttpClient httpClient, Duration maxErrorDuration, ScheduledExecutorService errorScheduledExecutor, RemoteTaskStats stats, boolean isBinaryTransportEnabled) { requireNonNull(initialTaskStatus, "initialTaskStatus is null"); this.taskId = initialTaskStatus.getTaskId(); this.onFail = requireNonNull(onFail, "onFail is null"); this.taskStatus = new StateMachine<>("task-" + taskId, executor, initialTaskStatus); this.refreshMaxWait = requireNonNull(refreshMaxWait, "refreshMaxWait is null"); this.taskStatusCodec = requireNonNull(taskStatusCodec, "taskStatusCodec is null"); this.executor = requireNonNull(executor, "executor is null"); this.httpClient = requireNonNull(httpClient, "httpClient is null"); this.errorTracker = new RequestErrorTracker(taskId, initialTaskStatus.getSelf(), maxErrorDuration, errorScheduledExecutor, "getting task status"); this.stats = requireNonNull(stats, "stats is null"); this.isBinaryTransportEnabled = isBinaryTransportEnabled; } public synchronized void start() { if (running) { // already running return; } running = true; scheduleNextRequest(); } public synchronized void stop() { running = false; if (future != null) { // do not terminate if the request is already running to avoid closing pooled connections future.cancel(false); future = null; } } private synchronized void scheduleNextRequest() { // stopped or done? TaskStatus taskStatus = getTaskStatus(); if (!running || taskStatus.getState().isDone()) { return; } // outstanding request? if (future != null && !future.isDone()) { // this should never happen log.error("Can not reschedule update because an update is already running"); return; } // if throttled due to error, asynchronously wait for timeout and try again ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::scheduleNextRequest, executor); return; } Request request = setContentTypeHeaders(isBinaryTransportEnabled, prepareGet()) .setUri(uriBuilderFrom(taskStatus.getSelf()).appendPath("status").build()) .setHeader(PRESTO_CURRENT_STATE, taskStatus.getState().toString()) .setHeader(PRESTO_MAX_WAIT, refreshMaxWait.toString()) .build(); ResponseHandler responseHandler; if (isBinaryTransportEnabled) { responseHandler = createFullSmileResponseHandler((SmileCodec<TaskStatus>) taskStatusCodec); } else { responseHandler = createAdaptingJsonResponseHandler(unwrapJsonCodec(taskStatusCodec)); } errorTracker.startRequest(); future = httpClient.executeAsync(request, responseHandler); currentRequestStartNanos.set(System.nanoTime()); Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor); } TaskStatus getTaskStatus() { return taskStatus.get(); } @Override public void success(TaskStatus value) { try (SetThreadName ignored = new SetThreadName("ContinuousTaskStatusFetcher-%s", taskId)) { updateStats(currentRequestStartNanos.get()); try { updateTaskStatus(value); errorTracker.requestSucceeded(); } finally { scheduleNextRequest(); } } } @Override public void failed(Throwable cause) { try (SetThreadName ignored = new SetThreadName("ContinuousTaskStatusFetcher-%s", taskId)) { updateStats(currentRequestStartNanos.get()); try { // if task not already done, record error TaskStatus taskStatus = getTaskStatus(); if (!taskStatus.getState().isDone()) { errorTracker.requestFailed(cause); } } catch (Error e) { onFail.accept(e); throw e; } catch (RuntimeException e) { onFail.accept(e); } finally { scheduleNextRequest(); } } } @Override public void fatal(Throwable cause) { try (SetThreadName ignored = new SetThreadName("ContinuousTaskStatusFetcher-%s", taskId)) { updateStats(currentRequestStartNanos.get()); onFail.accept(cause); } } void updateTaskStatus(TaskStatus newValue) { // change to new value if old value is not changed and new value has a newer version AtomicBoolean taskMismatch = new AtomicBoolean(); taskStatus.setIf(newValue, oldValue -> { // did the task instance id change if (!isNullOrEmpty(oldValue.getTaskInstanceId()) && !oldValue.getTaskInstanceId().equals(newValue.getTaskInstanceId())) { taskMismatch.set(true); return false; } if (oldValue.getState().isDone()) { // never update if the task has reached a terminal state return false; } if (newValue.getVersion() < oldValue.getVersion()) { // don't update to an older version (same version is ok) return false; } return true; }); if (taskMismatch.get()) { // This will also set the task status to FAILED state directly. // Additionally, this will issue a DELETE for the task to the worker. // While sending the DELETE is not required, it is preferred because a task was created by the previous request. onFail.accept(new PrestoException(REMOTE_TASK_MISMATCH, format("%s (%s)", REMOTE_TASK_MISMATCH_ERROR, HostAddress.fromUri(getTaskStatus().getSelf())))); } } public synchronized boolean isRunning() { return running; } /** * Listener is always notified asynchronously using a dedicated notification thread pool so, care should * be taken to avoid leaking {@code this} when adding a listener in a constructor. Additionally, it is * possible notifications are observed out of order due to the asynchronous execution. */ public void addStateChangeListener(StateMachine.StateChangeListener<TaskStatus> stateChangeListener) { taskStatus.addStateChangeListener(stateChangeListener); } private void updateStats(long currentRequestStartNanos) { stats.statusRoundTripMillis(nanosSince(currentRequestStartNanos).toMillis()); } }
{ "content_hash": "fe01bfbf3f7b550f5653238f556a352e", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 164, "avg_line_length": 39.33090909090909, "alnum_prop": 0.6808431952662722, "repo_name": "ptkool/presto", "id": "1b596c7c7db176c421de46967ee32fda8d9f0668", "size": "10816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28777" }, { "name": "CSS", "bytes": "13127" }, { "name": "HTML", "bytes": "28660" }, { "name": "Java", "bytes": "37430827" }, { "name": "JavaScript", "bytes": "216033" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "Python", "bytes": "8714" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29909" }, { "name": "TSQL", "bytes": "161695" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
{-# LANGUAGE OverloadedStrings, TupleSections, PackageImports #-} module Network.PeyoTLS.State ( HandshakeState, initState, PartnerId, newPartnerId, Keys(..), nullKeys, ContentType(..), Alert(..), AlertLevel(..), AlertDesc(..), CipherSuite(..), KeyExchange(..), BulkEncryption(..), randomGen, setRandomGen, getBuf, setBuf, getWBuf, setWBuf, getReadSN, getWriteSN, succReadSN, succWriteSN, ) where import "monads-tf" Control.Monad.Error.Class (Error(strMsg)) import Data.Maybe (fromJust) import Data.Word (Word8, Word64) import Data.String (IsString(..)) import qualified Data.ByteString as BS import qualified Codec.Bytable.BigEndian as B import Network.PeyoTLS.CipherSuite ( CipherSuite(..), KeyExchange(..), BulkEncryption(..)) data HandshakeState h g = HandshakeState { randomGen :: g, nextPartnerId :: Int, states :: [(PartnerId, StateOne g)] } initState :: g -> HandshakeState h g initState g = HandshakeState{ randomGen = g, nextPartnerId = 0, states = [] } data PartnerId = PartnerId Int deriving (Show, Eq) newPartnerId :: HandshakeState h g -> (PartnerId, HandshakeState h g) newPartnerId s = (PartnerId i ,) s{ nextPartnerId = succ i, states = (PartnerId i, so) : sos } where i = nextPartnerId s so = StateOne { rBuffer = (CTNull, ""), wBuffer = (CTNull, ""), readSN = 0, writeSN = 0 } sos = states s data StateOne g = StateOne { rBuffer :: (ContentType, BS.ByteString), wBuffer :: (ContentType, BS.ByteString), readSN :: Word64, writeSN :: Word64 } getState :: PartnerId -> HandshakeState h g -> StateOne g getState i = fromJust' "getState" . lookup i . states setState :: PartnerId -> StateOne g -> Modify (HandshakeState h g) setState i so s = s { states = (i, so) : states s } modifyState :: PartnerId -> Modify (StateOne g) -> Modify (HandshakeState h g) modifyState i f s = setState i (f $ getState i s) s data Keys = Keys { kCachedCS :: CipherSuite, kReadCS :: CipherSuite, kWriteCS :: CipherSuite, kMasterSecret :: BS.ByteString, kReadMacKey :: BS.ByteString, kWriteMacKey :: BS.ByteString, kReadKey :: BS.ByteString, kWriteKey :: BS.ByteString } deriving (Show, Eq) nullKeys :: Keys nullKeys = Keys { kCachedCS = CipherSuite KE_NULL BE_NULL, kReadCS = CipherSuite KE_NULL BE_NULL, kWriteCS = CipherSuite KE_NULL BE_NULL, kMasterSecret = "", kReadMacKey = "", kWriteMacKey = "", kReadKey = "", kWriteKey = "" } data ContentType = CTCCSpec | CTAlert | CTHandshake | CTAppData | CTNull | CTRaw Word8 deriving (Show, Eq) instance B.Bytable ContentType where encode CTNull = BS.pack [0] encode CTCCSpec = BS.pack [20] encode CTAlert = BS.pack [21] encode CTHandshake = BS.pack [22] encode CTAppData = BS.pack [23] encode (CTRaw ct) = BS.pack [ct] decode "\0" = Right CTNull decode "\20" = Right CTCCSpec decode "\21" = Right CTAlert decode "\22" = Right CTHandshake decode "\23" = Right CTAppData decode bs | [ct] <- BS.unpack bs = Right $ CTRaw ct decode _ = Left "State.decodeCT" data Alert = Alert AlertLevel AlertDesc String | NotDetected String deriving Show data AlertLevel = ALWarning | ALFatal | ALRaw Word8 deriving Show data AlertDesc = ADCloseNotify | ADUnexpectedMessage | ADBadRecordMac | ADUnsupportedCertificate | ADCertificateExpired | ADCertificateUnknown | ADIllegalParameter | ADUnknownCa | ADDecodeError | ADDecryptError | ADProtocolVersion | ADRaw Word8 deriving Show instance Error Alert where strMsg = NotDetected instance IsString Alert where fromString = NotDetected setRandomGen :: g -> HandshakeState h g -> HandshakeState h g setRandomGen rg st = st { randomGen = rg } getBuf :: PartnerId -> HandshakeState h g -> (ContentType, BS.ByteString) getBuf i = rBuffer . fromJust' "getBuf" . lookup i . states setBuf :: PartnerId -> (ContentType, BS.ByteString) -> Modify (HandshakeState h g) setBuf i = modifyState i . \bs st -> st { rBuffer = bs } getWBuf :: PartnerId -> HandshakeState h g -> (ContentType, BS.ByteString) getWBuf i = wBuffer . fromJust' "getWriteBuffer" . lookup i . states setWBuf :: PartnerId -> (ContentType, BS.ByteString) -> Modify (HandshakeState h g) setWBuf i = modifyState i . \bs st -> st{ wBuffer = bs } getReadSN, getWriteSN :: PartnerId -> HandshakeState h g -> Word64 getReadSN i = readSN . fromJust . lookup i . states getWriteSN i = writeSN . fromJust . lookup i . states succReadSN, succWriteSN :: PartnerId -> Modify (HandshakeState h g) succReadSN i = modifyState i $ \s -> s{ readSN = succ $ readSN s } succWriteSN i = modifyState i $ \s -> s{ writeSN = succ $ writeSN s } type Modify s = s -> s fromJust' :: String -> Maybe a -> a fromJust' _ (Just x) = x fromJust' msg _ = error msg
{ "content_hash": "1adfdc9f57f715047ced53e01b205c32", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 83, "avg_line_length": 34.2043795620438, "alnum_prop": 0.7040119504908238, "repo_name": "YoshikuniJujo/forest", "id": "f4e0c75c4a82fa585905edc8ca035f3ec1b230b6", "size": "4686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "subprojects/tls-analysis/server/src/Network/PeyoTLS/State.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "457" }, { "name": "Haskell", "bytes": "676713" }, { "name": "Shell", "bytes": "298" }, { "name": "Smalltalk", "bytes": "2068" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login_log extends MY_Controller { function __construct(){ parent::__construct(); check_permission('admin-login-log1'); } function index(){ // $this->load->view('login_log', $this->template_data); } }
{ "content_hash": "866613d57798421091e144fbb8c2f341", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 63, "avg_line_length": 17.352941176470587, "alnum_prop": 0.6542372881355932, "repo_name": "teekcode/cxpcms", "id": "8bb6840f65957ce5ea21b54c114479c4694a2465", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/admin/controllers/Login_log.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "720" }, { "name": "CSS", "bytes": "569831" }, { "name": "HTML", "bytes": "1713202" }, { "name": "JavaScript", "bytes": "6448048" }, { "name": "PHP", "bytes": "2220301" } ], "symlink_target": "" }
<?php namespace app\commands; use yii\console\Controller; use \app\models\core\Migration as CoreMigration; use \app\models\rt\Migration as RtMigration; use \app\models\sc\Migration as ScMigration; use ssimpson\opensslca\Opensslca; /** * This implements a minimal Certificate Authority using Opensslca * * @author Steve Simpson * @since 2.0 */ class CaController extends Controller { function __construct($id, $module, $config = []) { parent::__construct($id, $module, $config); } /** * This command imports the * @param string $path the path to file to import */ public function actionIndex() { $ca = \Yii::$app->opensslca; echo "Current CA: " . $ca->getCaSubject() ."\n\n"; echo "Usage:\n"; echo " ./yii ca/create -- create the initial Certificate Authority\n"; echo " ./yii ca/create --force -- create & overwritie the existing Certificate Authority\n"; echo "\n"; echo " ./yii ca/cert-with-key <common name> [<days> = 365] -- create a private key & certificate in a single file sent to stdout\n"; echo "\n"; echo " ./yii ca/list -- list certs that have been created.\n"; echo " ./yii ca/crl -- Generates a CRL in ca/crl.pem.\n"; echo "\n"; } public function actionCreate($opts=null) { $ca = \Yii::$app->opensslca; $force = false; if ($opts == "--force") { $force = true; } if ($ca->generateCetificateAuthority($force)) { echo "CA Created\n"; } else { echo "Error creating CA, check logs.\n"; } } public function actionCertWithKey($cn, $days=365) { if ($cn=='') { echo "Please specifiy the cn for usage with this function.\n"; return; } /* @var $ca Opensslca */ $ca = \Yii::$app->opensslca; $sn = $ca->getNextSerial(); $pkey = $ca->generatePrivateKey($sn); $dn = ['commonName'=>$cn ]; $csr = $ca->createCertificatSigningRequest($dn, $pkey); $cert = $ca->signCertificate($csr, $sn, $days); echo $ca->privateKeyToString($pkey); echo $ca->certificateToString($cert); } public function actionRevoke() { $argv=$_SERVER['argv']; $ca = \Yii::$app->opensslca; if ((count($argv) == 4) || (count($argv) == 5)) { $sn = $argv[2]; $reason = $argv[3]; if (count($argv) == 4) { $success = $ca->revokeCertificate($sn,$reason,'revoke'); } else { $success = $ca->revokeCertificate($sn,$reason,'revoke',$argv[4]); } } else { echo "Usage: \n"; echo " ./yii ca/revoke <sn> <reason> <date=now>\n"; echo "\n Reasons:\n"; foreach ($ca::$crlReasons as $id=>$reason) { echo " $id => $reason\n"; } echo "\n"; } } public function actionHold() { $argv=$_SERVER['argv']; $ca = \Yii::$app->opensslca; if ((count($argv) == 3) || (count($argv) == 4)) { $sn = $argv[2]; if (count($argv) == 3) { $success = $ca->revokeCertificate($sn,6,'hold'); } else { $success = $ca->revokeCertificate($sn,6,'hold',$argv[3]); } } else { echo "Usage: \n"; echo " ./yii ca/hold <sn> <date=now>\n"; echo "\n"; } } public function actionList() { $ca = \Yii::$app->opensslca; echo "Certificates Issued: \n"; foreach (glob($ca->getCaDir() . "/certs/*") as $cert) { echo " " . basename($cert) . ": " . $ca->getCertInfo($cert)['name'] ."\n"; } } public function actionCrl() { $ca = \Yii::$app->opensslca; $crl = $ca->generateCertificateRevocationList(); echo $crl . "\n"; } }
{ "content_hash": "c4d351f4949262571f917fa80b802ba6", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 142, "avg_line_length": 26.67105263157895, "alnum_prop": 0.4977799703996053, "repo_name": "SteveSimpson/yii2-opensslca", "id": "e7bab5e0129e91469ba0e0ae6db965b05e67f80e", "size": "4054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/CaController.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "19155" } ], "symlink_target": "" }
var modals = { progress: '\ <div id="in_progress_dlg" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" data-backdrop="static" data-keyboard="false">\ <div class="modal-dialog" style="width: 300px">\ <div class="modal-content">\ <div class="modal-header">\ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\ <h4 class="modal-title">Loading data...</h4>\ </div>\ <div id="modal_message_body" class="modal-body">\ <div class="progress">\ <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%">\ </div>\ </div>\ </div>\ </div>\ </div>\ </div>', warning: '\ <div id="message_dlg" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" data-backdrop="static" data-keyboard="false">\ <div class="modal-dialog" style="width: 400px">\ <div class="modal-content">\ <div class="modal-header">\ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\ <h4 class="modal-title">Warning</h4>\ </div>\ <div id="modal_message_body" class="modal-body">\ </div>\ </div>\ </div>\ </div>', info: '\ <div id="info_dlg" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">\ <div class="modal-dialog" style="width: 400px">\ <div class="modal-content">\ <div id="modal_message_body" class="modal-body"></div>\ </div>\ </div>\ </div>' }; function get_modal(name) { m = $(modals[name]); m.msg = function (message) { this.find('.modal-body').text(message); this.modal('show'); return this; }; m.show = function () { this.modal('show'); return this; }; m.hide = function () { this.modal('hide'); return this; }; return m; }
{ "content_hash": "3b7e6c9cb776c80754b14349c271091a", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 181, "avg_line_length": 43.3448275862069, "alnum_prop": 0.48687350835322196, "repo_name": "ianpark/uk_house_price_tracker", "id": "8f72d4d6bc55523ca0f51441fd419219144b2e24", "size": "2516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/js/modals.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2819" }, { "name": "HTML", "bytes": "3408" }, { "name": "JavaScript", "bytes": "179224" }, { "name": "Python", "bytes": "585" }, { "name": "Shell", "bytes": "240" } ], "symlink_target": "" }
/** * @author Dan Nuffer */ #ifndef OW_PROVIDER_IFC_LOADER_HPP_ #define OW_PROVIDER_IFC_LOADER_HPP_ #include "OW_config.h" #include "OW_SharedLibraryLoader.hpp" #include "OW_SharedLibrary.hpp" #include "OW_ProviderIFCBaseIFC.hpp" #include "OW_Array.hpp" #include "OW_String.hpp" #include "OW_ServiceEnvironmentIFC.hpp" #include "OW_IntrusiveReference.hpp" #include "OW_IntrusiveCountableBase.hpp" #include "OW_CimomCommonFwd.hpp" namespace OW_NAMESPACE { /** * This class is a base class for different provider interface loading * strategies. Each derived class should implement a method of locating the * provider interface shared libraries. The loadIFCs function needs to be * overridden, and then the createProviderIFCFromLib function can be used to * actually load the shared library. */ class OW_CIMOMCOMMON_API ProviderIFCLoaderBase : public IntrusiveCountableBase { public: ProviderIFCLoaderBase(SharedLibraryLoaderRef sll, ServiceEnvironmentIFCRef env) : m_sll( sll ) , m_env(env) { } virtual ~ProviderIFCLoaderBase(); /** * This function needs to be overridden by derived classes and implement a * strategy to obtain the shared library names of the provider interfaces. * Once the file names are obtained it should call createProviderIFCFromLib * and add the returned provider interface into interfaces. * * @param interfaces This is an out parameter. The ProviderIFC refs will be * added to the array. * @param shlibs This is an our parameter. The shared libraries of the * ProviderIFC refs will be added to this array. NOTE: The provider * IFC refs MUST go away and delete the underlying object before the * libraries are deleted, otherwise the program will segfault. * * The derived classes code will probably be similar to this: * virtual void loadIFCs( * Array<ProviderIFCBaseIFCRef>& ifcs, * Array<SharedLibraryRef>& shlibs) const * { * ifc_lib_pair rval; * rval = createProviderIFCFromLib( "libname" ); * if ( !rval.first.isNull() && !rval.second.isNull() ) * { * out.push_back( rval.first ); * shlibs.push_back( rval.second ); * } * * rval = createProviderIFCFromLib( "libname2" ); * if ( !rval.first.isNull() && !rval.second.isNull() ) * { * out.push_back( rval.first ); * shlibs.push_back( rval.second ); * } * } * */ virtual void loadIFCs( Array<ProviderIFCBaseIFCRef>& interfaces) const = 0; ServiceEnvironmentIFCRef getEnvironment() const { return m_env; } protected: /** * Function uses the SharedLibraryLoader to load the library designated * by libname (probably a filename) and creates an ProviderIFCBaseIFCRef. * * @param libname The name of the library to load. * * @returns A pair containing a ref counted pointer to the ProviderIFCBaseIFC * corresponding to libname and a ref counted point to the corresponding * SharedLibrary. If loading the library fails, null is returned. * e.g. retval.first.isNull() == true and retval.second.isNull() == true. */ ProviderIFCBaseIFCRef createProviderIFCFromLib(const String& libname) const; private: //ProviderIFCBaseIFC* safeCreateIFC(SharedLibraryRef sl) const; const SharedLibraryLoaderRef m_sll; ServiceEnvironmentIFCRef m_env; }; class OW_CIMOMCOMMON_API ProviderIFCLoader : public ProviderIFCLoaderBase { public: ProviderIFCLoader(SharedLibraryLoaderRef sll, ServiceEnvironmentIFCRef env) : ProviderIFCLoaderBase(sll, env) {} virtual ~ProviderIFCLoader(); virtual void loadIFCs(Array<ProviderIFCBaseIFCRef>& ifcs) const; /// Factory function static ProviderIFCLoaderRef createProviderIFCLoader( ServiceEnvironmentIFCRef env); }; } // end namespace OW_NAMESPACE #endif
{ "content_hash": "9f4f06719d0b67ebf899fdb7a863aa82", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 78, "avg_line_length": 31.905982905982906, "alnum_prop": 0.7356013929815162, "repo_name": "kkaempf/openwbem", "id": "c37a5350e5283c7230263696e74cd34d6436ff8a", "size": "5438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cimom/common/OW_ProviderIFCLoader.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "447743" }, { "name": "C++", "bytes": "8054531" }, { "name": "Perl", "bytes": "2789" }, { "name": "Shell", "bytes": "102214" } ], "symlink_target": "" }
require 'rails_helper' describe TestingModule::KlassMethods do let(:klass_methods) do TestingModule::KlassMethods.new end it '#defined_with_self' do expect(TestingModule::KlassMethods.defined_with_self(5)).to eq(5) end it '#defined_with_back_back_self' do expect(TestingModule::KlassMethods.defined_with_back_back_self(5)).to eq(5) end it '#back_to_public_defined_with_self' do expect(TestingModule::KlassMethods.back_to_public_defined_with_self(5)).to eq(5) end end
{ "content_hash": "3634587f52667b2c3c31e91dba5f7b51", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 84, "avg_line_length": 26.473684210526315, "alnum_prop": 0.7276341948310139, "repo_name": "Nedomas/zapata", "id": "404ba5959623720e8d7b034920a9b776ff2a3711", "size": "503", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/support/rails_test_app/spec/models/testing_module/klass_methods_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "683" }, { "name": "HTML", "bytes": "4893" }, { "name": "JavaScript", "bytes": "765" }, { "name": "Ruby", "bytes": "75742" }, { "name": "Shell", "bytes": "218" } ], "symlink_target": "" }
#include "tclInt.h" /* * Each invocation of the "package ifneeded" command creates a structure of * the following type, which is used to load the package into the interpreter * if it is requested with a "package require" command. */ typedef struct PkgAvail { char *version; /* Version string; malloc'ed. */ char *script; /* Script to invoke to provide this version of * the package. Malloc'ed and protected by * Tcl_Preserve and Tcl_Release. */ struct PkgAvail *nextPtr; /* Next in list of available versions of the * same package. */ } PkgAvail; /* * For each package that is known in any way to an interpreter, there is one * record of the following type. These records are stored in the * "packageTable" hash table in the interpreter, keyed by package name such as * "Tk" (no version number). */ typedef struct Package { char *version; /* Version that has been supplied in this * interpreter via "package provide" * (malloc'ed). NULL means the package doesn't * exist in this interpreter yet. */ PkgAvail *availPtr; /* First in list of all available versions of * this package. */ const void *clientData; /* Client data. */ } Package; /* * Prototypes for functions defined in this file: */ static int CheckVersionAndConvert(Tcl_Interp *interp, const char *string, char **internal, int *stable); static int CompareVersions(char *v1i, char *v2i, int *isMajorPtr); static int CheckRequirement(Tcl_Interp *interp, const char *string); static int CheckAllRequirements(Tcl_Interp *interp, int reqc, Tcl_Obj *const reqv[]); static int RequirementSatisfied(char *havei, const char *req); static int SomeRequirementSatisfied(char *havei, int reqc, Tcl_Obj *const reqv[]); static void AddRequirementsToResult(Tcl_Interp *interp, int reqc, Tcl_Obj *const reqv[]); static void AddRequirementsToDString(Tcl_DString *dstring, int reqc, Tcl_Obj *const reqv[]); static Package * FindPackage(Tcl_Interp *interp, const char *name); static const char * PkgRequireCore(Tcl_Interp *interp, const char *name, int reqc, Tcl_Obj *const reqv[], void *clientDataPtr); /* * Helper macros. */ #define DupBlock(v,s,len) \ ((v) = ckalloc(len), memcpy((v),(s),(len))) #define DupString(v,s) \ do { \ unsigned local__len = (unsigned) (strlen(s) + 1); \ DupBlock((v),(s),local__len); \ } while (0) /* *---------------------------------------------------------------------- * * Tcl_PkgProvide / Tcl_PkgProvideEx -- * * This function is invoked to declare that a particular version of a * particular package is now present in an interpreter. There must not be * any other version of this package already provided in the interpreter. * * Results: * Normally returns TCL_OK; if there is already another version of the * package loaded then TCL_ERROR is returned and an error message is left * in the interp's result. * * Side effects: * The interpreter remembers that this package is available, so that no * other version of the package may be provided for the interpreter. * *---------------------------------------------------------------------- */ #undef Tcl_PkgProvide int Tcl_PkgProvide( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of package. */ const char *version) /* Version string for package. */ { return Tcl_PkgProvideEx(interp, name, version, NULL); } int Tcl_PkgProvideEx( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of package. */ const char *version, /* Version string for package. */ const void *clientData) /* clientdata for this package (normally used * for C callback function table) */ { Package *pkgPtr; char *pvi, *vi; int res; pkgPtr = FindPackage(interp, name); if (pkgPtr->version == NULL) { DupString(pkgPtr->version, version); pkgPtr->clientData = clientData; return TCL_OK; } if (CheckVersionAndConvert(interp, pkgPtr->version, &pvi, NULL) != TCL_OK) { return TCL_ERROR; } else if (CheckVersionAndConvert(interp, version, &vi, NULL) != TCL_OK) { ckfree(pvi); return TCL_ERROR; } res = CompareVersions(pvi, vi, NULL); ckfree(pvi); ckfree(vi); if (res == 0) { if (clientData != NULL) { pkgPtr->clientData = clientData; } return TCL_OK; } Tcl_SetObjResult(interp, Tcl_ObjPrintf( "conflicting versions provided for package \"%s\": %s, then %s", name, pkgPtr->version, version)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "VERSIONCONFLICT", NULL); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * Tcl_PkgRequire / Tcl_PkgRequireEx / Tcl_PkgRequireProc -- * * This function is called by code that depends on a particular version * of a particular package. If the package is not already provided in the * interpreter, this function invokes a Tcl script to provide it. If the * package is already provided, this function makes sure that the * caller's needs don't conflict with the version that is present. * * Results: * If successful, returns the version string for the currently provided * version of the package, which may be different from the "version" * argument. If the caller's requirements cannot be met (e.g. the version * requested conflicts with a currently provided version, or the required * version cannot be found, or the script to provide the required version * generates an error), NULL is returned and an error message is left in * the interp's result. * * Side effects: * The script from some previous "package ifneeded" command may be * invoked to provide the package. * *---------------------------------------------------------------------- */ #undef Tcl_PkgRequire const char * Tcl_PkgRequire( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ const char *version, /* Version string for desired version; NULL * means use the latest version available. */ int exact) /* Non-zero means that only the particular * version given is acceptable. Zero means use * the latest compatible version. */ { return Tcl_PkgRequireEx(interp, name, version, exact, NULL); } const char * Tcl_PkgRequireEx( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ const char *version, /* Version string for desired version; NULL * means use the latest version available. */ int exact, /* Non-zero means that only the particular * version given is acceptable. Zero means use * the latest compatible version. */ void *clientDataPtr) /* Used to return the client data for this * package. If it is NULL then the client data * is not returned. This is unchanged if this * call fails for any reason. */ { Tcl_Obj *ov; const char *result = NULL; /* * If an attempt is being made to load this into a standalone executable * on a platform where backlinking is not supported then this must be a * shared version of Tcl (Otherwise the load would have failed). Detect * this situation by checking that this library has been correctly * initialised. If it has not been then return immediately as nothing will * work. */ if (tclEmptyStringRep == NULL) { /* * OK, so what's going on here? * * First, what are we doing? We are performing a check on behalf of * one particular caller, Tcl_InitStubs(). When a package is stub- * enabled, it is statically linked to libtclstub.a, which contains a * copy of Tcl_InitStubs(). When a stub-enabled package is loaded, its * *_Init() function is supposed to call Tcl_InitStubs() before * calling any other functions in the Tcl library. The first Tcl * function called by Tcl_InitStubs() through the stub table is * Tcl_PkgRequireEx(), so this code right here is the first code that * is part of the original Tcl library in the executable that gets * executed on behalf of a newly loaded stub-enabled package. * * One easy error for the developer/builder of a stub-enabled package * to make is to forget to define USE_TCL_STUBS when compiling the * package. When that happens, the package will contain symbols that * are references to the Tcl library, rather than function pointers * referencing the stub table. On platforms that lack backlinking, * those unresolved references may cause the loading of the package to * also load a second copy of the Tcl library, leading to all kinds of * trouble. We would like to catch that error and report a useful * message back to the user. That's what we're doing. * * Second, how does this work? If we reach this point, then the global * variable tclEmptyStringRep has the value NULL. Compare that with * the definition of tclEmptyStringRep near the top of the file * generic/tclObj.c. It clearly should not have the value NULL; it * should point to the char tclEmptyString. If we see it having the * value NULL, then somehow we are seeing a Tcl library that isn't * completely initialized, and that's an indicator for the error * condition described above. (Further explanation is welcome.) * * Third, so what do we do about it? This situation indicates the * package we just loaded wasn't properly compiled to be stub-enabled, * yet it thinks it is stub-enabled (it called Tcl_InitStubs()). We * want to report that the package just loaded is broken, so we want * to place an error message in the interpreter result and return NULL * to indicate failure to Tcl_InitStubs() so that it will also fail. * (Further explanation why we don't want to Tcl_Panic() is welcome. * After all, two Tcl libraries can't be a good thing!) * * Trouble is that's going to be tricky. We're now using a Tcl library * that's not fully initialized. In particular, it doesn't have a * proper value for tclEmptyStringRep. The Tcl_Obj system heavily * depends on the value of tclEmptyStringRep and all of Tcl depends * (increasingly) on the Tcl_Obj system, we need to correct that flaw * before making the calls to set the interpreter result to the error * message. That's the only flaw corrected; other problems with * initialization of the Tcl library are not remedied, so be very * careful about adding any other calls here without checking how they * behave when initialization is incomplete. */ tclEmptyStringRep = &tclEmptyString; Tcl_SetObjResult(interp, Tcl_ObjPrintf( "Cannot load package \"%s\" in standalone executable:" " This package is not compiled with stub support", name)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "UNSTUBBED", NULL); return NULL; } /* * Translate between old and new API, and defer to the new function. */ if (version == NULL) { result = PkgRequireCore(interp, name, 0, NULL, clientDataPtr); } else { if (exact && TCL_OK != CheckVersionAndConvert(interp, version, NULL, NULL)) { return NULL; } ov = Tcl_NewStringObj(version, -1); if (exact) { Tcl_AppendStringsToObj(ov, "-", version, NULL); } Tcl_IncrRefCount(ov); result = PkgRequireCore(interp, name, 1, &ov, clientDataPtr); TclDecrRefCount(ov); } return result; } int Tcl_PkgRequireProc( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ int reqc, /* Requirements constraining the desired * version. */ Tcl_Obj *const reqv[], /* 0 means to use the latest version * available. */ void *clientDataPtr) { const char *result = PkgRequireCore(interp, name, reqc, reqv, clientDataPtr); if (result == NULL) { return TCL_ERROR; } Tcl_SetObjResult(interp, Tcl_NewStringObj(result, -1)); return TCL_OK; } static const char * PkgRequireCore( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ int reqc, /* Requirements constraining the desired * version. */ Tcl_Obj *const reqv[], /* 0 means to use the latest version * available. */ void *clientDataPtr) { Interp *iPtr = (Interp *) interp; Package *pkgPtr; PkgAvail *availPtr, *bestPtr, *bestStablePtr; char *availVersion, *bestVersion; /* Internal rep. of versions */ int availStable, code, satisfies, pass; char *script, *pkgVersionI; Tcl_DString command; if (TCL_OK != CheckAllRequirements(interp, reqc, reqv)) { return NULL; } /* * It can take up to three passes to find the package: one pass to run the * "package unknown" script, one to run the "package ifneeded" script for * a specific version, and a final pass to lookup the package loaded by * the "package ifneeded" script. */ for (pass=1 ;; pass++) { pkgPtr = FindPackage(interp, name); if (pkgPtr->version != NULL) { break; } /* * Check whether we're already attempting to load some version of this * package (circular dependency detection). */ if (pkgPtr->clientData != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "circular package dependency:" " attempt to provide %s %s requires %s", name, (char *) pkgPtr->clientData, name)); AddRequirementsToResult(interp, reqc, reqv); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "CIRCULARITY", NULL); return NULL; } /* * The package isn't yet present. Search the list of available * versions and invoke the script for the best available version. We * are actually locating the best, and the best stable version. One of * them is then chosen based on the selection mode. */ bestPtr = NULL; bestStablePtr = NULL; bestVersion = NULL; for (availPtr = pkgPtr->availPtr; availPtr != NULL; availPtr = availPtr->nextPtr) { if (CheckVersionAndConvert(interp, availPtr->version, &availVersion, &availStable) != TCL_OK) { /* * The provided version number has invalid syntax. This * should not happen. This should have been caught by the * 'package ifneeded' registering the package. */ continue; } if (bestPtr != NULL) { int res = CompareVersions(availVersion, bestVersion, NULL); /* * Note: Use internal reps! */ if (res <= 0) { /* * The version of the package sought is not as good as the * currently selected version. Ignore it. */ ckfree(availVersion); availVersion = NULL; continue; } } /* * We have found a version which is better than our max. */ if (reqc > 0) { /* Check satisfaction of requirements. */ satisfies = SomeRequirementSatisfied(availVersion, reqc, reqv); if (!satisfies) { ckfree(availVersion); availVersion = NULL; continue; } } bestPtr = availPtr; if (bestVersion != NULL) { ckfree(bestVersion); } bestVersion = availVersion; /* * If this new best version is stable then it also has to be * better than the max stable version found so far. */ if (availStable) { bestStablePtr = availPtr; } } if (bestVersion != NULL) { ckfree(bestVersion); } /* * Now choose a version among the two best. For 'latest' we simply * take (actually keep) the best. For 'stable' we take the best * stable, if there is any, or the best if there is nothing stable. */ if ((iPtr->packagePrefer == PKG_PREFER_STABLE) && (bestStablePtr != NULL)) { bestPtr = bestStablePtr; } if (bestPtr != NULL) { /* * We found an ifneeded script for the package. Be careful while * executing it: this could cause reentrancy, so (a) protect the * script itself from deletion and (b) don't assume that bestPtr * will still exist when the script completes. */ char *versionToProvide = bestPtr->version; script = bestPtr->script; pkgPtr->clientData = versionToProvide; Tcl_Preserve(script); Tcl_Preserve(versionToProvide); code = Tcl_EvalEx(interp, script, -1, TCL_EVAL_GLOBAL); Tcl_Release(script); pkgPtr = FindPackage(interp, name); if (code == TCL_OK) { Tcl_ResetResult(interp); if (pkgPtr->version == NULL) { code = TCL_ERROR; Tcl_SetObjResult(interp, Tcl_ObjPrintf( "attempt to provide package %s %s failed:" " no version of package %s provided", name, versionToProvide, name)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "UNPROVIDED", NULL); } else { char *pvi, *vi; if (CheckVersionAndConvert(interp, pkgPtr->version, &pvi, NULL) != TCL_OK) { code = TCL_ERROR; } else if (CheckVersionAndConvert(interp, versionToProvide, &vi, NULL) != TCL_OK) { ckfree(pvi); code = TCL_ERROR; } else { int res = CompareVersions(pvi, vi, NULL); ckfree(pvi); ckfree(vi); if (res != 0) { code = TCL_ERROR; Tcl_SetObjResult(interp, Tcl_ObjPrintf( "attempt to provide package %s %s failed:" " package %s %s provided instead", name, versionToProvide, name, pkgPtr->version)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "WRONGPROVIDE", NULL); } } } } else if (code != TCL_ERROR) { Tcl_Obj *codePtr = Tcl_NewIntObj(code); Tcl_SetObjResult(interp, Tcl_ObjPrintf( "attempt to provide package %s %s failed:" " bad return code: %s", name, versionToProvide, TclGetString(codePtr))); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "BADRESULT", NULL); TclDecrRefCount(codePtr); code = TCL_ERROR; } if (code == TCL_ERROR) { Tcl_AppendObjToErrorInfo(interp, Tcl_ObjPrintf( "\n (\"package ifneeded %s %s\" script)", name, versionToProvide)); } Tcl_Release(versionToProvide); if (code != TCL_OK) { /* * Take a non-TCL_OK code from the script as an indication the * package wasn't loaded properly, so the package system * should not remember an improper load. * * This is consistent with our returning NULL. If we're not * willing to tell our caller we got a particular version, we * shouldn't store that version for telling future callers * either. */ if (pkgPtr->version != NULL) { ckfree(pkgPtr->version); pkgPtr->version = NULL; } pkgPtr->clientData = NULL; return NULL; } break; } /* * The package is not in the database. If there is a "package unknown" * command, invoke it (but only on the first pass; after that, we * should not get here in the first place). */ if (pass > 1) { break; } script = ((Interp *) interp)->packageUnknown; if (script != NULL) { Tcl_DStringInit(&command); Tcl_DStringAppend(&command, script, -1); Tcl_DStringAppendElement(&command, name); AddRequirementsToDString(&command, reqc, reqv); code = Tcl_EvalEx(interp, Tcl_DStringValue(&command), Tcl_DStringLength(&command), TCL_EVAL_GLOBAL); Tcl_DStringFree(&command); if ((code != TCL_OK) && (code != TCL_ERROR)) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "bad return code: %d", code)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "BADRESULT", NULL); code = TCL_ERROR; } if (code == TCL_ERROR) { Tcl_AddErrorInfo(interp, "\n (\"package unknown\" script)"); return NULL; } Tcl_ResetResult(interp); } } if (pkgPtr->version == NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "can't find package %s", name)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "UNFOUND", NULL); AddRequirementsToResult(interp, reqc, reqv); return NULL; } /* * At this point we know that the package is present. Make sure that the * provided version meets the current requirements. */ if (reqc != 0) { CheckVersionAndConvert(interp, pkgPtr->version, &pkgVersionI, NULL); satisfies = SomeRequirementSatisfied(pkgVersionI, reqc, reqv); ckfree(pkgVersionI); if (!satisfies) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "version conflict for package \"%s\": have %s, need", name, pkgPtr->version)); Tcl_SetErrorCode(interp, "TCL", "PACKAGE", "VERSIONCONFLICT", NULL); AddRequirementsToResult(interp, reqc, reqv); return NULL; } } if (clientDataPtr) { const void **ptr = (const void **) clientDataPtr; *ptr = pkgPtr->clientData; } return pkgPtr->version; } /* *---------------------------------------------------------------------- * * Tcl_PkgPresent / Tcl_PkgPresentEx -- * * Checks to see whether the specified package is present. If it is not * then no additional action is taken. * * Results: * If successful, returns the version string for the currently provided * version of the package, which may be different from the "version" * argument. If the caller's requirements cannot be met (e.g. the version * requested conflicts with a currently provided version), NULL is * returned and an error message is left in interp->result. * * Side effects: * None. * *---------------------------------------------------------------------- */ #undef Tcl_PkgPresent const char * Tcl_PkgPresent( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ const char *version, /* Version string for desired version; NULL * means use the latest version available. */ int exact) /* Non-zero means that only the particular * version given is acceptable. Zero means use * the latest compatible version. */ { return Tcl_PkgPresentEx(interp, name, version, exact, NULL); } const char * Tcl_PkgPresentEx( Tcl_Interp *interp, /* Interpreter in which package is now * available. */ const char *name, /* Name of desired package. */ const char *version, /* Version string for desired version; NULL * means use the latest version available. */ int exact, /* Non-zero means that only the particular * version given is acceptable. Zero means use * the latest compatible version. */ void *clientDataPtr) /* Used to return the client data for this * package. If it is NULL then the client data * is not returned. This is unchanged if this * call fails for any reason. */ { Interp *iPtr = (Interp *) interp; Tcl_HashEntry *hPtr; Package *pkgPtr; hPtr = Tcl_FindHashEntry(&iPtr->packageTable, name); if (hPtr) { pkgPtr = Tcl_GetHashValue(hPtr); if (pkgPtr->version != NULL) { /* * At this point we know that the package is present. Make sure * that the provided version meets the current requirement by * calling Tcl_PkgRequireEx() to check for us. */ const char *foundVersion = Tcl_PkgRequireEx(interp, name, version, exact, clientDataPtr); if (foundVersion == NULL) { Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "PACKAGE", name, NULL); } return foundVersion; } } if (version != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "package %s %s is not present", name, version)); } else { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "package %s is not present", name)); } Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "PACKAGE", name, NULL); return NULL; } /* *---------------------------------------------------------------------- * * Tcl_PackageObjCmd -- * * This function is invoked to process the "package" Tcl command. See the * user documentation for details on what it does. * * Results: * A standard Tcl result. * * Side effects: * See the user documentation. * *---------------------------------------------------------------------- */ /* ARGSUSED */ int Tcl_PackageObjCmd( ClientData dummy, /* Not used. */ Tcl_Interp *interp, /* Current interpreter. */ int objc, /* Number of arguments. */ Tcl_Obj *const objv[]) /* Argument objects. */ { static const char *const pkgOptions[] = { "forget", "ifneeded", "names", "prefer", "present", "provide", "require", "unknown", "vcompare", "versions", "vsatisfies", NULL }; enum pkgOptions { PKG_FORGET, PKG_IFNEEDED, PKG_NAMES, PKG_PREFER, PKG_PRESENT, PKG_PROVIDE, PKG_REQUIRE, PKG_UNKNOWN, PKG_VCOMPARE, PKG_VERSIONS, PKG_VSATISFIES }; Interp *iPtr = (Interp *) interp; int optionIndex, exact, i, satisfies; PkgAvail *availPtr, *prevPtr; Package *pkgPtr; Tcl_HashEntry *hPtr; Tcl_HashSearch search; Tcl_HashTable *tablePtr; const char *version; const char *argv2, *argv3, *argv4; char *iva = NULL, *ivb = NULL; if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?"); return TCL_ERROR; } if (Tcl_GetIndexFromObj(interp, objv[1], pkgOptions, "option", 0, &optionIndex) != TCL_OK) { return TCL_ERROR; } switch ((enum pkgOptions) optionIndex) { case PKG_FORGET: { const char *keyString; for (i = 2; i < objc; i++) { keyString = TclGetString(objv[i]); hPtr = Tcl_FindHashEntry(&iPtr->packageTable, keyString); if (hPtr == NULL) { continue; } pkgPtr = Tcl_GetHashValue(hPtr); Tcl_DeleteHashEntry(hPtr); if (pkgPtr->version != NULL) { ckfree(pkgPtr->version); } while (pkgPtr->availPtr != NULL) { availPtr = pkgPtr->availPtr; pkgPtr->availPtr = availPtr->nextPtr; Tcl_EventuallyFree(availPtr->version, TCL_DYNAMIC); Tcl_EventuallyFree(availPtr->script, TCL_DYNAMIC); ckfree(availPtr); } ckfree(pkgPtr); } break; } case PKG_IFNEEDED: { int length, res; char *argv3i, *avi; if ((objc != 4) && (objc != 5)) { Tcl_WrongNumArgs(interp, 2, objv, "package version ?script?"); return TCL_ERROR; } argv3 = TclGetString(objv[3]); if (CheckVersionAndConvert(interp, argv3, &argv3i, NULL) != TCL_OK) { return TCL_ERROR; } argv2 = TclGetString(objv[2]); if (objc == 4) { hPtr = Tcl_FindHashEntry(&iPtr->packageTable, argv2); if (hPtr == NULL) { ckfree(argv3i); return TCL_OK; } pkgPtr = Tcl_GetHashValue(hPtr); } else { pkgPtr = FindPackage(interp, argv2); } argv3 = Tcl_GetStringFromObj(objv[3], &length); for (availPtr = pkgPtr->availPtr, prevPtr = NULL; availPtr != NULL; prevPtr = availPtr, availPtr = availPtr->nextPtr) { if (CheckVersionAndConvert(interp, availPtr->version, &avi, NULL) != TCL_OK) { ckfree(argv3i); return TCL_ERROR; } res = CompareVersions(avi, argv3i, NULL); ckfree(avi); if (res == 0){ if (objc == 4) { ckfree(argv3i); Tcl_SetObjResult(interp, Tcl_NewStringObj(availPtr->script, -1)); return TCL_OK; } Tcl_EventuallyFree(availPtr->script, TCL_DYNAMIC); break; } } ckfree(argv3i); if (objc == 4) { return TCL_OK; } if (availPtr == NULL) { availPtr = ckalloc(sizeof(PkgAvail)); DupBlock(availPtr->version, argv3, (unsigned) length + 1); if (prevPtr == NULL) { availPtr->nextPtr = pkgPtr->availPtr; pkgPtr->availPtr = availPtr; } else { availPtr->nextPtr = prevPtr->nextPtr; prevPtr->nextPtr = availPtr; } } argv4 = Tcl_GetStringFromObj(objv[4], &length); DupBlock(availPtr->script, argv4, (unsigned) length + 1); break; } case PKG_NAMES: if (objc != 2) { Tcl_WrongNumArgs(interp, 2, objv, NULL); return TCL_ERROR; } else { Tcl_Obj *resultObj; resultObj = Tcl_NewObj(); tablePtr = &iPtr->packageTable; for (hPtr = Tcl_FirstHashEntry(tablePtr, &search); hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { pkgPtr = Tcl_GetHashValue(hPtr); if ((pkgPtr->version != NULL) || (pkgPtr->availPtr != NULL)) { Tcl_ListObjAppendElement(NULL,resultObj, Tcl_NewStringObj( Tcl_GetHashKey(tablePtr, hPtr), -1)); } } Tcl_SetObjResult(interp, resultObj); } break; case PKG_PRESENT: { const char *name; if (objc < 3) { goto require; } argv2 = TclGetString(objv[2]); if ((argv2[0] == '-') && (strcmp(argv2, "-exact") == 0)) { if (objc != 5) { goto requireSyntax; } exact = 1; name = TclGetString(objv[3]); } else { exact = 0; name = argv2; } hPtr = Tcl_FindHashEntry(&iPtr->packageTable, name); if (hPtr != NULL) { pkgPtr = Tcl_GetHashValue(hPtr); if (pkgPtr->version != NULL) { goto require; } } version = NULL; if (exact) { version = TclGetString(objv[4]); if (CheckVersionAndConvert(interp, version, NULL, NULL) != TCL_OK) { return TCL_ERROR; } } else { if (CheckAllRequirements(interp, objc-3, objv+3) != TCL_OK) { return TCL_ERROR; } if ((objc > 3) && (CheckVersionAndConvert(interp, TclGetString(objv[3]), NULL, NULL) == TCL_OK)) { version = TclGetString(objv[3]); } } Tcl_PkgPresentEx(interp, name, version, exact, NULL); return TCL_ERROR; break; } case PKG_PROVIDE: if ((objc != 3) && (objc != 4)) { Tcl_WrongNumArgs(interp, 2, objv, "package ?version?"); return TCL_ERROR; } argv2 = TclGetString(objv[2]); if (objc == 3) { hPtr = Tcl_FindHashEntry(&iPtr->packageTable, argv2); if (hPtr != NULL) { pkgPtr = Tcl_GetHashValue(hPtr); if (pkgPtr->version != NULL) { Tcl_SetObjResult(interp, Tcl_NewStringObj(pkgPtr->version, -1)); } } return TCL_OK; } argv3 = TclGetString(objv[3]); if (CheckVersionAndConvert(interp, argv3, NULL, NULL) != TCL_OK) { return TCL_ERROR; } return Tcl_PkgProvideEx(interp, argv2, argv3, NULL); case PKG_REQUIRE: require: if (objc < 3) { requireSyntax: Tcl_WrongNumArgs(interp, 2, objv, "?-exact? package ?requirement ...?"); return TCL_ERROR; } version = NULL; argv2 = TclGetString(objv[2]); if ((argv2[0] == '-') && (strcmp(argv2, "-exact") == 0)) { Tcl_Obj *ov; int res; if (objc != 5) { goto requireSyntax; } version = TclGetString(objv[4]); if (CheckVersionAndConvert(interp, version, NULL, NULL) != TCL_OK) { return TCL_ERROR; } /* * Create a new-style requirement for the exact version. */ ov = Tcl_NewStringObj(version, -1); Tcl_AppendStringsToObj(ov, "-", version, NULL); version = NULL; argv3 = TclGetString(objv[3]); Tcl_IncrRefCount(ov); res = Tcl_PkgRequireProc(interp, argv3, 1, &ov, NULL); TclDecrRefCount(ov); return res; } else { if (CheckAllRequirements(interp, objc-3, objv+3) != TCL_OK) { return TCL_ERROR; } return Tcl_PkgRequireProc(interp, argv2, objc-3, objv+3, NULL); } break; case PKG_UNKNOWN: { int length; if (objc == 2) { if (iPtr->packageUnknown != NULL) { Tcl_SetObjResult(interp, Tcl_NewStringObj(iPtr->packageUnknown, -1)); } } else if (objc == 3) { if (iPtr->packageUnknown != NULL) { ckfree(iPtr->packageUnknown); } argv2 = Tcl_GetStringFromObj(objv[2], &length); if (argv2[0] == 0) { iPtr->packageUnknown = NULL; } else { DupBlock(iPtr->packageUnknown, argv2, (unsigned) length+1); } } else { Tcl_WrongNumArgs(interp, 2, objv, "?command?"); return TCL_ERROR; } break; } case PKG_PREFER: { static const char *const pkgPreferOptions[] = { "latest", "stable", NULL }; /* * See tclInt.h for the enum, just before Interp. */ if (objc > 3) { Tcl_WrongNumArgs(interp, 2, objv, "?latest|stable?"); return TCL_ERROR; } else if (objc == 3) { /* * Seting the value. */ int newPref; if (Tcl_GetIndexFromObj(interp, objv[2], pkgPreferOptions, "preference", 0, &newPref) != TCL_OK) { return TCL_ERROR; } if (newPref < iPtr->packagePrefer) { iPtr->packagePrefer = newPref; } } /* * Always return current value. */ Tcl_SetObjResult(interp, Tcl_NewStringObj(pkgPreferOptions[iPtr->packagePrefer], -1)); break; } case PKG_VCOMPARE: if (objc != 4) { Tcl_WrongNumArgs(interp, 2, objv, "version1 version2"); return TCL_ERROR; } argv3 = TclGetString(objv[3]); argv2 = TclGetString(objv[2]); if (CheckVersionAndConvert(interp, argv2, &iva, NULL) != TCL_OK || CheckVersionAndConvert(interp, argv3, &ivb, NULL) != TCL_OK) { if (iva != NULL) { ckfree(iva); } /* * ivb cannot be set in this branch. */ return TCL_ERROR; } /* * Comparison is done on the internal representation. */ Tcl_SetObjResult(interp, Tcl_NewIntObj(CompareVersions(iva, ivb, NULL))); ckfree(iva); ckfree(ivb); break; case PKG_VERSIONS: if (objc != 3) { Tcl_WrongNumArgs(interp, 2, objv, "package"); return TCL_ERROR; } else { Tcl_Obj *resultObj = Tcl_NewObj(); argv2 = TclGetString(objv[2]); hPtr = Tcl_FindHashEntry(&iPtr->packageTable, argv2); if (hPtr != NULL) { pkgPtr = Tcl_GetHashValue(hPtr); for (availPtr = pkgPtr->availPtr; availPtr != NULL; availPtr = availPtr->nextPtr) { Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj(availPtr->version, -1)); } } Tcl_SetObjResult(interp, resultObj); } break; case PKG_VSATISFIES: { char *argv2i = NULL; if (objc < 4) { Tcl_WrongNumArgs(interp, 2, objv, "version ?requirement ...?"); return TCL_ERROR; } argv2 = TclGetString(objv[2]); if (CheckVersionAndConvert(interp, argv2, &argv2i, NULL) != TCL_OK) { return TCL_ERROR; } else if (CheckAllRequirements(interp, objc-3, objv+3) != TCL_OK) { ckfree(argv2i); return TCL_ERROR; } satisfies = SomeRequirementSatisfied(argv2i, objc-3, objv+3); ckfree(argv2i); Tcl_SetObjResult(interp, Tcl_NewBooleanObj(satisfies)); break; } default: Tcl_Panic("Tcl_PackageObjCmd: bad option index to pkgOptions"); } return TCL_OK; } /* *---------------------------------------------------------------------- * * FindPackage -- * * This function finds the Package record for a particular package in a * particular interpreter, creating a record if one doesn't already * exist. * * Results: * The return value is a pointer to the Package record for the package. * * Side effects: * A new Package record may be created. * *---------------------------------------------------------------------- */ static Package * FindPackage( Tcl_Interp *interp, /* Interpreter to use for package lookup. */ const char *name) /* Name of package to fine. */ { Interp *iPtr = (Interp *) interp; Tcl_HashEntry *hPtr; int isNew; Package *pkgPtr; hPtr = Tcl_CreateHashEntry(&iPtr->packageTable, name, &isNew); if (isNew) { pkgPtr = ckalloc(sizeof(Package)); pkgPtr->version = NULL; pkgPtr->availPtr = NULL; pkgPtr->clientData = NULL; Tcl_SetHashValue(hPtr, pkgPtr); } else { pkgPtr = Tcl_GetHashValue(hPtr); } return pkgPtr; } /* *---------------------------------------------------------------------- * * TclFreePackageInfo -- * * This function is called during interpreter deletion to free all of the * package-related information for the interpreter. * * Results: * None. * * Side effects: * Memory is freed. * *---------------------------------------------------------------------- */ void TclFreePackageInfo( Interp *iPtr) /* Interpereter that is being deleted. */ { Package *pkgPtr; Tcl_HashSearch search; Tcl_HashEntry *hPtr; PkgAvail *availPtr; for (hPtr = Tcl_FirstHashEntry(&iPtr->packageTable, &search); hPtr != NULL; hPtr = Tcl_NextHashEntry(&search)) { pkgPtr = Tcl_GetHashValue(hPtr); if (pkgPtr->version != NULL) { ckfree(pkgPtr->version); } while (pkgPtr->availPtr != NULL) { availPtr = pkgPtr->availPtr; pkgPtr->availPtr = availPtr->nextPtr; Tcl_EventuallyFree(availPtr->version, TCL_DYNAMIC); Tcl_EventuallyFree(availPtr->script, TCL_DYNAMIC); ckfree(availPtr); } ckfree(pkgPtr); } Tcl_DeleteHashTable(&iPtr->packageTable); if (iPtr->packageUnknown != NULL) { ckfree(iPtr->packageUnknown); } } /* *---------------------------------------------------------------------- * * CheckVersionAndConvert -- * * This function checks to see whether a version number has valid syntax. * It also generates a semi-internal representation (string rep of a list * of numbers). * * Results: * If string is a properly formed version number the TCL_OK is returned. * Otherwise TCL_ERROR is returned and an error message is left in the * interp's result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CheckVersionAndConvert( Tcl_Interp *interp, /* Used for error reporting. */ const char *string, /* Supposedly a version number, which is * groups of decimal digits separated by * dots. */ char **internal, /* Internal normalized representation */ int *stable) /* Flag: Version is (un)stable. */ { const char *p = string; char prevChar; int hasunstable = 0; /* * 4* assuming that each char is a separator (a,b become ' -x '). * 4+ to have spce for an additional -2 at the end */ char *ibuf = ckalloc(4 + 4*strlen(string)); char *ip = ibuf; /* * Basic rules * (1) First character has to be a digit. * (2) All other characters have to be a digit or '.' * (3) Two '.'s may not follow each other. * * TIP 268, Modified rules * (1) s.a. * (2) All other characters have to be a digit, 'a', 'b', or '.' * (3) s.a. * (4) Only one of 'a' or 'b' may occur. * (5) Neither 'a', nor 'b' may occur before or after a '.' */ if (!isdigit(UCHAR(*p))) { /* INTL: digit */ goto error; } *ip++ = *p; for (prevChar = *p, p++; *p != 0; p++) { if (!isdigit(UCHAR(*p)) && /* INTL: digit */ ((*p!='.' && *p!='a' && *p!='b') || ((hasunstable && (*p=='a' || *p=='b')) || ((prevChar=='a' || prevChar=='b' || prevChar=='.') && (*p=='.')) || ((*p=='a' || *p=='b' || *p=='.') && prevChar=='.')))) { goto error; } if (*p == 'a' || *p == 'b') { hasunstable = 1; } /* * Translation to the internal rep. Regular version chars are copied * as is. The separators are translated to numerics. The new separator * for all parts is space. */ if (*p == '.') { *ip++ = ' '; *ip++ = '0'; *ip++ = ' '; } else if (*p == 'a') { *ip++ = ' '; *ip++ = '-'; *ip++ = '2'; *ip++ = ' '; } else if (*p == 'b') { *ip++ = ' '; *ip++ = '-'; *ip++ = '1'; *ip++ = ' '; } else { *ip++ = *p; } prevChar = *p; } if (prevChar!='.' && prevChar!='a' && prevChar!='b') { *ip = '\0'; if (internal != NULL) { *internal = ibuf; } else { ckfree(ibuf); } if (stable != NULL) { *stable = !hasunstable; } return TCL_OK; } error: ckfree(ibuf); Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected version number but got \"%s\"", string)); Tcl_SetErrorCode(interp, "TCL", "VALUE", "VERSION", NULL); return TCL_ERROR; } /* *---------------------------------------------------------------------- * * CompareVersions -- * * This function compares two version numbers (in internal rep). * * Results: * The return value is -1 if v1 is less than v2, 0 if the two version * numbers are the same, and 1 if v1 is greater than v2. If *satPtr is * non-NULL, the word it points to is filled in with 1 if v2 >= v1 and * both numbers have the same major number or 0 otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CompareVersions( char *v1, char *v2, /* Versions strings, of form 2.1.3 (any number * of version numbers). */ int *isMajorPtr) /* If non-null, the word pointed to is filled * in with a 0/1 value. 1 means that the * difference occured in the first element. */ { int thisIsMajor, res, flip; char *s1, *e1, *s2, *e2, o1, o2; /* * Each iteration of the following loop processes one number from each * string, terminated by a " " (space). If those numbers don't match then * the comparison is over; otherwise, we loop back for the next number. * * TIP 268. * This is identical the function 'ComparePkgVersion', but using the new * space separator as used by the internal rep of version numbers. The * special separators 'a' and 'b' have already been dealt with in * 'CheckVersionAndConvert', they were translated into numbers as well. * This keeps the comparison sane. Otherwise we would have to compare * numerics, the separators, and also deal with the special case of * end-of-string compared to separators. The semi-list rep we get here is * much easier to handle, as it is still regular. * * Rewritten to not compute a numeric value for the extracted version * number, but do string comparison. Skip any leading zeros for that to * work. This change breaks through the 32bit-limit on version numbers. */ thisIsMajor = 1; s1 = v1; s2 = v2; while (1) { /* * Parse one decimal number from the front of each string. Skip * leading zeros. Terminate found number for upcoming string-wise * comparison, if needed. */ while ((*s1 != 0) && (*s1 == '0')) { s1++; } while ((*s2 != 0) && (*s2 == '0')) { s2++; } /* * s1, s2 now point to the beginnings of the numbers to compare. Test * for their signs first, as shortcut to the result (different signs), * or determines if result has to be flipped (both negative). If there * is no shortcut we have to insert terminators later to limit the * strcmp. */ if ((*s1 == '-') && (*s2 != '-')) { /* s1 < 0, s2 >= 0 => s1 < s2 */ res = -1; break; } if ((*s1 != '-') && (*s2 == '-')) { /* s1 >= 0, s2 < 0 => s1 > s2 */ res = 1; break; } if ((*s1 == '-') && (*s2 == '-')) { /* a < b => -a > -b, etc. */ s1++; s2++; flip = 1; } else { flip = 0; } /* * The string comparison is needed, so now we determine where the * numbers end. */ e1 = s1; while ((*e1 != 0) && (*e1 != ' ')) { e1++; } e2 = s2; while ((*e2 != 0) && (*e2 != ' ')) { e2++; } /* * s1 .. e1 and s2 .. e2 now bracket the numbers to compare. Insert * terminators, compare, and restore actual contents. First however * another shortcut. Compare lengths. Shorter string is smaller * number! Thus we strcmp only strings of identical length. */ if ((e1-s1) < (e2-s2)) { res = -1; } else if ((e2-s2) < (e1-s1)) { res = 1; } else { o1 = *e1; *e1 = '\0'; o2 = *e2; *e2 = '\0'; res = strcmp(s1, s2); res = (res < 0) ? -1 : (res ? 1 : 0); *e1 = o1; *e2 = o2; } /* * Stop comparing segments when a difference has been found. Here we * may have to flip the result to account for signs. */ if (res != 0) { if (flip) { res = -res; } break; } /* * Go on to the next version number if the current numbers match. * However stop processing if the end of both numbers has been * reached. */ s1 = e1; s2 = e2; if (*s1 != 0) { s1++; } else if (*s2 == 0) { /* * s1, s2 both at the end => identical */ res = 0; break; } if (*s2 != 0) { s2++; } thisIsMajor = 0; } if (isMajorPtr != NULL) { *isMajorPtr = thisIsMajor; } return res; } /* *---------------------------------------------------------------------- * * CheckAllRequirements -- * * This function checks to see whether all requirements in a set have * valid syntax. * * Results: * TCL_OK is returned if all requirements are valid. Otherwise TCL_ERROR * is returned and an error message is left in the interp's result. * * Side effects: * May modify the interpreter result. * *---------------------------------------------------------------------- */ static int CheckAllRequirements( Tcl_Interp *interp, int reqc, /* Requirements to check. */ Tcl_Obj *const reqv[]) { int i; for (i = 0; i < reqc; i++) { if ((CheckRequirement(interp, TclGetString(reqv[i])) != TCL_OK)) { return TCL_ERROR; } } return TCL_OK; } /* *---------------------------------------------------------------------- * * CheckRequirement -- * * This function checks to see whether a requirement has valid syntax. * * Results: * If string is a properly formed requirement then TCL_OK is returned. * Otherwise TCL_ERROR is returned and an error message is left in the * interp's result. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CheckRequirement( Tcl_Interp *interp, /* Used for error reporting. */ const char *string) /* Supposedly a requirement. */ { /* * Syntax of requirement = version * = version-version * = version- */ char *dash = NULL, *buf; dash = strchr(string, '-'); if (dash == NULL) { /* * No dash found, has to be a simple version. */ return CheckVersionAndConvert(interp, string, NULL, NULL); } if (strchr(dash+1, '-') != NULL) { /* * More dashes found after the first. This is wrong. */ Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected versionMin-versionMax but got \"%s\"", string)); Tcl_SetErrorCode(interp, "TCL", "VALUE", "VERSIONRANGE", NULL); return TCL_ERROR; } /* * Exactly one dash is present. Copy the string, split at the location of * dash and check that both parts are versions. Note that the max part can * be empty. Also note that the string allocated with strdup() must be * freed with free() and not ckfree(). */ DupString(buf, string); dash = buf + (dash - string); *dash = '\0'; /* buf now <=> min part */ dash++; /* dash now <=> max part */ if ((CheckVersionAndConvert(interp, buf, NULL, NULL) != TCL_OK) || ((*dash != '\0') && (CheckVersionAndConvert(interp, dash, NULL, NULL) != TCL_OK))) { ckfree(buf); return TCL_ERROR; } ckfree(buf); return TCL_OK; } /* *---------------------------------------------------------------------- * * AddRequirementsToResult -- * * This function accumulates requirements in the interpreter result. * * Results: * None. * * Side effects: * The interpreter result is extended. * *---------------------------------------------------------------------- */ static void AddRequirementsToResult( Tcl_Interp *interp, int reqc, /* Requirements constraining the desired * version. */ Tcl_Obj *const reqv[]) /* 0 means to use the latest version * available. */ { Tcl_Obj *result = Tcl_GetObjResult(interp); int i, length; for (i = 0; i < reqc; i++) { const char *v = Tcl_GetStringFromObj(reqv[i], &length); if ((length & 0x1) && (v[length/2] == '-') && (strncmp(v, v+((length+1)/2), length/2) == 0)) { Tcl_AppendPrintfToObj(result, " exactly %s", v+((length+1)/2)); } else { Tcl_AppendPrintfToObj(result, " %s", v); } } } /* *---------------------------------------------------------------------- * * AddRequirementsToDString -- * * This function accumulates requirements in a DString. * * Results: * None. * * Side effects: * The DString argument is extended. * *---------------------------------------------------------------------- */ static void AddRequirementsToDString( Tcl_DString *dsPtr, int reqc, /* Requirements constraining the desired * version. */ Tcl_Obj *const reqv[]) /* 0 means to use the latest version * available. */ { int i; if (reqc > 0) { for (i = 0; i < reqc; i++) { TclDStringAppendLiteral(dsPtr, " "); TclDStringAppendObj(dsPtr, reqv[i]); } } else { TclDStringAppendLiteral(dsPtr, " 0-"); } } /* *---------------------------------------------------------------------- * * SomeRequirementSatisfied -- * * This function checks to see whether a version satisfies at least one * of a set of requirements. * * Results: * If the requirements are satisfied 1 is returned. Otherwise 0 is * returned. The function assumes that all pieces have valid syntax. And * is allowed to make that assumption. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int SomeRequirementSatisfied( char *availVersionI, /* Candidate version to check against the * requirements. */ int reqc, /* Requirements constraining the desired * version. */ Tcl_Obj *const reqv[]) /* 0 means to use the latest version * available. */ { int i; for (i = 0; i < reqc; i++) { if (RequirementSatisfied(availVersionI, TclGetString(reqv[i]))) { return 1; } } return 0; } /* *---------------------------------------------------------------------- * * RequirementSatisfied -- * * This function checks to see whether a version satisfies a requirement. * * Results: * If the requirement is satisfied 1 is returned. Otherwise 0 is * returned. The function assumes that all pieces have valid syntax, and * is allowed to make that assumption. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int RequirementSatisfied( char *havei, /* Version string, of candidate package we * have. */ const char *req) /* Requirement string the candidate has to * satisfy. */ { /* * The have candidate is already in internal rep. */ int satisfied, res; char *dash = NULL, *buf, *min, *max; dash = strchr(req, '-'); if (dash == NULL) { /* * No dash found, is a simple version, fallback to regular check. The * 'CheckVersionAndConvert' cannot fail. We pad the requirement with * 'a0', i.e '-2' before doing the comparison to properly accept * unstables as well. */ char *reqi = NULL; int thisIsMajor; CheckVersionAndConvert(NULL, req, &reqi, NULL); strcat(reqi, " -2"); res = CompareVersions(havei, reqi, &thisIsMajor); satisfied = (res == 0) || ((res == 1) && !thisIsMajor); ckfree(reqi); return satisfied; } /* * Exactly one dash is present (Assumption of valid syntax). Copy the req, * split at the location of dash and check that both parts are versions. * Note that the max part can be empty. */ DupString(buf, req); dash = buf + (dash - req); *dash = '\0'; /* buf now <=> min part */ dash++; /* dash now <=> max part */ if (*dash == '\0') { /* * We have a min, but no max. For the comparison we generate the * internal rep, padded with 'a0' i.e. '-2'. */ CheckVersionAndConvert(NULL, buf, &min, NULL); strcat(min, " -2"); satisfied = (CompareVersions(havei, min, NULL) >= 0); ckfree(min); ckfree(buf); return satisfied; } /* * We have both min and max, and generate their internal reps. When * identical we compare as is, otherwise we pad with 'a0' to ove the range * a bit. */ CheckVersionAndConvert(NULL, buf, &min, NULL); CheckVersionAndConvert(NULL, dash, &max, NULL); if (CompareVersions(min, max, NULL) == 0) { satisfied = (CompareVersions(min, havei, NULL) == 0); } else { strcat(min, " -2"); strcat(max, " -2"); satisfied = ((CompareVersions(min, havei, NULL) <= 0) && (CompareVersions(havei, max, NULL) < 0)); } ckfree(min); ckfree(max); ckfree(buf); return satisfied; } /* *---------------------------------------------------------------------- * * Tcl_PkgInitStubsCheck -- * * This is a replacement routine for Tcl_InitStubs() that is called * from code where -DUSE_TCL_STUBS has not been enabled. * * Results: * Returns the version of a conforming stubs table, or NULL, if * the table version doesn't satisfy the requested requirements, * according to historical practice. * * Side effects: * None. * *---------------------------------------------------------------------- */ const char * Tcl_PkgInitStubsCheck( Tcl_Interp *interp, const char * version, int exact) { const char *actualVersion = Tcl_PkgPresent(interp, "Tcl", version, 0); if (exact && actualVersion) { const char *p = version; int count = 0; while (*p) { count += !isdigit(UCHAR(*p++)); } if (count == 1) { if (0 != strncmp(version, actualVersion, strlen(version))) { /* Construct error message */ Tcl_PkgPresent(interp, "Tcl", version, 1); return NULL; } } else { return Tcl_PkgPresent(interp, "Tcl", version, 1); } } return actualVersion; } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */
{ "content_hash": "1446a77e1e79127b869eb81aabcab988", "timestamp": "", "source": "github", "line_count": 1923, "max_line_length": 78, "avg_line_length": 27.55486219448778, "alnum_prop": 0.605438967313354, "repo_name": "bitkeeper-scm/bitkeeper", "id": "f6e8b203fdf4519c8aea1217793cd4489510b2bd", "size": "53494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gui/tcltk/tcl/generic/tclPkg.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138638" }, { "name": "Awk", "bytes": "537" }, { "name": "Batchfile", "bytes": "17857" }, { "name": "BlitzBasic", "bytes": "194161" }, { "name": "C", "bytes": "28873391" }, { "name": "C#", "bytes": "54012" }, { "name": "C++", "bytes": "863164" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "28687" }, { "name": "CSS", "bytes": "2606" }, { "name": "Common Lisp", "bytes": "1386" }, { "name": "DIGITAL Command Language", "bytes": "31087" }, { "name": "DTrace", "bytes": "7347" }, { "name": "Emacs Lisp", "bytes": "205568" }, { "name": "HTML", "bytes": "1374203" }, { "name": "JavaScript", "bytes": "6682" }, { "name": "Jolie", "bytes": "3956" }, { "name": "Lex", "bytes": "189720" }, { "name": "Logos", "bytes": "168703" }, { "name": "M4", "bytes": "744535" }, { "name": "Makefile", "bytes": "506590" }, { "name": "Module Management System", "bytes": "3093" }, { "name": "Objective-C", "bytes": "220655" }, { "name": "Pascal", "bytes": "94171" }, { "name": "Perl", "bytes": "125543" }, { "name": "Perl 6", "bytes": "1129" }, { "name": "PostScript", "bytes": "130437" }, { "name": "Python", "bytes": "48455" }, { "name": "R", "bytes": "1390" }, { "name": "Roff", "bytes": "4316683" }, { "name": "Ruby", "bytes": "4837" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "742546" }, { "name": "Tcl", "bytes": "4829953" }, { "name": "TeX", "bytes": "677682" }, { "name": "Vim script", "bytes": "385" }, { "name": "Yacc", "bytes": "64491" }, { "name": "sed", "bytes": "2377" } ], "symlink_target": "" }
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application( realpath(dirname(__DIR__)) ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $app->singleton( Illuminate\Contracts\Http\Kernel::class, CroudTech\RepositoryTest\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, CroudTech\Repositories\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, CroudTech\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
{ "content_hash": "ae6985f7f9347e0af000e4821fece4a2", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 75, "avg_line_length": 30, "alnum_prop": 0.5387878787878788, "repo_name": "CroudSupport/laravel-repositories", "id": "d4333b929dcef07e6628c14b82fbeb44bedd480a", "size": "1650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/testapp/bootstrap/app.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "73055" } ], "symlink_target": "" }
package com.netflix.servo.monitor; import com.google.common.base.Objects; import com.google.common.util.concurrent.AtomicDouble; /** * A {@link Gauge} that reports a double value. */ public class DoubleGauge implements Gauge<Double> { private final AtomicDouble number = new AtomicDouble(0.0); private final MonitorConfig config; /** * Create a new instance with the specified configuration * * @param config configuration for this gauge */ public DoubleGauge(MonitorConfig config) { this.config = config; } /** * Set the current value. */ public void set(Double n) { number.set(n); } /** {@inheritDoc} */ @Override public Double getValue() { return number.get(); } /** {@inheritDoc} */ @Override public MonitorConfig getConfig() { return config; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DoubleGauge)) { return false; } final DoubleGauge that = (DoubleGauge) o; // AtomicDouble does not implement a proper .equals so we need to compare the // underlying double return config.equals(that.config) && number.get() == that.number.get(); } /** {@inheritDoc} */ @Override public int hashCode() { // AtomicDouble does not implement a proper .hashCode() so we need to use the // underlying double return Objects.hashCode(number.get(), config); } /** {@inheritDoc} */ @Override public String toString() { return Objects.toStringHelper(this).add("number", number).add("config", config).toString(); } }
{ "content_hash": "4b8240c7c979cc632b0d50417bcf06f0", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 99, "avg_line_length": 25.779411764705884, "alnum_prop": 0.6069594980034227, "repo_name": "dmuino/servo", "id": "e2db1d734f6328bbc491769cdcdb4cac85daaeae", "size": "2350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "servo-core/src/main/java/com/netflix/servo/monitor/DoubleGauge.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "13533" }, { "name": "Java", "bytes": "496633" }, { "name": "Shell", "bytes": "7468" } ], "symlink_target": "" }
import Quill from '../quill'; import clone from 'clone'; import equal from 'deep-equal'; import platform from '../lib/platform'; let Delta = Quill.require('delta'); class Keyboard { // TODO allow passing in hotkeys in options constructor(quill, options = {}) { this.quill = quill; this.hotkeys = {}; this.quill.root.addEventListener('keydown', (evt) => { let which = evt.which || evt.keyCode; let range = this.quill.getSelection(); let prevent = (this.hotkeys[which] || []).reduce(function(prevent, hotkey) { let [key, callback] = hotkey; if (!match(evt, key)) return prevent; return callback(range, key, evt) || prevent; }, false); if (prevent) { return evt.preventDefault(); } }); } addHotkey(hotkeys, callback) { if (!Array.isArray(hotkeys)) { hotkeys = [hotkeys]; } hotkeys.forEach((hotkey) => { hotkey = coerce(hotkey); if (hotkey == null) { return this.quill.emit(Quill.events.DEBUG, 'Attempted to add invalid hotkey', hotkey); } this.hotkeys[hotkey.key] = this.hotkeys[hotkey.key] || []; this.hotkeys[hotkey.key].push([hotkey, callback]); }); } removeHotkey(hotkeys, callback) { if (!Array.isArray(hotkeys)) { hotkeys = [hotkeys]; } return hotkeys.reduce((removed, query) => { query = coerce(query); if ((query != null) && (this.hotkeys[query.key] != null)) { this.hotkeys[query.key] = this.hotkeys[query.key].filter(function(target) { if (equal(target[0], query) && ((callback == null) || callback === target[1])) { removed.push(target[1]); return false; } return true; }); } return removed; }); } } function corce(hotkey) { switch (typeof hotkey) { case 'string': if (Keyboard.hotkeys[hotkey.toUpperCase()] != null) { hotkey = clone(Keyboard.hotkeys[hotkey.toUpperCase()], false); } else if (hotkey.length === 1) { hotkey = { key: hotkey }; } else { return null; } break; case 'number': hotkey = { key: hotkey }; break; case 'object': hotkey = clone(hotkey, false); break; default: return null; } if (typeof hotkey.key === 'string') { hotkey.key = hotkey.key.toUpperCase().charCodeAt(0); } return hotkey; } function match(evt, hotkey) { let metaKey = platform.isMac() ? evt.metaKey : evt.metaKey || evt.ctrlKey; if (hotkey.metaKey !== metaKey && hotkey.metaKey !== null) return false; if (hotkey.shiftKey !== evt.shiftKey && hotkey.shiftKey !== null) return false; if (hotkey.altKey !== evt.altKey && hotkey.altKey !== null) return false; return true; } Quill.registerModule('keyboard', Keyboard); export { Keyboard as default };
{ "content_hash": "9d30e3850bd321a0fd194b5cab462498", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 94, "avg_line_length": 28.757575757575758, "alnum_prop": 0.5876361081840534, "repo_name": "jcppman/quill", "id": "0a24a695a3300cb16dc266834fcdf6410cb6a05b", "size": "2847", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/modules/keyboard.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9590" }, { "name": "JavaScript", "bytes": "144214" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" /> <link rel="prev" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.13.4</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.13.4</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root" class="md-nav__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">KalmanSmoother.smooth_conventional</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional"> <h1 id="generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py attribute"> <dt class="sig sig-object py" id="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional"> <span class="sig-prename descclassname"><span class="pre">KalmanSmoother.</span></span><span class="sig-name descname"><span class="pre">smooth_conventional</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">False</span></em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" title="Permalink to this definition">¶</a></dt> <dd><p>(bool) Flag for conventional (Durbin and Koopman, 2012) Kalman smoothing.</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical </span> </div> </a> <a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 01, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "9b27e375588c5d451523f554c169f68c", "timestamp": "", "source": "github", "line_count": 457, "max_line_length": 999, "avg_line_length": 41.90809628008753, "alnum_prop": 0.6147660818713451, "repo_name": "statsmodels/statsmodels.github.io", "id": "635f96d2f6c3d5e8f4a882ccd47523c7f2859364", "size": "19156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.13.4/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.multiverse.stms.gamma.transactions.fat; import org.multiverse.stms.gamma.transactions.GammaTxnConfig; import static org.junit.Assert.assertNull; public class FatMonoGammaTxn_commitTest extends FatGammaTxn_commitTest<FatMonoGammaTxn> { @Override protected void assertCleaned(FatMonoGammaTxn transaction) { assertNull(transaction.tranlocal.owner); } @Override protected FatMonoGammaTxn newTransaction(GammaTxnConfig config) { return new FatMonoGammaTxn(config); } protected FatMonoGammaTxn newTransaction() { return new FatMonoGammaTxn(new GammaTxnConfig(stm)); } }
{ "content_hash": "4a7b24caa95663816d78953e75b4e2b9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 89, "avg_line_length": 29, "alnum_prop": 0.7617554858934169, "repo_name": "Felorati/Thesis", "id": "43b0466e571a63f986aae3c56eba529e96e20755", "size": "638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/Tests/Multiverse/multiverse-core/src/test/java/org/multiverse/stms/gamma/transactions/fat/FatMonoGammaTxn_commitTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "404065" }, { "name": "CSS", "bytes": "9057" }, { "name": "Groovy", "bytes": "41944" }, { "name": "HTML", "bytes": "30679" }, { "name": "Java", "bytes": "2667624" }, { "name": "PostScript", "bytes": "535704" }, { "name": "Shell", "bytes": "975" }, { "name": "TeX", "bytes": "474097" } ], "symlink_target": "" }
import requests import logging from wia import Wia ''' wia_post: args: path: string specifying url path kwargs: variable-length dict which can contain data for post request ''' def post(path, kwargs): url = generate_url(path) headers = generate_headers(path) if 'file' in kwargs: logging.debug("Has file argument.") kwargsCopy = dict(kwargs) del kwargsCopy['file'] if type(kwargs['file']) is str : with open(kwargs['file'], 'rb') as f: r = requests.post(url, data=kwargsCopy, headers=headers, files={'file': f}) else: r = requests.post(url, data=kwargsCopy, headers=headers, files={'file': kwargs['file']}) kwargs['file'].close() else: logging.debug("No file argument. Posting as JSON.") r = requests.post(url, json=kwargs, headers=headers) return r ''' wia_put: args: path: string specifying url path kwargs: variable-length dict which can contain data for put request ''' def put(path, kwargs): url = generate_url(path) headers = generate_headers(path) data = kwargs r = requests.put(url, json=data, headers=headers) return r ''' wia_get: args: path: string specifying url path kwargs: variable-length dict which can contain query params ''' def get(path, **kwargs): url = generate_url(path) headers = generate_headers(path) r = requests.get(url, headers=headers, params=kwargs) return r ''' wia_delete: args: path: string specifying url path ''' def delete(path): url = generate_url(path) headers = generate_headers(path) r = requests.delete(url, headers=headers) return r def generate_url(path): if path is None: path = '' url = Wia().rest_config['protocol'] + '://' + Wia().rest_config['host'] + '/' + Wia().rest_config['basePath'] + '/' + path logging.debug('URL: %s', url) return url def generate_headers(path): headers = {} if Wia().app_key is not None: headers['x-app-key'] = Wia().app_key if Wia().access_token is not None: headers['Authorization'] = 'Bearer ' + Wia().access_token return headers
{ "content_hash": "af6c18da833e4af77a223a7fd53cc6c6", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 126, "avg_line_length": 24.340425531914892, "alnum_prop": 0.5957167832167832, "repo_name": "wiaio/wia-python-sdk", "id": "1a7854e69117abc7ca36d26f39cad34adb8edf60", "size": "2288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wia/rest_client.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6757" }, { "name": "HTML", "bytes": "11086816" }, { "name": "JavaScript", "bytes": "23025" }, { "name": "Python", "bytes": "40583" } ], "symlink_target": "" }
#region License #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; namespace Sanford.StateMachineToolkit { public abstract partial class StateMachine<TState, TEvent, TArgs> { /// <summary> /// The TransitionCollection represents a collection of Transitions. /// Each <see cref="State"/> object has its own /// TransitionCollection for holding its Transitions.<para/> /// When a Transition is added to a State's <see cref="State.Transitions"/>, /// it is registered with an event ID. This event ID is a value identifying an event a /// <see cref="State"/> can receive. When a <see cref="State"/> /// receives an event, it uses the event's ID to check to see if it has any Transitions for that /// event (as described above). /// </summary> private class TransitionCollection { #region TransitionCollection Members #region Fields // The owner of the collection. private readonly State m_owner; // The table of transitions. private readonly Dictionary<TEvent, List<Transition>> m_transitions; #endregion #region Construction /// <summary> /// Initializes a new instance of the TransitionCollection class with /// the specified number of events. /// </summary> /// <param name="owner"> /// The state that owns the TransitionCollection. /// </param> public TransitionCollection(State owner, IEqualityComparer<TEvent> comparer = null) { m_transitions = new Dictionary<TEvent, List<Transition>>(comparer); m_owner = owner; } #endregion #region Methods /// <summary> /// Adds a Transition to the collection for the specified event ID. /// </summary> /// <param name="eventId"> /// The event ID associated with the Transition. /// </param> /// <param name="trans"> /// The Transition to add. /// </param> /// <remarks> /// When a Transition is added to the collection, it is associated with /// the specified event ID. When a State receives an event, it looks up /// the event ID in its TransitionCollection to see if there are any /// Transitions for the specified event. /// </remarks> public void Add(TEvent eventId, Transition trans) { #region Preconditions if (trans.Source != null) { throw new InvalidOperationException( "This Transition has already been added to another State."); } #endregion // Set the transition's source. trans.Source = m_owner; // If there are no Transitions for the specified event ID. if (!m_transitions.ContainsKey(eventId)) { // Create new list of Transitions for the specified event ID. m_transitions[eventId] = new List<Transition>(); } // Add Transition. m_transitions[eventId].Add(trans); } /// <summary> /// Adds a Transition to the collection for the specified event ID. /// </summary> /// <param name="eventId"> /// The event ID associated with the Transition. /// </param> /// <param name="targetState"> /// The target state of the transtion. /// </param> /// <param name="actions"> /// Optional array of actions, to be performed during the transition. /// </param> /// <remarks> /// When a Transition is added to the collection, it is associated with /// the specified event ID. When a State receives an event, it looks up /// the event ID in its TransitionCollection to see if there are any /// Transitions for the specified event. /// </remarks> public void Add(TEvent eventId, State targetState, params EventHandler<TransitionEventArgs<TState, TEvent, TArgs>>[] actions) { Add(eventId, null, targetState, actions); } /// <summary> /// Adds a Transition to the collection for the specified event ID. /// </summary> /// <param name="eventId"> /// The event ID associated with the Transition. /// </param> /// <param name="guard"> /// The guard to test to determine whether the transition should take /// place. /// </param> /// <param name="targetState"> /// The target state of the transtion. /// </param> /// <param name="actions"> /// Optional array of actions, to be performed during the transition. /// </param> /// <remarks> /// When a Transition is added to the collection, it is associated with /// the specified event ID. When a State receives an event, it looks up /// the event ID in its TransitionCollection to see if there are any /// Transitions for the specified event. /// </remarks> public void Add(TEvent eventId, GuardHandler<TState, TEvent, TArgs> guard, State targetState, params EventHandler<TransitionEventArgs<TState, TEvent, TArgs>>[] actions) { Transition trans = new Transition(guard, targetState); foreach (EventHandler<TransitionEventArgs<TState, TEvent, TArgs>> action in actions) { if (action == null) continue; trans.Actions += action; } Add(eventId, trans); } /// <summary> /// Removes the specified Transition at the specified event ID. /// </summary> /// <param name="eventId"> /// The event ID associated with the Transition. /// </param> /// <param name="trans"> /// The Transition to remove. /// </param> public void Remove(TEvent eventId, Transition trans) { if (!m_transitions.ContainsKey(eventId)) return; // If there are Transitions at the specified event id. m_transitions[eventId].Remove(trans); // If there are no more Transitions at the specified event id. if (m_transitions[eventId].Count == 0) { // Indicate that there are no Transitions at this event id. m_transitions.Remove(eventId); } } #endregion #region Properties /// <summary> /// Gets a collection of Transitions at the specified event ID. /// </summary> /// <remarks> /// If there are no Transitions at the specified event ID, the value /// of the collection will be null. /// </remarks> public IEnumerable<Transition> this[TEvent eventId] { get { return m_transitions.ContainsKey(eventId) ? m_transitions[eventId] : null; } } #endregion #endregion } } }
{ "content_hash": "3961f09c9dbfd722d5fa5961c857e454", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 180, "avg_line_length": 38.41626794258373, "alnum_prop": 0.5145099016066758, "repo_name": "OmerMor/StateMachineToolkit", "id": "7a9a777cc1a1b9384d8a6f81f7004f0a508079f0", "size": "9179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/StateMachineToolkit/TransitionCollection.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "300058" }, { "name": "Ruby", "bytes": "1477" }, { "name": "Shell", "bytes": "243" } ], "symlink_target": "" }
<?php $lang = array(); $lang['user_blocked'] = "Vous &ecirc;tes actuellement bloqu&eacute;s du syst&egrave;me."; $lang['user_verify_failed'] = "Code captcha invalide."; $lang['email_password_invalid'] = "Adresse email / mot de passe invalide."; $lang['email_password_incorrect'] = "Adresse email / mot de passe incorrect."; $lang['remember_me_invalid'] = "Le champ se souvenir de moi est invalide."; $lang['password_short'] = "Le mot de passe est trop court."; $lang['password_long'] = "Le mot de passe est trop long."; $lang['password_invalid'] = "Le mot de passe doit contenir au moins un caractère en miniscule et en majuscule, et au moins un chiffre."; $lang['password_nomatch'] = "Les mots de passe ne sont pas identiques."; $lang['password_changed'] = "Le mot de passe a bien &eacute;t&eacute; chang&eacute;."; $lang['password_incorrect'] = "Le mot de passe actuel est incorrect."; $lang['password_notvalid'] = "Le mot de passe est invalide."; $lang['newpassword_short'] = "Le nouveau mot de passe est trop court."; $lang['newpassword_long'] = "Le nouveau mot de passe est trop long."; $lang['newpassword_invalid'] = "Le nouveau mot de passe doit contenir au moins un caractère en miniscule et en majuscule, et au moins un chiffre."; $lang['newpassword_nomatch'] = "Les nouveaux mots de passe ne sont pas identiques."; $lang['newpassword_match'] = "Le nouveau mot de passe est le m&ecirc;me que l'ancien."; $lang['email_short'] = "L'adresse email est trop courte."; $lang['email_long'] = "L'adresse email est trop longue."; $lang['email_invalid'] = "L'adresse email est invalide."; $lang['email_incorrect'] = "L'adresse email est incorrecte."; $lang['email_banned'] = "Cette adresse email est interdite."; $lang['email_changed'] = "L'adresse email a bien &eacute;t&eacute; chang&eacute;e."; $lang['newemail_match'] = "La nouvelle adresse email est identique à l'adresse email actuelle."; $lang['account_inactive'] = "Le compte n'a pas encore &eacute;t&eacute; activ&eacute;."; $lang['account_activated'] = "Le compte est desormais activ&eacute;."; $lang['logged_in'] = "Vous &ecirc;tes maintenant connect&eacute;s."; $lang['logged_out'] = "Vous avez &eacute;t&eacute; deconnect&eacute;s."; $lang['system_error'] = "Une erreur syst&egrave;me a &eacute;t&eacute; rencontr&eacute;e. Veuillez r&eacute;essayer."; $lang['register_success'] = "Le compte a bien &eacute;t&eacute; cr&eacute;e. L'email d'activation vous a &eacute;t&eacute; envoy&eacute;."; $lang['register_success_emailmessage_suppressed'] = "Le compte a bien &eacute;t&eacute; cr&eacute;e."; $lang['email_taken'] = "L'adresse email est d&eacute;j&agrave; utilis&eacute;e."; $lang['resetkey_invalid'] = "La cl&eacute; de r&eacute;initialisation est invalide."; $lang['resetkey_incorrect'] = "La cl&eacute; de r&eacute;initialisation est incorrecte."; $lang['resetkey_expired'] = "La cl&eacute; de r&eacute;initialisation est expir&eacute;e."; $lang['password_reset'] = "Le mot de passe a bien &eacute;t&eacute; r&eacute;initialis&eacute;."; $lang['activationkey_invalid'] = "La cl&eacute; d'activation est invalide."; $lang['activationkey_incorrect'] = "La cl&eacute; d'activation est incorrecte."; $lang['activationkey_expired'] = "La cl&eacute; d'activation est expir&eacute;e."; $lang['reset_requested'] = "Une demande de r&eacute;initialisation de votre mot de passe a &eacute;t&eacute; envoy&eacute;."; $lang['reset_requested_emailmessage_suppressed'] = "Une demande de r&eacute;initialisation de votre mot de passe a &eacutet&eacute cr&eacute&eacute."; $lang['reset_exists'] = "Une demande de r&eacute;initialisation de votre mot de passe existe d&eacute;j&agrave;."; $lang['already_activated'] = "Le compte est d&eacute;j&agrave; activ&eacute;."; $lang['activation_sent'] = "L'email d'activation a bien &eacute;t&eacute; envoy&eacute;."; $lang['activation_exists'] = "L'email d'activation a d&eacute;j&agrave; &eacute;t&eacute; envoy&eacute;."; $lang['email_activation_subject'] = '%s - Activation de compte'; $lang['email_activation_body'] = 'Bonjour,<br/><br/> Pour pouvoir vous connecter vous devez d\'abord activer votre compte en cliquant sur le lien suivant :<strong><a href="%1$s/%2$s">%1$s/%2$s</a></strong><br/><br/>Vous devrez utiliser cette clé d\'activation : <strong>%3$s</strong><br/><br/>\n Si vous ne souhaitez pas vous enregistrer sur %1$s vous pouvez ignorer ce message.'; $lang['email_activation_altbody'] = 'Bonjour,' . "\n\n" . 'Pour pouvoir vous connecter vous devez d\'abord activer votre compte en cliquant sur le lien suivant :' . "\n" . '%1$s/%2$s' . "\n\n" . 'Vous devrez utiliser cette clé d\'activation : %3$s' . "\n\n" . 'Si vous ne souhaitez pas vous enregistrer sur %1$s vous pouvez ignorer ce message.'; $lang['email_reset_subject'] = '%s - Reinitialisation du mot de passe'; $lang['email_reset_body'] = 'Bonjour,<br/><br/>Pour reinitialiser votre mot de passe cliquez sur le lien suivant :<br/><br/><strong><a href="%1$s/%2$s">%1$s/%2$s</a></strong><br/><br/>Vous devrez utiliser cette clé pour reinitialiser votre mot de passe: <strong>%3$s</strong><br/><br/>Si vous n\'avez pas demandé une réinitialisation du mot de passe, vous pouvez ignorer ce message.'; $lang['email_reset_altbody'] = 'Bonjour,' . "\n\n" . 'Pour reinitialiser votre mot de passe cliquez sur le lien suivant :' . "\n" . '%1$s/%2$s' . "\n\n" . 'Vous devrez utiliser cette clé pour reinitialiser votre mot de passe depuis cette adresse : %1$s' . "\n\n" . 'Si vous n\'avez pas demandé une réinitialisation du mot de passe, vous pouvez ignorer ce message.'; $lang['account_deleted'] = "Compte supprimé."; ?>
{ "content_hash": "5c71dea5e6717316da5d44ae90802d77", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 384, "avg_line_length": 75.70270270270271, "alnum_prop": 0.7072474116387004, "repo_name": "ChristinMilloy/PHPAuth", "id": "a4f99c7a3b1edd90c5fa00b5f7bdc8f8b76ad422", "size": "5614", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "languages/fr_FR.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "285264" } ], "symlink_target": "" }
 CKEDITOR.plugins.setLang( 'flash', 'no', { access: 'Scripttilgang', accessAlways: 'Alltid', accessNever: 'Aldri', accessSameDomain: 'Samme domene', alignAbsBottom: 'Abs bunn', alignAbsMiddle: 'Abs midten', alignBaseline: 'Bunnlinje', alignTextTop: 'Tekst topp', bgcolor: 'Bakgrunnsfarge', chkFull: 'Tillat fullskjerm', chkLoop: 'Loop', chkMenu: 'Slå på Flash-meny', chkPlay: 'Autospill', flashvars: 'Variabler for flash', hSpace: 'HMarg', properties: 'Egenskaper for Flash-objekt', propertiesTab: 'Egenskaper', quality: 'Kvalitet', qualityAutoHigh: 'Auto høy', qualityAutoLow: 'Auto lav', qualityBest: 'Best', qualityHigh: 'Høy', qualityLow: 'Lav', qualityMedium: 'Medium', scale: 'Skaler', scaleAll: 'Vis alt', scaleFit: 'Skaler til å passe', scaleNoBorder: 'Ingen ramme', title: 'Flash-egenskaper', vSpace: 'VMarg', validateHSpace: 'HMarg må være et tall.', validateSrc: 'Vennligst skriv inn lenkens url.', validateVSpace: 'VMarg må være et tall.', windowMode: 'Vindumodus', windowModeOpaque: 'Opaque', windowModeTransparent: 'Gjennomsiktig', windowModeWindow: 'Vindu' } );
{ "content_hash": "192828bf8b3709dd45d630a984ef6761", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 49, "avg_line_length": 27.875, "alnum_prop": 0.7174887892376681, "repo_name": "Rudhie/simlab", "id": "810c33431ae5df06874df0d14376b235bda2ead1", "size": "1268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/ckeditor/plugins/flash/lang/no.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "364" }, { "name": "CSS", "bytes": "186843" }, { "name": "HTML", "bytes": "427207" }, { "name": "JavaScript", "bytes": "5743945" }, { "name": "PHP", "bytes": "1987763" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../spec_helper' describe ThemeController do define_models :theme_controller before(:each) do activate_site(:default) stub_site_themes end describe "site, login, and admin requirements" do define_models :theme_controller it "should require a site" do test_site_requirement(true, [ lambda { get :stylesheets, :filename => 'f', :ext => 'css' }, lambda { get :images, :filename => 'f', :ext => 'png' }, lambda { get :javascripts, :filename => 'f', :ext => 'js' }]) end it "should not require login" do test_login_requirement(false, false, [ lambda { get :stylesheets, :filename => 'f', :ext => 'css' }, lambda { get :images, :filename => 'f', :ext => 'png' }, lambda { get :javascripts, :filename => 'f', :ext => 'js' }]) end end describe "rendering files" do define_models :theme_controller it "should render not found if the path contains .. (for safety)" do get :stylesheets, :filename => 'a/b/../c', :ext => 'css' response.should be_missing end it "should return not found if the file doesn't exist" do p = mock_model(Pathname, :+ => '') p.stub!(:file?).and_return(false) Pathname.stub!(:new).and_return(p) get :images, :filename => 'f', :ext => 'png' response.should be_missing end describe "with a file that exists" do define_models :theme_controller before(:each) do p = mock_model(Pathname, :+ => '') p.stub!(:file?).and_return(true) p.stub!(:read).and_return('abc') p.stub!(:basename).and_return('fake_name') Pathname.stub!(:new).and_return(p) end it "should render correctly when the css resource exists" do get :stylesheets, :filename => 'f', :ext => 'css' response.body.should == 'abc' end it "should set the correct type for css" do get :stylesheets, :filename => 'f', :ext => 'css' response.headers['type'].should == 'text/css; charset=utf-8' end it "should render correctly when the javascript resource exists" do get :javascripts, :filename => 'f', :ext => 'js' response.body.should == 'abc' end it "should set the correct type for javascript" do get :javascripts, :filename => 'f', :ext => 'js' response.headers['type'].should == 'text/javascript; charset=utf-8' end it "should cache the result for javascripts" do lambda { get :javascripts, :filename => 'f', :ext => 'js' }.should change(CacheItem, :count).by(1) end it "should cache the result for stylesheets" do lambda { get :stylesheets, :filename => 'f', :ext => 'css' }.should change(CacheItem, :count).by(1) end it "should cache the result for images" do lambda { get :images, :filename => 'f', :ext => 'png' }.should change(CacheItem, :count).by(1) end describe "when rendering images" do define_models :theme_controller it "should set the correct headers" do get :images, :filename => 'f', :ext => 'png' { 'Content-Transfer-Encoding' => 'binary', 'Content-Disposition' => 'inline; filename="fake_name"', 'Cache-Control' => 'private' }.each do |key, value| response.headers[key].should == value end end it "should render correctly when the png resource exists" do get :images, :filename => 'f', :ext => 'png' response.body.should == 'abc' end it "should set the correct type for png" do get :images, :filename => 'f', :ext => 'png' response.headers['type'].should == 'image/png' end it "should render correctly when the jpg resource exists" do get :images, :filename => 'f', :ext => 'jpg' response.body.should == 'abc' end it "should set the correct type for jpg" do get :images, :filename => 'f', :ext => 'jpg' response.headers['type'].should == 'image/jpeg' end it "should render correctly when the gif resource exists" do get :images, :filename => 'f', :ext => 'gif' response.body.should == 'abc' end it "should set the correct type for gif" do get :images, :filename => 'f', :ext => 'gif' response.headers['type'].should == 'image/gif' end it "should be successful even if the type is random" do get :images, :filename => 'f', :ext => 'random' response.body.should == 'abc' end it "should set the correct headers when the type is random" do get :images, :filename => 'f', :ext => 'random' response.headers['type'].should == 'application/binary' end end end end end
{ "content_hash": "bc361ddbd049f584de62e6189c76a0c8", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 109, "avg_line_length": 35.794326241134755, "alnum_prop": 0.554388745789578, "repo_name": "aub/spritz", "id": "f71a3a4dbdb7a9c23ec7b3eb09298841a530d649", "size": "5047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/controllers/theme_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1253" }, { "name": "CSS", "bytes": "27834" }, { "name": "HTML", "bytes": "33067" }, { "name": "JavaScript", "bytes": "41730" }, { "name": "Liquid", "bytes": "9462" }, { "name": "Ruby", "bytes": "480983" } ], "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_151) on Wed Dec 13 10:32:40 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.config.transactions.log_store.transactions (BOM: * : All 2017.12.1 API)</title> <meta name="date" content="2017-12-13"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../../org/wildfly/swarm/config/transactions/log_store/transactions/package-summary.html" target="classFrame">org.wildfly.swarm.config.transactions.log_store.transactions</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="ParticipantsConsumer.html" title="interface in org.wildfly.swarm.config.transactions.log_store.transactions" target="classFrame"><span class="interfaceName">ParticipantsConsumer</span></a></li> <li><a href="ParticipantsSupplier.html" title="interface in org.wildfly.swarm.config.transactions.log_store.transactions" target="classFrame"><span class="interfaceName">ParticipantsSupplier</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="Participants.html" title="class in org.wildfly.swarm.config.transactions.log_store.transactions" target="classFrame">Participants</a></li> </ul> <h2 title="Enums">Enums</h2> <ul title="Enums"> <li><a href="Participants.Status.html" title="enum in org.wildfly.swarm.config.transactions.log_store.transactions" target="classFrame">Participants.Status</a></li> </ul> </div> </body> </html>
{ "content_hash": "99090e5db6fb34813e2a7a2cb3221518", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 218, "avg_line_length": 60.233333333333334, "alnum_prop": 0.7133370226895407, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "8d9f03f5834aa8cdd0140cbdd6e0517413816194", "size": "1807", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2017.12.1/apidocs/org/wildfly/swarm/config/transactions/log_store/transactions/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package integrationTests.textFile; import java.io.*; import java.util.*; import org.junit.*; import mockit.*; import integrationTests.textFile.TextFile.*; import static org.junit.Assert.*; public final class TextFileUsingVerificationsTest { @Test public void createTextFile(@Mocked DefaultTextReader reader) throws Exception { assertNotNull(reader); new TextFile("file", 0); new Verifications() {{ new DefaultTextReader("file"); }}; } @Test public void createTextFileByCapturingTheTextReaderClassThroughItsBaseType(@Capturing TextReader reader) throws Exception { new TextFile("file", 0); } @Test public void parseTextFileUsingConcreteClass(@Mocked final DefaultTextReader reader) throws Exception { new Expectations() {{ reader.readLine(); returns("line1", "another,line", null); }}; TextFile textFile = new TextFile("file", 200); List<String[]> result = textFile.parse(); assertResultFromTextFileParsing(result); new Verifications() {{ reader.close(); }}; } void assertResultFromTextFileParsing(List<String[]> result) { assertEquals(2, result.size()); String[] line1 = result.get(0); assertEquals(1, line1.length); assertEquals("line1", line1[0]); String[] line2 = result.get(1); assertEquals(2, line2.length); assertEquals("another", line2[0]); assertEquals("line", line2[1]); } @Test public void parseTextFileUsingInterface(@Mocked final TextReader reader) throws Exception { new Expectations() {{ reader.readLine(); returns("line1", "another,line", null); }}; TextFile textFile = new TextFile(reader, 100); List<String[]> result = textFile.parse(); assertResultFromTextFileParsing(result); new VerificationsInOrder() {{ reader.skip(100); reader.close(); }}; } @Test public void parseTextFileUsingBufferedReader(@Mocked final BufferedReader reader, @Mocked FileReader fileReader) throws Exception { new Expectations() {{ reader.readLine(); returns("line1", "another,line", null); }}; TextFile textFile = new TextFile("file"); List<String[]> result = textFile.parse(); assertResultFromTextFileParsing(result); new Verifications() {{ reader.close(); }}; } }
{ "content_hash": "80169bc41cfe73525fb449596c8e4fe1", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 115, "avg_line_length": 25.731182795698924, "alnum_prop": 0.6552444630171333, "repo_name": "russelyang/jmockit1", "id": "912e2da561ce6f889f44fd8190643f290f6b5f2e", "size": "2521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/test/integrationTests/textFile/TextFileUsingVerificationsTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3524" }, { "name": "Java", "bytes": "2057320" }, { "name": "JavaScript", "bytes": "3493" } ], "symlink_target": "" }
#pragma once #include "../kernel/value.h" #include "../../bmmlib.h" // forward declarations class MAXBitMapWindow; class MotionTracker; class MAXBitMap; // entry in MAXBitMap window table struct mbm_window { HWND window; MAXBitMap* mbm; }; /* ------------------------ MAXBitMap ------------------------------ */ applyable_class (MAXBitMap) class MAXBitMap : public Value { public: BitmapInfo bi; // our BitMapInfo Bitmap* bm; // the actual bitmap Tab<MotionTracker*> trackers; // any motion trackers MotionTracker* dragger; // tracker currently under drag WNDPROC main_window_proc; // original display window proc if ours installed GBuffer* gb; // GBuffer if non-NULL GBufReader* gbr; // current GBuffer reader if non-NULL short flags; static Tab<mbm_window> windows; // table of MAXBitMap windows currently open ScripterExport MAXBitMap(); ScripterExport MAXBitMap(BitmapInfo bi, Bitmap* bm); ~MAXBitMap(); static void setup(); static MAXBitMap* find_window_mbm(HWND hwnd); classof_methods (MAXBitMap, Value); # define is_bitmap(v) ((DbgVerify(!is_sourcepositionwrapper(v)), (v))->tag == class_tag(MAXBitMap)) void collect(); void gc_trace(); ScripterExport void sprin1(CharStream* s); Value* new_motionTracker(); void install_window_proc(); #include "../macros/define_implementations.h" def_visible_generic ( display, "display"); def_visible_generic ( unDisplay, "unDisplay" ); def_visible_generic ( save, "save" ); def_visible_generic ( gotoFrame, "gotoFrame"); def_visible_generic ( close, "close"); def_visible_generic ( getTracker, "getTracker" ); def_visible_generic ( deleteTracker, "deleteTracker" ); use_generic ( copy, "copy" ); def_visible_generic ( zoom, "zoom" ); def_visible_generic ( crop, "crop" ); def_visible_generic ( setAsBackground, "setAsBackground" ); def_visible_generic ( getPixels, "getPixels" ); def_visible_generic ( setPixels, "setPixels" ); def_visible_generic ( getIndexedPixels, "getIndexedPixels" ); def_visible_generic ( setIndexedPixels, "setIndexedPixels" ); def_visible_generic ( getChannel, "getChannel" ); def_visible_generic ( getChannelAsMask, "getChannelAsMask" ); use_generic ( free, "free"); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); ScripterExport void to_fpvalue(FPValue& v); }; #define BM_SAVED 0x0001 // bitmap has been written to and output steam is open #define BM_READONLY 0x0002 // existing bitmap opened (and so readonly). #define BM_FILEBACKED 0x0004 // bitmap is backed by a file /* -------------------- MotionTracker -------------------------- */ applyable_class (MotionTracker) class MotionTracker : public Value { public: MAXBitMap* mbm; // the bitmap I'm tracking int index; // which tracker in that bitmap int cur_frame; // frame I last tracked POINT center; // current feature center RECT bounds; // feature bounds relative to center RECT motion_bounds; // maximum frame-to-frame motion relative to feature center POINT mouse_down_at; // mouse pos at mousedown int handle_x; // handle pos at mouse_down.. int handle_y; // handle pos at mouse_down.. int handle; // which handle is dragging BYTE* target; // current target image as 3 BYTE RGB per pixel POINT* track_cache; // keeps a cache of tracking coords, one per frame (inval if change gizmo) short compare_mode; // feature matching space: rgb color, luminence, edge-filtered, etc. float match_distance; // last tracking match 'distance' HBITMAP id_bitmap; // unbelievable - I need to use a bitmap copy to do XOR text drawing short flags; MotionTracker(MAXBitMap* imbm, int iindex); ~MotionTracker(); classof_methods(MotionTracker, Value); void collect(); ScripterExport void sprin1(CharStream* s); void gc_trace(); void track(); void clear_track_cache(); void set_center(int x, int y); void set_index(int i); void copy_target(); void draw(HWND hWnd); void draw_gizmo(HDC hdc); void inval_gizmo(); BOOL start_drag(HWND hwnd, int wParam, long lParam); void drag(HWND hwnd, int wParam, long lParam); void end_drag(HWND hwnd); void move(HWND hwnd, int dx, int dy); void deselect(HWND hwnd); def_visible_generic ( resample, "resample"); def_visible_generic ( reset, "reset"); def_property ( center ); Value* get_property(Value** arg_list, int count); Value* set_property(Value** arg_list, int count); }; #define MT_GIZMO_SELECTED 0x0001 #define MT_GIZMO_MOVED 0x0002 #define MT_ENABLED 0x0004 #define MT_MATCH_RGB 0 #define MT_MATCH_GRAY 1 #define MT_MATCH_EDGE 2 #define MT_MATCH_RANK 3 #define MT_NO_HANDLE 0 // handle codes... #define MT_CENTER 1 #define MT_TOPLEFT_BOUNDS 2 #define MT_BOTLEFT_BOUNDS 3 #define MT_TOPRIGHT_BOUNDS 4 #define MT_BOTRIGHT_BOUNDS 5 #define MT_TOPLEFT_MBOUNDS 6 #define MT_BOTLEFT_MBOUNDS 7 #define MT_TOPRIGHT_MBOUNDS 8 #define MT_BOTRIGHT_MBOUNDS 9
{ "content_hash": "c3ce65b607a8897081dae394aa843242", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 100, "avg_line_length": 32.45859872611465, "alnum_prop": 0.6813186813186813, "repo_name": "favedit/MoCross", "id": "55931cb74db5931c576f26165274cdeaf4d9ea52", "size": "5191", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/Reference/MaxSdk-2014/Include/maxscript/maxwrapper/bitmaps.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "19515" }, { "name": "C", "bytes": "12939673" }, { "name": "C#", "bytes": "6744036" }, { "name": "C++", "bytes": "22566573" }, { "name": "Java", "bytes": "44614" }, { "name": "Makefile", "bytes": "3602334" }, { "name": "Objective-C", "bytes": "19417" }, { "name": "PHP", "bytes": "5760" }, { "name": "Python", "bytes": "170434" }, { "name": "R", "bytes": "2957" }, { "name": "Shell", "bytes": "220566" } ], "symlink_target": "" }
var filesystem = function () {} // vendor dependencies var Promise = require('bluebird') var s3 = require('s3') // local dependencies var logger = require(enduro.enduro_path + '/libs/logger') filesystem.prototype.init = function () { // no init required } filesystem.prototype.upload = function (filename, path_to_file) { var self = this return new Promise(function (resolve, reject) { var destination_url = self.get_remote_url(filename) var client = s3.createClient({ s3Options: { accessKeyId: enduro.config.variables.S3_KEY, secretAccessKey: enduro.config.variables.S3_SECRET, region: enduro.config.s3.region || 'us-west-1', }, }) var params = { localFile: path_to_file, s3Params: { Bucket: enduro.config.s3.bucket, Key: filename, }, } var uploader = client.uploadFile(params) uploader.on('error', function (err) { console.error('unable to upload:', err.stack) }) uploader.on('end', function () { logger.timestamp('File uploaded successfully: ' + destination_url) return resolve(destination_url) }) }) } filesystem.prototype.get_remote_url = function (filename, juicebox) { if (enduro.config.s3.cloudfront && !juicebox) { return 'https://' + enduro.config.s3.cloudfront + '/' + filename } else if (enduro.config.s3.region === 'us-east-1') { return 'https://s3.amazonaws.com/' + enduro.config.s3.bucket + '/' + filename } else { return 'https://s3-' + (enduro.config.s3.region || 'us-west-1') + '.amazonaws.com/' + enduro.config.s3.bucket + '/' + filename } } module.exports = new filesystem()
{ "content_hash": "251847a7811e9c0f3a3343625c4eeaa5", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 128, "avg_line_length": 26.433333333333334, "alnum_prop": 0.6702395964691047, "repo_name": "maxmedia/Enduro", "id": "82c4b1cd24f9ec96bc1b40067073b7e31968350d", "size": "1990", "binary": false, "copies": "1", "ref": "refs/heads/develop-mxm", "path": "libs/remote_tools/filesystems/s3_filesystem.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10009" }, { "name": "HTML", "bytes": "6194" }, { "name": "JavaScript", "bytes": "386606" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright [2017] [NIRVANA PRIVATE LIMITED] ~ ~ 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. --> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:centerColor="@color/transparent" android:endColor="@color/transparent" android:startColor="@color/gray_ebony_clay"/> </shape>
{ "content_hash": "98f1db789d70aaa58aebaf0327f26804", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 79, "avg_line_length": 38.34615384615385, "alnum_prop": 0.675025075225677, "repo_name": "NlRVANA/Unity", "id": "581fd666db4f212665f65a27b9fd85cb23af0b16", "size": "997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/shape_item_shadow.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17918" }, { "name": "Kotlin", "bytes": "441909" } ], "symlink_target": "" }
//初始化页面 var treeEname; var userId; var menuUrlValueType; var ssoSystemId_value; efform_onload = function (){ ssoSystemId_value = document.getElementById("result-0-ssoSystemId").value; menuUrlValueType = document.getElementById("result-0-menuType").value; var info=_getEi(); block_system = info.getBlock("result_system"); userId=info.get("userId"); treeEname=document.getElementById("result-0-treeEname").value; if(treeEname!=null && treeEname!=""){ efbutton.setButtonStatus("insert", false); document.getElementById("result-0-treeEname").readOnly=true; document.getElementById("result-0-nodeEname").readOnly=true; }else{ efbutton.setButtonStatus("update", false); } if(info.get("userId") == "anonymou"){ var parent = document.getElementById('result-0-menuType'); parent.removeChild(parent.options[0]); } selectCity(); } /** 页面逻辑验证 */ function validatePageLogic(){ //如果用户在“菜单来源”中选择“来自平台” 或“来自内容管理”,则“单点登录标识”只能为“不可用”; if(ef.get("result-0-menuType").value!="1"&&ef.get("result-0-ssoSystemId").value.trim().length>0){ alert("如果您在\"菜单类型\"中选择\"来自平台\" 或\"来自内容管理\",则\"单点登录系统标识\"只能选择\"不可用\""); return false; } } //点击新增按钮 button_insert_onclick = function(){ if(validatePageLogic()==false){ return; } if(treeEname==null || treeEname==""){ if(efvalidateDiv("ef_region_result")&& !checkchinese(document.getElementById("result-0-treeEname").value,"result-0-treeEname") && !checkchinese(document.getElementById("result-0-nodeEname").value,"result-0-nodeEname")){ var info = new EiInfo(); info.set("userId",userId); info.setByNode("ef_region_result"); EiCommunicator.send( "EV1401", "insert" , info, menu_callback ); } }else{ alert("请选择修改按钮!"); } } //点击修改按钮 button_update_onclick = function(){ if(validatePageLogic()==false){ return; } if(efvalidateDiv("ef_region_result")){ var info = new EiInfo(); info.set("userId",userId); info.setByNode("ef_region_result"); EiCommunicator.send( "EV1401", "update" , info, menu_callback ); } } //回调函数 var menu_callback = { onSuccess : function(eiInfo) { //efform_onload(); alert(eiInfo.get("clew")); if(eiInfo.get("clew") == "操作成功!"){ myrefresh(); } }, onFail : function(eMsg) { alert(eiInfo.get("clew")); } } function selectCity(){ var province=document.getElementById("result-0-menuType"); var options=province.options; var value=""; for(var i=0;i<options.length;i++){ if(options[i].selected){ value=options[i].value; if(value=="0"){ document.getElementById("result-0-menuUrl").readOnly=true; var htm="<img title='menu' src='"+efico.get("efform.efImgList")+"' onClick='openSelectMenu();'/>"; var node=document.getElementById("img"); node.innerHTML=htm; enptyMenuUrl(0); crSsoSystemId(0); menuUrlValueType = 0; }else if(value==1){ document.getElementById("result-0-menuUrl").readOnly=false; var htm=""; var node=document.getElementById("img"); node.innerHTML=htm; enptyMenuUrl(1); crSsoSystemId(1); menuUrlValueType = 1; }else if(value==2){ document.getElementById("result-0-menuUrl").readOnly=true; var htm="<img title='menu' src='"+efico.get("efform.efImgList")+"' onClick='openWindow();'/>"; var node=document.getElementById("img"); node.innerHTML=htm; enptyMenuUrl(2); crSsoSystemId(2); menuUrlValueType = 2; } } } } //在弹出grid中选择一个记录时触发的函数 function efgrid_onRowClicked( grid_id, row_index ){ if("test_divwindowsubNode" == grid_id){ grid = efgrid.getGridObject("test_divwindowsubNode"); if(grid.getCellValue(row_index,2,TYPE_DATA)==null || grid.getCellValue(row_index,2,TYPE_DATA)==""){ ef.get("result-0-menuUrl").value=" "; }else ef.get("result-0-menuUrl").value = grid.getCellValue(row_index,1,TYPE_FIX); efwindow.hide(); } } //点击菜单地址后图标时触发函数 function openSelectMenu(){ var info = new EiInfo(); var divWindow = efcascadeselect.createDivWindow( "test_divwindow", "efwindow","选择菜单url信息",350,270,"","关闭"); efwindow.show(ef.get("result-0-menuUrl"),"test_divwindow_ajax_loading"); EiCommunicator.send( "EV1401", "queryMenu", info, country_callback ,false,true ); } var divwindow; //回调函数 country_callback = { onSuccess : function(eiInfo){ divwindow = document.getElementById("test_divwindow"); efwindow.hide(); var style_config = new Object(); style_config["operationBar"] = "true"; var grid = new efgrid("result",divwindow.id+"subNode"); var custom_cols = {"index":{},"metas":[]}; grid.setEnable( false ); grid.setReadonly( true ); grid.setAjax( true ); grid.setAutoDraw( true ); grid.setServiceName( "EV1401" ); grid.setQueryMethod( "queryMenu" ); grid.setCustomColumns( custom_cols ); grid.setData( eiInfo ); grid.setStyle( style_config ); for(i=grid.dataColumns.length;i>=1;i--){ column = grid.getColumn( i-1, TYPE_DATA ); column.set( "width", 300/grid.dataColumns.length); } grid.paint(); efwindow.show(document.getElementById("result-0-menuUrl"),divwindow.id,"fixed"); }, onFail : function(eMsg){ alert("failure"); } } //点击新弹出grid关闭时回调函数 efcascadeselect.ensure_onclick = function(){ grid = efgrid.getGridObject(divwindow.id+"subNode"); efwindow.hide(); } //刷新父页面,关闭当前页面 function myrefresh(){ window.close(); } //弹出窗口 openWindow = function(){ if(userId == "anonymou"){ var obj = window.showModalDialog("DispatchAction.do?efFormEname=EVCM0204","","edge:raised;scroll:1;status:0;help:0;resizable:1;dialogWidth:200px;dialogHeight:250px;"); if(obj != undefined) document.getElementById("result-0-menuUrl").value=obj; }else{ var obj = window.showModalDialog("DispatchAction.do?efFormEname=EVCM0203","","edge:raised;scroll:1;status:0;help:0;resizable:1;dialogWidth:200px;dialogHeight:250px;"); if(obj != undefined) document.getElementById("result-0-menuUrl").value=obj; } } //如果是从用户自定义选择平台的或内容管理类的话menuUrl清空 enptyMenuUrl = function(size){ if(menuUrlValueType != size){ document.getElementById("result-0-menuUrl").value = " "; } } //选择单点登录select时候调用函数 selectSsoSystemId = function(){ ssoSystemId_value = document.getElementById("result-0-ssoSystemId").value; } //判断单点登录的select crSsoSystemId = function(size){ document.getElementById("result-0-ssoSystemId").options.length = 0; if(size == 1){ document.getElementById("result-0-ssoSystemId").options.add(new Option("不使用"," ")); for(var i=0;i<block_system.getRows().length;i++){ document.getElementById("result-0-ssoSystemId").options.add(new Option(block_system.getCell(i, "systemName"),block_system.getCell(i, "systemId"))); } document.getElementById("result-0-ssoSystemId").value = ssoSystemId_value; }else{ document.getElementById("result-0-ssoSystemId").options.add(new Option("不使用"," ")); } } //判断输入字符不能汉字以及一些特殊符号 function checkchinese(str,idName){ var badChar ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; badChar += "abcdefghijklmnopqrstuvwxyz"; badChar += "0123456789"; badChar += " "+" ";//半角与全角空格 badChar += "_"; for(var i=0;i<str.length;i++){ var c = str.charAt(i);//字符串str中的字符 if(badChar.indexOf(c) <= -1){ document.getElementById(idName).select(); alert("对不起,资源标签允许输入的字符包括:数字、英文字母(大小写均可)、和下划线(_),并且中间可以包含空格。"); return true; } } }
{ "content_hash": "748542d808d07e05ff19aa5d66ca3f64", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 221, "avg_line_length": 32.401709401709404, "alnum_prop": 0.6554998681086784, "repo_name": "stserp/erp1", "id": "b00082030b45b5260db2e3dcdae27eac740363ba", "size": "8224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/web/EV/EV1401.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "44086" }, { "name": "CSS", "bytes": "305836" }, { "name": "ColdFusion", "bytes": "126937" }, { "name": "HTML", "bytes": "490616" }, { "name": "Java", "bytes": "21647120" }, { "name": "JavaScript", "bytes": "6599859" }, { "name": "Lasso", "bytes": "18060" }, { "name": "PHP", "bytes": "41541" }, { "name": "Perl", "bytes": "20182" }, { "name": "Perl 6", "bytes": "21700" }, { "name": "Python", "bytes": "39177" }, { "name": "SourcePawn", "bytes": "111" }, { "name": "XSLT", "bytes": "3404" } ], "symlink_target": "" }
package com.ragdroid.rxify.codelab; import com.ragdroid.rxify.core.mvp.BasePresenter; import com.ragdroid.rxify.core.mvp.BaseView; /** * Created by garimajain on 08/11/16. */ public interface CodeLabContract { interface View extends BaseView { void append(String text); } interface Presenter extends BasePresenter { void prepare(); } }
{ "content_hash": "a0712aba1966fbadafc6b34bf575d898", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 49, "avg_line_length": 17.181818181818183, "alnum_prop": 0.6957671957671958, "repo_name": "ragdroid/rxify", "id": "d720b8474b1357d76cf79a8acbd3a8f802698334", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/ragdroid/rxify/codelab/CodeLabContract.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "99207" }, { "name": "Kotlin", "bytes": "5837" } ], "symlink_target": "" }
<div class="container"> <script type="text/stache" can-autorender id='main'> <can-import from="jquery" /> <can-import from="bootstrap" /> <can-import from="bootstrap/dist/css/bootstrap.css" /> <can-import from="bitcentive/styles.less" /> <can-import from="bitcentive/components/page-dashboard/contribution-month/" /> <bit-contribution-month contributionMonthId:from="contributionMonthId"/> </script> </div> <style> .callout { background-color: #fff; } </style> <script src="../../../node_modules/steal/steal.js" main="can-view-autorender"> import 'bitcentive/models/fixtures/fixtures-socket'; import viewModel from 'can-view-model'; import autorender from 'can-view-autorender'; window.viewModel = viewModel; autorender(function(){ viewModel(document.getElementById("main")).set("contributionMonthId","1"); }); </script>
{ "content_hash": "ee29c07875ed2d1bf4e39e796356ce20", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 80, "avg_line_length": 32.53846153846154, "alnum_prop": 0.7222222222222222, "repo_name": "donejs/bitcentive", "id": "e90ef22e896c9623733e5f4593422afe326f2435", "size": "846", "binary": false, "copies": "1", "ref": "refs/heads/staging", "path": "public/components/page-dashboard/contribution-month/contribution-month.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7085" }, { "name": "HTML", "bytes": "16436" }, { "name": "JavaScript", "bytes": "157970" } ], "symlink_target": "" }
SimpleBot ========= SimpleBot is an easy-to-install and easy-to-use general purpose IRC bot, written in Perl. It is built on the awesome [Bot::BasicBot](http://search.cpan.org/dist/Bot-BasicBot/) framework. Features at a glance: * Single-command install on most flavors of Linux * Alarm clock, countdown to date/time, timer * Google Calendar integration with countdown to events * Google Search commands for searching and defining terms * Weather system for current conditions and 5-day forecast * Twitter integration for automatically following or retweeting * Custom topic system for defining a set of columns and a divider * FAQ system to define custom commands that emit text * Scoreboard system for awarding points to users * Poll system with user voting * Calculator and unit converter * Version check and self-upgrade commands * Network utilities such as ping, DNS lookup, URL sniff * Custom greetings and goodbyes for users * Insult generator (have the bot insult a user) * Custom access level control for all commands (voice, half, op, etc.) * Custom activator symbols (exclamation point, etc.) * Configuration editing system from within IRC * Administrative commands including nick, join, restart, quit, upgrade, etc. * Puppet mode (have the bot say anything in any channel, sent from a PM) * Integrated help text for all commands * Database implemented with simple JSON files on disk ## Single-Command Install To install SimpleBot, execute this command as root on your server: curl -s "http://pixlcore.com/software/simplebot/install-latest-stable.txt" | bash Or, if you don't have curl, you can use wget: wget -O - "http://pixlcore.com/software/simplebot/install-latest-stable.txt" | bash This will install the latest stable version of SimpleBot. Change the word "stable" to "dev" to install the development branch. This single command installer should work fine on any modern Linux RedHat (RHEL, Fedora, CentOS) or Debian (Ubuntu) operating system. Basically, anything that has "yum" or "apt-get" should be happy. See the manual installation instructions for other OSes, or if the single-command installer doesn't work for you. After installation, you will be provided instructions for connecting to a server for the first time. If you are running our sister product, [SimpleIRC](https://github.com/jhuckaby/simpleirc), on the same server as SimpleBot, this will be detected and everything automatically set up and connected for you. ### Plugin APIs The bot's Weather Plugin uses a free API available from WeatherUnderground.com. You will need to sign up for a free account and get an API Key in order to use this Plugin. For instructions, type "!help weather" in a channel where the bot is, or "/msg simplebot help weather" on the IRC console. The bot's Twitter Plugin uses the free Twitter API v1.1. For this, you will need to sign up for a Twitter account, and create a free "application" on dev.twitter.com, in order to get API keys and use the Plugin. For instructions, type "!help twitter" in a channel where the bot is, or "/msg simplebot help twitter" on the IRC console. ## Command Summary * REGISTER - Attempt to register the bot nickname with NickServ. * IDENTIFY - Attempt to identify with NickServ (happens automatically on connect). * NICK - Change the bot's nickname permanently. * MSG - Send a custom private message to any user (i.e. NickServ, ChanServ, etc.) * ACCESS - Change user access levels for commands (set, get, list) * OWNER - Change bot ownership (add, remove, list) * ACTIVATOR - Change bot activator symbols (add, remove, list) * SAY - Have the bot say something (puppet mode) * EMOTE - Have the bot emote something. * EVAL - Eval raw Perl code (for debugging only) * EXEC - Execute raw shell command (for debugging only) * JOIN - Have the bot join a channel (remembers, autojoins) * LEAVE - Have the bot leave a channel (removes autojoin) * CONFIG - Set or get configuration values. * SAVE - Immediately save bot data to disk * QUIT - Make the bot disconnect and shut down. * RESTART - Make the bot restart itself. * VERSION - Report current and latest available version of SimpleBot. * UPGRADE - Upgrade SimpleBot to the latest version. * AUTOKICK - Add, delete or list phrases that automatically kick users when spoken. * CALC - Perform simple math calculations. * CONVERT - Convert values between many known units (i.e. temp, weight, volume). * RAND - Generate a random number given a maximum or range. * ROLL - Roll dice for use in Roll Playing Games, such as Dungeons & Dragons. * HASH - Generate MD5 hash of string, or a random source. * PICK - Pick a random user from the channel, and notify them. * 8BALL - Ask the magic 8-ball a question. * TIME - Emits the current date/time in the user's local timezone (if known). * ALARM - Sets single or repeating alarms which alert the user at the proper date/time. * COUNTDOWN - Countdown to a particular time, date or next calendar event. * TIMER - Simple countdown timer given minutes and seconds. * TIMEZONE - Set your timezone for date/time related queries. * QUAKES - Report most recent earthquake from USGS, and enable live quake monitoring. * FAQ - Register a custom FAQ command which can be recalled at any time. * CALENDAR - Attach a Google Calendar to the current channel, and show the current / next event. * CURRENT - Show the current event from the channel's calendar, if any. * NEXT - Show the next event on the channel's calendar and when it starts. * HELLO - Set auto-greeting so bot says hello to you when you join. * BYE - Set auto-goodbye so bot says goodbye to you after you leave. * HELP - Show this help text. * INSULT - Insult a user. * LAST - Report when a user was last seen in a channel. * PING - Pings a hostname to see if it responds, and reports the round trip time in milliseconds. * HOST - Attempts to resolve a hostname to IP, or IP to hostname, using DNS. * HEAD - Analyzes a given URL, and reports back its HTTP response headers (byte size, web server, etc.). * TCP - Attempt a TCP socket connection on a given hostname/IP and port number. * POINTS - Manage a "points" system to give special users credit. * AWARD - Award points to a user. * DEDUCT - Deduct points from a user. * SCORES - Show the top scores or clears the list. * POLL - Manage polls (open, close, results). * VOTE - Cast your vote for an open poll. * TOPIC - Set the channel topic in special named columns, separated by a divider. * TWITTER - Follow people on twitter, or retweet someone's latest tweet. * RT - Retweet the last tweet of any Twitter username or #hashtag. * FOLLOW - Start following a Twitter username or #hashtag in the current channel. * UNFOLLOW - Stop following a Twitter username or #hashtag in the current channel. * FOLLOWING - List all users and/or #hashtags we are current following on Twitter. * WEATHER - Get current conditions for US zip code, 'city state' or 'city country'. * FORECAST - Set 5 day forecast for US zip code, 'city state' or 'city country'. * LOCATION - Set your default location and time zone for future queries. * GOOGLE - Perform Google search and return first result. * IMAGE - Perform Google image search and return direct URL to first result. * DEFINE - Define term using the Wikipedia API or DictionaryAPI.com. * SPELL - Spell check a word (uses DictionaryAPI.com). * URBAN - Define term using the Urban Dictionary API. * STOCK - Grab stock quote given company symbol (uses Yahoo Finance API). * BITCOIN - Lookup the current price of Bitcoin in USD. * REDDIT - Emit random image from front page of selected subreddit. * ROTTEN - Lookup movie ratings from RottenTomatoes.com. * PLOT - Lookup movie plot (synopsis) from RottenTomatoes.com. * CAST - Lookup movie cast from RottenTomatoes.com. * BEER - Lookup beer information from BreweryDB.com. * NEWS - Lookup news for a specific topic, using the Google News API. * XKCD - Grab latest comic title and image from xkcd.com. ## Admin Group ### ACCESS ACCESS set command level ACCESS get command ACCESS list This allows you to manipulate the minimum user access levels per each bot command. For example, 'access set emote op' would only allow operators (and up) to access the 'emote' command. Use 'access get emote' to determine the current access level for a command, or 'access list' to list levels for all commands. Examples: !access set join owner !access get twitter !access list ### ACTIVATOR ACTIVATOR add symbol ACTIVATOR remove symbol ACTIVATOR list This allows you to manipulate the activation symbols that the bot recognizes. By default the bot listens to tilde ('~') and exclamation ('!') prefixed commands, but you may remove these and add others. Any non-alphanumeric symbol is acceptable. Example: activator add ^ ### CONFIG CONFIG SET path value CONFIG GET path This command lets you get or set configuration values, without having to directly edit the config files on the server. The values are saved in the bot database, and overide the config file values when the bot starts up. You do have to know the "path" of the configuration value you want to get/set, which can be a simple key name, or PluginName/ElementName for plugin configurations. Examples: !config set server 127.0.0.1 !config set port 6667 !config set Weather/APIKey cxs2x8wb5eh8mydgf74qa4s !config set Twitter/AccessTokenSecret BqF4txQFOWvdgwxdKxaviJlx91gI6Xprks763j ### EMOTE EMOTE text EMOTE #channel text Same as "say", but causes the bot to emote instead. ### EVAL EVAL code This will evaluate (run) raw Perl code. Use with extreme caution. Bot owners only. ### EXEC EXEC command This will execute the provided text as a shell command on the server. Use with extreme caution. Bot owners only. ### IDENTIFY IDENTIFY IDENTIFY password This command makes the bot attempt to identify with NickServ. This happens automatically upon connect, as long as a password is specified in the bot's config file. The standard '/msg NickServ IDENTIFY PASSWORD" command is sent, unless otherwise specified on the command itself (i.e. you can enter a different password, or different arguments altogether, if the IRC server requires it). Whatever you enter is then remembered for future connections on the same server. ### JOIN JOIN #channel This will cause the bot to join the channel specified by #channel. Also, he will remember this and auto-join the channel whenever he connects. ### LEAVE LEAVE LEAVE #channel This will cause the bot to leave a channel. You can specify the channel by name, or omit it to have the bot leave the current channel. ### MSG MSG who message Send a custom private message to any user. This can be used to construct custom commands for NickServ or ChanServ. For example: !msg NickServ REGISTER mypassword myemail. However, see REGISTER command. ### NICK NICK newnick This command changes the bot's nickname. The new name is saved to disk, so the bot will always remember its current value, even after a restart. ### OWNER OWNER add username OWNER remove username OWNER list This allows you to manipulate the list of bot "owners", which are users who always have full control over the bot and can execute every command, regardless of access level. Note that a user must have at least Half-Op (+h) permissions to become a bot owner. This is a protection system to prevent users from changing their nick to a known bot owner who is offline, and then trying to access the bot before the nick identify timeout occurs. ### QUIT QUIT This will cause the bot to disconnect from the IRC server and shut down. It will NOT restart. ### REGISTER REGISTER REGISTER password email REGISTER any params needed This command makes the bot attempt to register its nickname with NickServ. The standard "/msg NickServ PASSWORD EMAIL" command is sent, using the password and email in the bot's config file, unless otherwise specified on the command itself. If you like you can format your own REGISTER command, as required by the IRC server. Bot owners only. ### RESTART RESTART This will cause the bot to disconnect and reconnect to the IRC server. ### SAVE SAVE This causes the bot to immediately save all data to disk. Normally this process happens automatically in the background every minute, if any data has changed. However, this command will jump the interval and save instantly. ### SAY SAY text SAY #channel text Have the bot say something. Include #channel to specify a channel, so for example you can tell the bot what to say in a private chat, and he'll emit the text on a specific channel. Omit #channel and he'll just say it in the same context you spoke to him. ### UPGRADE UPGRADE UPGRADE branch This command upgrades the bot to the latest available version on PixlCore.com. If you enter the command by itself, it upgrades to the latest version in the current branch (i.e. stable, dev, etc.). However, you can also switch branches using the upgrade command. Just include the branch name after the command. For example, if you are on the stable branch and want to switch to the bleeding-edge development branch, type: !upgrade dev ### VERSION VERSION This will emit the current installed version of the SimpleBot software, as well as check PixlCore.com to see if there is a newer version available. ## Auto Kick Group ### AUTOKICK AUTOKICK add BADWORD AUTOKICK delete BADWORD AUTOKICK list This allows you to set special words or phrases (regular expressions) that will automatically kick users if spoken. Use '!autokick add WORD' to add a word or phrase to the list, '!autokick delete WORD' to remove one, and '!autokick list' to list them all. The list is channel specific. To change the message sent to users as they are kicked out, use this command: !config set AutoKick/KickMessage Your Message Here ## Calc Group ### CALC CALC expression This command performs simple math calculations, and posts the answer to the channel (or user if in a private message). Examples: !calc 45 + 5 !calc (374634 * 34) / 500.1 !calc 2 ** 8 ### CONVERT CONVERT value units to units This command converts numerical values between various units, such as temperature, weight and volume. It posts the answer to the channel (or user if in a private message). For example, you could type "!convert 45 lbs to kg" to convert pounds to kilograms, which would output 20.41165665 kg. Examples: !convert 100 lbs to kg !convert 25 C to F !convert 5 mm to in !convert 1 gallon to cm^3 !convert 4500 rpm to hz ### HASH HASH HASH string This command computes an MD5 digest (hash) given a source string, or creates a random one if nothing is provided. The output is 32-characters in length, lower-case, and hexadecimal encoded. ### PICK PICK This command picks a random user from the current channel. All nicks that end in "bot" or "serv" are excluded, as well as the bot itself (even if its name doesn't end in "bot"). The idea is to pick humans only. The chosen user's nickname is emitted to the channel. Uses an ultra-random number generator. ### RAND RAND RAND max RAND min - max This command picks a random number, and emits the result. Without any parameters, it picks a floating point decimal between 0.0 and 1.0. With one number specified, it is treated as the maximum, and picks a number between 0 and it. With two numbers specified, they are treated as a range. Will round down to nearest integer if only integers are provided, otherwise it will use floats. Uses an ultra-random number generator. ### ROLL ROLL dice ROLL dice +/- modifier This command rolls dice for use in RPGs like Dungeons & Dragons. It can roll any number of any-sided die, plus or minus a modifier. The syntax for the dice is (NUM)d(SIDES), and the optional modifier is simply +/-(NUMBER). Uses an ultra-random number generator. Examples: !roll 1d6 !roll 2d20 !roll 1d100 +20 ## Clock Group ### ALARM ALARM SET date/time ALARM SET date/time description ALARM LIST ALARM DELETE index Use ALARM SET to set an alarm for any future date/time. The bot should figure out your formatting. Something as simple as "!alarm set 8:30" would work, as well as "!alarm set sunday january 25 6pm repeat call nancy". Include the word "repeat" for a repeating alarm (otherwise it is one time only), and an optional description. Enter "!alarm list" to list all the current alarms, and "!alarm delete 1" to delete the first one in the list. The alarm will sound in the channel in which it was set. Examples: !alarm set 9:45 !alarm set 4:30 pm Walk the Dog !alarm set saturday 11 am repeat Watch Podcast ### COUNTDOWN COUNTDOWN TO time COUNTDOWN TO date/time description COUNTDOWN TO CALENDAR COUNTDOWN STOP This command sets a countdown to a specific point in time. Specify the destination date and/or time, or use the keyword "calendar" to count down to the next event on a Google Calendar attached to the channel. Examples: "!countdown to 7:30", and "!countdown to calendar". The bot emits progress reports in ever-increasing frequency as the target time approaches. Use "!countdown stop" to cancel an active timer. Only one timer may be active per channel. Examples: !countdown to 9:30 !countdown to midnight !countdown to sunday 4:30 pm !countdown to calendar ### TIME TIME TIME timezone This command prints the current bot server date and time, in the local timezone of the user, if known (i.e. see !help location). Examples: !time !time Eastern !time GMT ### TIMER TIMER MM::SS TIMER HH::MM::SS TIMER STOP This command sets a countdown timer, given a duration specified in MM::SS, HH::MM::SS or human time, such as "5 minutes". The bot emits progress reports in ever-increasing frequency as the target time approaches. Use "!timer stop" to cancel an active timer. Only one timer may be active per channel. Examples: !timer 5:00 !timer 1:00:00 !timer 45 minutes !timer 12 hours ### TIMEZONE TIMEZONE zone Set your personal timezone for future date/time queries. It will always be remembered for you, so you only have to enter it once. This affects bot commands such as !time, !alarm and !countdown. You can use any of the following formats: !timezone Pacific !timezone Eastern !timezone America/Los_Angeles !timezone GMT-0800 ## Earthquake Group ### QUAKES QUAKES on QUAKES off QUAKES status QUAKE This command can enable or disable live earthquake monitoring (data provided by USGS). The bot can emit earthquake reports into the current channel, within 60 seconds of the event happening. Type "!quakes on" to enable live monitoring, "!quakes off" to disable it, and "!quakes status" to get the current status. You can also type "!quake" to emit the most recent quake reported in the last 24 hours. The USGS provides five different earthquake feeds, which vary on their minimum magnitude. To set which feed to pull from, use this command: !config set Earthquake/FeedID significant Acceptable values for FeedID are "significant", "4.5", "2.5", "1.0" or "all". ## FAQ Group ### FAQ FAQ command answer FAQ list FAQ delete NAME This registers a custom FAQ command and associates some text with it. Then, users can recall the FAQ answer by entering the custom command just like any other bot command. You can also use "!faq list" to get a list of all the FAQ commands for the current channel, and "!faq delete NAME" to delete them. Examples: !faq myserver Welcome to my server! Please read the rules at http://myserver.com/rules/ !myserver !faq list !faq delete myserver To control which users have access to view FAQs, set the access level for the 'faqview' pseudo-command, like this: !access set faqview voice ## Google Calendar Group ### CALENDAR CALENDAR SET your-google-cal-id CALENDAR REFRESH CALENDAR CURRENT CALENDAR NEXT CALENDAR DELETE These commands allow you to attach a Google Calendar to the current #channel, so you can emit the current and next events anytime you want. To find your Calendar ID, open your calendar in Google, make sure it is public, edit settings, then grab the ID in the "Calendar Address" section which should look like this: "(Calendar ID: iu9de9ell3bhagnk1con4052q0@group.calendar.google.com)". The CALENDAR command can be abbreviated to just "CAL" if you want, i.e. "!cal refresh". ### CURRENT CURRENT This emits the current calendar event to the channel, including its title and the time it started (uses timezone from calendar). ### NEXT NEXT This emits the next upcoming calendar event to the channel, including its title and starting time (uses timezone from calendar). Will also include the starting date if it is after today. ## Hello Bye Group ### BYE BYE goodbye-text This sets an automatic "goodbye" that the bot will speak in each channel you leave (or all channels if you drop off IRC). Omit goodbye text to disable. ### HELLO HELLO greeting-text This sets an auto-greeting of your choice, which the bot will remember. When you join a channel that the bot is in, it will speak your custom greeting. Omit greeting text to disable. ## Help Group ### HELP HELP HELP command Shows general help, or if a command is specified, shows help for that particular command. ## Insult Group ### INSULT INSULT nickname INSULT nickname adjective INSULT nickname adjective noun. Generates a random insult and throws it at the target user. You may specify replacement adjectives and/or a replacement noun if you like. Specify which is which by adding punctuation to the noun only. The insult database was borrowed and modified from the Perl Acme-Scurvy-Whoreson-BilgeRat-Backend-insultserver module: http://search.cpan.org/dist/Acme-Scurvy-Whoreson-BilgeRat-Backend-insultserver/ ## Last Group ### LAST LAST nickname This reports when the user was last seen in the channel, and what he/she last said. ## Net Group ### HEAD HEAD url This command analyzes a given URL, and reports back its size, web server software, and any other information it has. Command aliases: !whead, !http, !sniff, !url ### HOST HOST hostname This command attempts to resolve a given hostname to IP address, or IP to hostname, using local DNS. Command alias: !dns ### PING PING hostname This command pings a given hostname or IP address, and reports the round trip packet time. ### TCP TCP hostname port This command attempts a TCP socket connection on the given hostname/IP and port. It returns if the operation was successful or not. Command aliases: !connect, !telnet ## Points Group ### AWARD AWARD nickname points This gives the target user the specified amount of "points". Points are an arbitrary score rating which can be used for whatever you want. The amount of points must be an integer. Examples: !award eric 50 !award nancy 10 ### DEDUCT DEDUCT nickname points This is the opposite of award, meaning it takes points away from the user. If the user's score hits zero (or below) they are removed from the score list. Examples: !deduct eric 50 !deduct nancy 10 ### POINTS POINTS AWARD - Award points to a user. POINTS DEDUCT - Deduct points from a user. POINTS SCORES - Show the top scores or clears the list. Use these commands to manage a "points" system for your users. Give special users points for rewards that you invent. You can reward or deduct points, and see the current "scores" of the top users. You can optionally omit the POINTS command and just type the sub-commmands directly. See help on the individual sub-commands for more details, e.g. HELP AWARD or HELP SCORES. ### SCORES SCORES SCORES 20 SCORES clear This shows you the top scoring users with the most points. It defaults to showing the top 10, but you can include a different number to show the top N users. To clear ALL the scores from all users, enter "!scores clear". ## Poll Group ### POLL POLL open MY TITLE POLL open MY TITLE (ITEM1, ITEM2, ITEM3) POLL status POLL close POLL results POLL history This command manages polls. Use the "!poll open ..." command to start a new poll, but specify the poll title after the command, e.g. "!poll open What's your favorite food?". Type "!poll close" to close the poll, and "!poll results" to get the voting results. To see historical polls, use "!poll history". If you want to limit the items people can vote for, include them as a comma-separated list in parenthesis. Examples: !poll open What's your favorite OS? !poll open What game should we play? (Minecraft, FTB, Pong) !poll close !poll results ### VOTE VOTE (your vote) This command casts your vote in the current open poll. Just enter the desired value after the command, e.g. "!vote pizza". Votes are matched case-insensitively against previous votes. So if someone votes for "pizza" and someone else votes for "PIZZA", they are treated as the same value. ## Topic Group ### TOPIC TOPIC - Set the channel topic column. TOWNER - Set the channel topic "owner" column (your name). TVERB - Set the channel topic "verb" column (i.e. "is"). TSTATUS - Set the channel topic "status" column (i.e. "Away"). TSTATIC - Set the channel topic "static" column (i.e. your website URL). TDIVIDER - Set the divider string which separates the topic columns, defaults to a pipe (|). TREFRESH - Refresh the channel topic, in case some Op changed it manually. TRESET - Reset (clear) the topic to a blank string. TON - Shortcut for !tstatus Online TOFF - Shortcut for !tstatus Offline These commands control the channel topic using a set of named "columns" and a divider. It is based on an original design by TMFKsoft and also used in the popular Techie-Bot. It produces topics like the following: "Minecraft Chat | Eric is Online | http://mysever.com". That is made of up 5 different columns, a topic (Minecraft Chat), an owner (Eric), a verb (is), a status (Online), and a static string (http://myserver.com). You can set each column separately without affecting the others: !topic Minecraft Chat !towner Eric !tverb is !tstatus Away !tstatic http://mywebsite.com ## Twitter Group ### FOLLOW FOLLOW @username FOLLOW #hashtag Starts following @username's tweets (or tweets for a #hashtag) on Twitter, and automatically echos them into the current channel. Will omit @replies and RTs by the user. Please note that due to Twitter API throttling, the bot can only check one per user's timeline once per minute, so if the bot is following 2 people, it may take up to 2 minutes to see new tweets from either of them. ### FOLLOWING FOLLOWING List all users and/or hashtags we are currently following on Twitter, and in which channels. ### RT RT @username RT #hashtag Retweet the last tweet of the specified Twitter username or #hashtag. Will omit @replies and RTs by the user. ### TWITTER TWITTER RT - Retweet the last tweet of any Twitter username into the current channel. TWITTER FOLLOW - Start following a Twitter username in the current channel. TWITTER UNFOLLOW - Stop following a Twitter username in the current channel. TWITTER FOLLOWING - List all users we are current following on Twitter. TWITTER RELOAD - Reload the Twitter Plugin (reconnect to the Twitter API). Use these commands to follow people on twitter, manage your follow list, or retweet the latest tweet by any Twitter user. You can optionally omit the TWITTER command and just type the sub-commmands directly (except for RELOAD). See help on the individual sub-commands for more details, e.g. HELP RT or HELP FOLLOW. To set up the Twitter Plugin for the first time, you will have to register for an API key at dev.twitter.com. This is a free developer API so the bot can establish a connection on your account's behalf, to read tweets using the officialy supported Twitter API v1.1. Go to https://dev.twitter.com/ to get started. To register the bot, go to https://dev.twitter.com/apps and click "Create a new application". Fill out the form, naming the application whatever you want. The bot only requires "Read Only" access, and you can leave the "Callback URL" blank. When finished, click "Create your Twitter application". At this point you should be given 4 different alphanumeric keys, a "Consumer key", "Consumer secret", "Access token" and "Access token secret". Teach all four of these to the bot like this: !config set Twitter/ConsumerKey YOUR_CONSUMER_KEY_HERE !config set Twitter/ConsumerSecret YOUR_CONSUMER_SECRET_HERE !config set Twitter/AccessToken YOUR_ACCESS_TOKEN_HERE !config set Twitter/AccessTokenSecret YOUR_ACCESS_TOKEN_SECRET_HERE At this point the Twitter Plugin should be ready to use, and the API keys will be saved in case the bot restarts. Test it by trying to retweet your last tweet into chat: "!rt @YOUR_TWITTER_NAME". ### UNFOLLOW UNFOLLOW @username UNFOLLOW #hashtag Stop following @username's tweets (or all tweets from a #hashtag) in the current channel. ## Weather Group ### FORECAST FORECAST location Get a 5-day forecast for the specified location, which can be any 5-digit US ZIP code, or any city and country separated by spaces. For example, 'forecast guelph canada' or 'forecast toronto canada'. Countries needs to be spelled out. See "!help weather" for details on setting up your API key for WeatherUnderground.com (it's free). ### LOCATION LOCATION city state country LOCATION zipcode Set your location for future weather and date/time queries, which the bot remembers. This also looks up your time zone based on your location, and stores that for displaying and calculating dates and times for you. See "!help weather" for details on setting up your API key for WeatherUnderground.com (used for the location service -- it's free). ### WEATHER WEATHER location Get current weather conditions. Specify any 5-digit US ZIP code, or any city and country separated by spaces. For example, 'weather guelph canada' or 'weather toronto canada'. Countries need to be spelled out. To get weather for countries outside the US, you will need to register for a free API Key at: http://www.wunderground.com/weather/api/ After signing up, copy your API key and paste it into this command: !config set Weather/APIKey YOUR_API_KEY_HERE At this point the Weather Plugin should be ready to use. Test it out by checking your local weather: "!weather london england". ## Web Search Group ### BEER BEER name Use this command to lookup beer information from BreweryDB.com. Please note that this API requires a free API key. Sign up at http://www.brewerydb.com/developers/ and then configure your API key with this command: !config set WebSearch/BeerAPIKey YOUR_API_KEY_HERE ### BITCOIN BITCOIN BTC Lookup the current price of Bitcoin in US dollars. This uses a free API from BitStamp.net. ### DEFINE DEFINE term This uses the Wikipedia API to locate a suitable definition for a term. The result is emitted to the current channel. If a definition cannot be found, the bot also tries DictionaryAPI.com (Merriam-Webster), which requires a free API key. Sign up at http://www.dictionaryapi.com/ and then configure your API key with this command: !config set WebSearch/DictAPIKey YOUR_API_KEY_HERE Note that this is optional, and the DEFINE command works just fine with Wikipedia for most terms. The DictionaryAPI.com is mainly used as a fallback, if the Wikipedia API fails or it doesn't define a particular term. ### GOOGLE GOOGLE search-query GOOGLE nickname This uses the Google Search API to search for a query, and returns the first result. If a username is specified, the last thing the user said is used as the query. The result is emitted to the current channel. ### IMAGE IMAGE search-query IMAGE nickname This uses the Google Image Search API to search for an image given a text string, and returns a direct URL to the first result. If a username is specified, the last thing the user said is used as the query. The result is emitted to the current channel. If you repeat the same query multiple times, it will cycle through the first 4 results. Note that Google SafeSearch is used by default. If you want an unsafe image search, use this syntax: '!image unsafe YOUR_QUERY'. ### NEWS NEWS topic Lookup news for a particlar topic, using the free Google News API. The article source, title, link, and summary are emitted to the channel. ### REDDIT REDDIT subreddit R subreddit Pick a random image from the front page of the specified subreddit, and output the image URL. Examples: !reddit earthporn !r aww ### ROTTEN ROTTEN movie MOVIE movie PLOT movie CAST movie Use these commands to lookup movie ratings, synopsis and cast using the RottenTomatoes.com API. Please note that this API requires a free API key. Sign up at http://developer.rottentomatoes.com/ and then configure your API key with this command: !config set WebSearch/RottenAPIKey YOUR_API_KEY_HERE ### SPELL SPELL word This command uses the free API provided by DictionaryAPI.com (Merriam-Webster) to check the spelling of a word. If the word cannot be found in the dictionary, spelling suggestions are provided. Please note that this API requires a free API key. Sign up at http://www.dictionaryapi.com/ and then configure your API key with this command: !config set WebSearch/DictAPIKey YOUR_API_KEY_HERE ### STOCK STOCK symbol This uses the Yahoo Finance API to grab a stock quote for the given symbol. It reports the current price and change. Example: !stock GOOG ### URBAN URBAN term This uses the Urban Dictionary API to locate a suitable definition for a term. The result is emitted to the current channel. Beware: Urban Dictionary can be very NSFW. Use this at your own risk. Remember, you can restrict access for any command to be owner only: !access set urban owner ### XKCD XKCD This grabs the latest comic title and image from xkcd.com. ## Copyright and Legal SimpleBot is copyright (c) 2013 - 2014 by Joseph Huckaby and PixlCore.com. It is released under the MIT License (see below). SimpleBot relies on the following non-core Perl modules, which are automatically installed, along with their prerequisites, using [cpanm](http://cpanmin.us): * POE * Bot::BasicBot * JSON::XS * LWP::UserAgent * URI::Escape * HTTP::Date * DateTime * DateTime::TimeZone * DateTime::TimeZone::Alias * Net::Twitter::Lite * Net::Ping::External * Math::Units ### MIT License 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.
{ "content_hash": "591c0b22e975c04619509b135c00f978", "timestamp": "", "source": "github", "line_count": 798, "max_line_length": 495, "avg_line_length": 44.46115288220551, "alnum_prop": 0.7616685456595265, "repo_name": "jhuckaby/simplebot", "id": "613c744387d5bd19bb302858522b1a66324c9071", "size": "35480", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Perl", "bytes": "252397" }, { "name": "Shell", "bytes": "8373" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>QQmlFileSelector &mdash; PyQt 5.5.1 Reference Guide</title> <link rel="stylesheet" href="../_static/classic.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '5.5.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/logo_tn.ico"/> <link rel="top" title="PyQt 5.5.1 Reference Guide" href="../index.html" /> <link rel="up" title="PyQt5 Class Reference" href="../class_reference.html" /> <link rel="next" title="QQmlImageProviderBase" href="qqmlimageproviderbase.html" /> <link rel="prev" title="QQmlExtensionPlugin" href="qqmlextensionplugin.html" /> </head> <body role="document"> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qqmlimageproviderbase.html" title="QQmlImageProviderBase" accesskey="N">next</a> |</li> <li class="right" > <a href="qqmlextensionplugin.html" title="QQmlExtensionPlugin" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="qqmlfileselector"> <h1>QQmlFileSelector<a class="headerlink" href="#qqmlfileselector" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="PyQt5.QtQml.QQmlFileSelector"> <em class="property">class </em><code class="descclassname">PyQt5.QtQml.</code><code class="descname">QQmlFileSelector</code><a class="headerlink" href="#PyQt5.QtQml.QQmlFileSelector" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="http://doc.qt.io/qt-5/qqmlfileselector.html">C++ documentation</a></p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/logo.png" alt="Logo"/> </a></p> <h4>Previous topic</h4> <p class="topless"><a href="qqmlextensionplugin.html" title="previous chapter">QQmlExtensionPlugin</a></p> <h4>Next topic</h4> <p class="topless"><a href="qqmlimageproviderbase.html" title="next chapter">QQmlImageProviderBase</a></p> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="qqmlimageproviderbase.html" title="QQmlImageProviderBase" >next</a> |</li> <li class="right" > <a href="qqmlextensionplugin.html" title="QQmlExtensionPlugin" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.5.1 Reference Guide</a> &raquo;</li> <li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> &raquo;</li> </ul> </div> <div class="footer" role="contentinfo"> &copy; Copyright 2015 Riverbank Computing Limited. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1. </div> </body> </html>
{ "content_hash": "f8b6bc6623b83b972820bc30de211c6d", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 231, "avg_line_length": 43.78225806451613, "alnum_prop": 0.5986369497144962, "repo_name": "lnerit/ktailFSM", "id": "482f5b50425f116ab2e5d1afad5ebe972ed67286", "size": "5431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/lib.linux-x86_64-2.7/PyQt-gpl-5.5.1/doc/html/api/qqmlfileselector.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1244611" }, { "name": "C++", "bytes": "162227" }, { "name": "CMake", "bytes": "263764" }, { "name": "CSS", "bytes": "43770" }, { "name": "HTML", "bytes": "6828420" }, { "name": "JavaScript", "bytes": "181156" }, { "name": "Lex", "bytes": "20379" }, { "name": "NSIS", "bytes": "26328" }, { "name": "Python", "bytes": "777767" }, { "name": "XQuery", "bytes": "2830" }, { "name": "Yacc", "bytes": "240898" } ], "symlink_target": "" }
<div class="constructor"></div>
{ "content_hash": "4f49832ecfbeccb3765a546c84d8711f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.6875, "repo_name": "ginseng/ginseng", "id": "6b49665c3e1b12f0b38a3b09d521a9ea8269a267", "size": "32", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/fixtures/spec/constructor.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1845" }, { "name": "JavaScript", "bytes": "167198" }, { "name": "Makefile", "bytes": "2124" }, { "name": "Shell", "bytes": "2545" } ], "symlink_target": "" }
title: Melvin Draupnir seotitle: Melvin Draupnir img: /images/melvin-draupnir.jpg position: Journalist education: School of Hard Knocks experience: Real Life short_desc: Melvin Draupnir is a cryptocurrency journalist. long_desc: Melvin Draupnir is a cryptocurrency journalist with interests in cybersecurity, open-source , network effects and the intersection between economics and cryptography that make Bitcoin a natural fit. affiliations: twitter: bitcoinminer github: residence: Moon cats: [ ] website: --- <p>Melvin Draupnir is a cryptocurrency journalist living on the Moon, where Bitcoin is going!, and has been entrenched in the cryptocurrency community since 2012. <p>His passions include open source code, Bitcoin, cryptocurrency, economics, geopolitics and decentralized applications. A student of Austrian Economics, Draupnir found Bitcoin in 2012 and has been a hodler and evangelist ever since. <p>His interests in cybersecurity, open-source , network effects and the intersection between economics and cryptography make Bitcoin a natural draw. <p>Draupnir has written hundreds of articles about these topics and their emergence today.
{ "content_hash": "7d31be6aa91e38166fb055225abac8f1", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 234, "avg_line_length": 60.63157894736842, "alnum_prop": 0.8185763888888888, "repo_name": "sunnankar/wucorg", "id": "fd00cc745ba1453b6c4b5a6e9180359ef26c4e63", "size": "1156", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_people/melvin-draupnir.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "191423" }, { "name": "HTML", "bytes": "2070119" }, { "name": "JavaScript", "bytes": "126181" }, { "name": "PHP", "bytes": "96" }, { "name": "Python", "bytes": "2572" } ], "symlink_target": "" }
import copy import numpy as np import matplotlib.pyplot as plt from pylab import * class MLDiagnostics: """ This class can be used to produce learning curves. These are plots of evolution of Training Error and Cross Validation Error across lambda(in general a control param for model complexity). This plot can help diagnose if the ML algorithmic model has high bias or a high variance problem and can thus help decide the next course of action. In general, ML Algorithm is of the form, Y=f(t,X) + lambdaVal*|t| where Y is the output, t is the model parameter vector, lambdaVal is the regularization parameter. |t| is the size of model parameter vector. """ def __init__(self, learner, Xtrain, Ytrain, Xcv, Ycv, lambdaArray): self.learner = learner self.Xtrain = Xtrain self.Ytrain = Ytrain self.Xcv = Xcv self.Ycv = Ycv self.lambdaArray = lambdaArray self.ErrTrain = np.zeros((len(lambdaArray), 1)) self.ErrCV = copy.copy(self.ErrTrain) def avgsqerror(self, Y, Ypred): return np.sum((Y - Ypred) ** 2) / len(Y) def plotCurves(self, filename): Xrange = [i * self.step for i in range(1, len(self.ErrTrain) + 1)] plt.plot(Xrange, self.ErrTrain, label="Train Error") plt.plot(Xrange, self.ErrCV, label="CV Error") plt.title('Learning Curves') plt.xlabel('# of Training Examples') plt.ylabel('Average Error') plt.draw() savefig(filename, format='pdf') def runDiagnostics(self, filename): for i, lambdaVal in zip(range(len(self.lambdaArray)), self.lambdaArray): learner = copy.copy(self.learner()) # is deep copy required # setLambda needs to be a supported function for all ML strategies. learner.setLambda(lambdaVal) learner.addEvidence(self.Xtrain, self.Ytrain) YtrPred = learner.query(self.Xtrain) self.ErrTrain[i] = self.avgsqerror(self.Ytrain, YtrPred) YcvPred = learner.query(self.Xcv) self.ErrCV[i] = self.avgsqerror(self.Ycv, YcvPred) self.plotCurves(filename)
{ "content_hash": "fdfaa7295e6900eed8f81ceab852db6d", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 141, "avg_line_length": 43.09803921568628, "alnum_prop": 0.6442220200181984, "repo_name": "hughdbrown/QSTK-nohist", "id": "ab7f82e7187d07dd087a34ede8906af8f7ad50e8", "size": "2596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qstklearn/mldiagnostics.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "5708" }, { "name": "Java", "bytes": "8096" }, { "name": "JavaScript", "bytes": "10874" }, { "name": "Python", "bytes": "707741" }, { "name": "Racket", "bytes": "2540" }, { "name": "Ruby", "bytes": "4262" }, { "name": "Shell", "bytes": "4600" } ], "symlink_target": "" }
var models = require('../models'), GeoFeatureCollection = models.GeoFeatureCollection, coordinates = require('geogoose').coordinates, config = require('../config'), format = require('../api/import/formats/geojson'), assert = require('assert'), mongoose = require('mongoose'), _ = require('underscore'); describe('GeoJSON raw', function() { var featureCollection, GeoFeature; before(function(done) { mongoose.connect(config.DB_URI); featureCollection = new GeoFeatureCollection({ active: true, status: config.DataStatus.COMPLETE, title: 'GeoJSON test' }); featureCollection.save(function(err, collection) { GeoFeature = collection.getFeatureModel(); return done(err); }); }); it('should import a GeoJSON file and save each Feature in the DB', function(done) { var parser = format.Parser(), totalCount, saved = 0; var onData = function(data) { var f = new GeoFeature(data, false); f.featureCollection = featureCollection; f.save(function(err, result) { if (err) throw err; saved++; if (saved == totalCount) { done(); } }); }; var onEnd = function(data) { }; parser.on('data', onData) .on('end', onEnd) .on('root', function(root, count) { totalCount = count; }); parser.fromPath('test/data/internet_users_2005_choropleth_lowres.json'); }); it('should find Switzerland by name', function(done) { GeoFeature.findOne({'properties.name': 'Switzerland'}, function(err, result) { if (err) throw err; assert(result); assert.deepEqual(result.bbox.toObject(), [ 5.970000000000001,45.839999999999996, 10.47,47.71 ]); done(); }); }); it('should find countries within a box', function(done) { GeoFeature.geoWithin(coordinates.polygonFromBbox([1,40,11,48])).sort({'properties.name': 1}).exec(function(err, result) { if (err) throw err; assert(result.length); var countries = result.map(function(val) { return val.properties.name; }); assert.deepEqual(countries, [ 'Andorra', 'Liechtenstein', 'Monaco', 'Switzerland' ]); done(); }); }); it('should find countries intersecting a box', function(done) { GeoFeature.geoIntersects(coordinates.polygonFromBbox([1,40,11,48])).sort({'properties.name': 1}).exec(function(err, result) { if (err) throw err; assert(result.length); var countries = result.map(function(val) { return val.properties.name; }); assert.deepEqual(countries, [ 'Andorra', 'Austria', 'France', 'Germany', 'Italy', 'Liechtenstein', 'Monaco', 'Spain', 'Switzerland' ]); done(); }); }); after(function() { mongoose.disconnect(); }); });
{ "content_hash": "df541b8fbc0a62d467b720d3c7111ba0", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 127, "avg_line_length": 23.778761061946902, "alnum_prop": 0.6471901749162635, "repo_name": "Safecast/GeoSense", "id": "d46c8b09c5bffe881061edb7e372efc4682d30d1", "size": "2687", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/import-geojson-raw.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14012" }, { "name": "CSS", "bytes": "472840" }, { "name": "HTML", "bytes": "66872150" }, { "name": "JavaScript", "bytes": "11801690" }, { "name": "Python", "bytes": "371952" }, { "name": "Shell", "bytes": "13403" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <title> Navajo (NAV) price, charts, and info | Crypto-Currency Market Capitalizations </title> <meta name="description" content="Crypto-currency market cap rankings, charts, and more"> <meta name="google-site-verification" content="EDc1reqlQ-zAgeRrrgAxRXNK-Zs9JgpE9a0wdaoSO9A" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta property="og:image" content="http://coinmarketcap.com/static/img/CoinMarketCap.png" /> <link rel="stylesheet" href="/static/css/normalize.css?v=20131227"> <link rel="stylesheet" href="/static/css/main.css?v=20140406"> <link rel="stylesheet" href="/static/css/bootstrap3.min.css"> <link rel="stylesheet" href="/static/css/style.css?v=20140804"> <link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'> <script type='text/javascript'> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script type='text/javascript'> googletag.cmd.push(function() { googletag.defineSlot('/48901027/landing_leaderboard_bottom', [728, 90], 'div-gpt-ad-1404794882900-0').addService(googletag.pubads()); googletag.defineSlot('/48901027/landing_leaderboard_top', [728, 90], 'div-gpt-ad-1404794882900-1').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <div class="container"> <div class="row"> <div class="col-xs-6"> <div id="global-stats" class="small"></div> </div> <div class="col-xs-6 text-right"> <a href="https://twitter.com/CoinMKTCap" class="twitter-follow-button" data-show-count="false">Follow @CoinMKTCap</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> </div> </div> <div class="row"> <div class="col-xs-12"> <div id="title"><a href="/">Crypto-Currency Market Capitalizations</a></div> </div> </div> <hr/> <div id="leaderboard" class="text-center"> <!-- landing_leaderboard_top --> <div id='div-gpt-ad-1404794882900-1' style='width:728px; height:90px;margin: 0 auto;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1404794882900-1'); }); </script> </div> </div> <nav id="nav-main" class="navbar navbar-default hidden-xs" role="navigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Currencies <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="/">Top 100</a></li> <li><a href="/currencies/views/all/">Full List</a></li> <li class="divider"></li> <li><a href="/">Market Cap by Available Supply</a></li> <li><a href="/currencies/views/market-cap-by-total-supply/">Market Cap by Total Supply</a></li> <li><a href="/currencies/views/filter-non-mineable/">Filter Non-Mineable</a></li> <li><a href="/currencies/views/filter-premined/">Filter Premined</a></li> <li><a href="/currencies/views/filter-non-mineable-and-premined/">Filter Non-Mineable and Premined</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Markets <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="/currencies/volume/24-hour/">24 Hour Volume Rankings (Currency)</a></li> <li><a href="/exchanges/volume/24-hour/">24 Hour Volume Rankings (Exchange)</a></li> </ul> </li> </ul> <form action="/currencies/search/" class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" id="quick-search-box" class="form-control js-quick-search" placeholder="Search Currencies" name="q"> </div> <button class="btn btn-primary" type="submit"><i class="glyphicon glyphicon-search"></i></button> </form> </nav> <div class="row bottom-margin-1x"> <div class="col-xs-4"> <h1 class="text-large"><img src="/static/img/coins/16x16/navajo.png" class="currency-logo" alt="Navajo"> Navajo <small class="bold">(NAV)</small></h1> </div> <div class="col-xs-8"> <div> <span class="text-large">$ 0.002384</span> <span class="text-large positive_change ">(24.99 %)</span> <br/> <small class="text-gray">0.00000400 BTC</small> <small class=" positive_change "> (22.90 %)</small> </div> </div> </div> <div class="row bottom-margin-2x"> <div class="col-xs-4"> <ul class="list-unstyled"> <li><span class="glyphicon glyphicon-link text-gray" title="Website"></span> <a href="https://bitcointalk.org/index.php?topic=679791.0">https://bitcointalk.org/index.php?t...</a></li> <li><span class="glyphicon glyphicon-search text-gray" title="Explorer"></span> <a href="http://cryptexplorer.com/chain/NavajoCoin/">http://cryptexplorer.com/chain/Nava...</a></li> </ul> </div> <div class="col-xs-8"> <table class="table"> <tr> <th>Market Cap</th> <th>Volume (24h)</th> <th>Available Supply</th> </tr> <tr> <td><small>$ 135,934</small> <br/> <small class="text-gray">228 BTC</small> </td> <td><small>$ 1,769</small><br/> <small class="text-gray">3 BTC</small></td> <td class="td-top"><small>57,023,491 NAV</small></td> </tr> </table> </div> </div> <div class="row bottom-margin-1x"> <div class="col-xs-12"> <ul class="nav nav-tabs text-left" role="tablist"> <li><a href="#charts" role="tab" data-toggle="tab"> <span class="glyphicon glyphicon-stats text-gray"></span> Charts </a></li> <li><a href="#markets" role="tab" data-toggle="tab"><span class="glyphicon glyphicon-transfer text-gray"></span> Markets </a></li> </ul> </div> <div class="col-xs-12 tab-content"> <div id="charts" class="tab-pane"> <div class="tab-header"> <h2 class="pull-left">Navajo Charts</h2> <ul class="nav nav-pills pull-right"> <li class="pointer"><a data-timespan-days="7" data-toggle="pill">7 Day</a></li> <li class="pointer"><a data-timespan-days="30" data-toggle="pill">30 Day</a></li> <li class="pointer"><a data-timespan-days="90" data-toggle="pill">90 Day</a></li> <li class="pointer"><a data-timespan-days="180" data-toggle="pill">180 Day</a></li> <li class="pointer"><a data-timespan-days="365" data-toggle="pill">365 Day</a></li> </ul> <div class="clear"></div> </div> <div id="long-term-graph" style="width:1225px;height:300px"></div> <div id="volume-graph" style="width:1225px;height:100px"></div> </div> <div id="markets" class="tab-pane"> <div class="tab-header"> <h2 class="text-left">Navajo Markets</h2> <table id="markets" class="table no-border table-condensed"> <tr><th>#</th><th>Source</th><th>Pair</th><th class="text-right">Volume (24h)</th><th class="text-right">Price</th><th class="text-right">Volume (%)</th><th class="text-right">Updated</th></tr> <tr> <td>1</td> <td><a href="/exchanges/bittrex/">Bittrex</a></td><td><a href="https://bittrex.com/Market/Index?MarketName=BTC-NAV">NAV/BTC</a></td> <td class="text-right volume" data-usd="1768.74" data-btc="2.96816">$ 1,769</td><td class="text-right price" data-usd="0.00238381" data-btc="4.00032e-06">$ 0.002384</td> <td class="text-right">99.96 %</td> <td class="text-right " >Recently</td> </tr> <tr> <td>2</td> <td><a href="/exchanges/poloniex/">Poloniex</a></td><td><a href="https://poloniex.com/exchange/btc_nav">NAV/BTC</a></td> <td class="text-right volume" data-usd="0.643868" data-btc="0.00108049">$ 1</td><td class="text-right price" data-usd="0.00244341" data-btc="4.10033e-06">$ 0.002443</td> <td class="text-right">0.04 %</td> <td class="text-right " >Recently</td> </tr> <tr> <td>3</td> <td><a href="/exchanges/bter/">BTER</a></td><td><a href="https://bter.com/trade/nav_btc">NAV/BTC</a></td> <td class="text-right volume" data-usd="?" data-btc="?">$ 0</td><td class="text-right price" data-usd="?" data-btc="?">$ 0</td> <td class="text-right">0.00 %</td> <td class="text-right " >Recently</td> </tr> <tr> <td>4</td> <td><a href="/exchanges/cryptsy/">Cryptsy</a></td><td><a href="https://www.cryptsy.com/markets/view/">NAV/BTC</a></td> <td class="text-right volume" data-usd="?" data-btc="?">$ 0</td><td class="text-right price" data-usd="?" data-btc="?">$ 0</td> <td class="text-right">0.00 %</td> <td class="text-right " >Recently</td> </tr> </table> <div class="clear"></div> </div> </div> </div> </div> <div class="row text-center" id="leaderboard-bottom"> <!-- landing_leaderboard_bottom --> <div id='div-gpt-ad-1404794882900-0' style='width:728px; height:90px;margin: 0 auto;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1404794882900-0'); }); </script> </div> </div> <hr/> <div id="footer" class="row"> <div class="col-xs-4">&copy; 2014 CoinMarketCap | <a href="http://buysellads.com/buy/detail/229736" target="_blank">Advertise</a> | <a href="https://bitcointalk.org/index.php?topic=199685.0" target="_blank">BitcoinTalk</a></div> <div class="col-xs-8 text-right"> Donate BTC: <a class="pointer" data-toggle="modal" data-target="#donate_btc">15gJiApW3G9MN2iTteQwQbq7NundwGWwv6</a> | <a class="pointer" data-toggle="modal" data-target="#donate">Others</a> </div> </div> <!-- Modals --> <div class="modal fade" id="donate_btc" tabindex="-1" role="dialog" aria-labelledby="donate_btc_label" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header text-center"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="donate_btc_label">Donate Bitcoin</h4> </div> <div class="modal-body text-center"> <strong>15gJiApW3G9MN2iTteQwQbq7NundwGWwv6</strong> <br/> <img src="/static/img/qrcodes/donate_bitcoin.png" alt="Donate Bitcoin"><br/> </div> </div> </div> </div> <div class="modal fade" id="donate" tabindex="-1" role="dialog" aria-labelledby="donate_label" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header text-center"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="donate_label">Donate</h4> </div> <div class="modal-body small"> <div class="row"> <div class="col-xs-6 text-left">Donate Bitcoin: 15gJiApW3G9MN2iTteQwQbq7NundwGWwv6</div> <div class="col-xs-6 text-right"><img src="/static/img/qrcodes/donate_btc.png" alt="Donate Bitcoin"></div> </div> <hr/> <div class="row"> <div class="col-xs-6 text-left">Donate Litecoin: LSYpWLTeK53UxFfEKmBoSqVrxmNJYTgDg3</div> <div class="col-xs-6 text-right"><img src="/static/img/qrcodes/donate_ltc.png" alt="Donate Litecoin"></div> </div> <hr/> <div class="row"> <div class="col-xs-6 text-left">Donate Peercoin: PTx4t3qdtP8BwPWDCG1iZ3sC6pAV1yUcLn</div> <div class="col-xs-6 text-right"><img src="/static/img/qrcodes/donate_ppc.png" alt="Donate Peercoin"></div> </div> <hr/> <div class="row"> <div class="col-xs-6 text-left">Donate Dogecoin: DD6AF6YbyF2rFHf45a7uekaPTo6KWAZHkG</div> <div class="col-xs-6 text-right"><img src="/static/img/qrcodes/donate_doge.png" alt="Donate Dogecoin"></div> </div> <hr/> </div> </div> </div> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="/static/js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="/static/js/plugins.js"></script> <script src="/static/js/vendor/bootstrap/bootstrap.min.js"></script> <script> $.ajax({ url: "/static/generated_pages/global/stats.json", type: "GET", dataType: "json", success: function(data) { $("#global-stats").html('<a href="/currencies/views/all/">'+ data.active_crypto_currencies +' Currencies</a> / <a href="/currencies/volume/24-hour/">'+ data.active_markets +' Markets</a>') } }); </script> <script src="/static/js/vendor/typeahead/typeahead.bundle.min.js"></script> <script src="/static/js/vendor/handlebars/handlebars.runtime.min.js"></script> <script src="/static/js/templates/quick_search.compiled.template"></script> <script src="/static/js/quick_search.js?v=20140727"></script> <script src="/static/js/vendor/flot/jquery.flot.min.js"></script> <script src="/static/js/vendor/flot/jquery.flot.time.min.js"></script> <script src="/static/js/vendor/flot/jquery.flot.navigate.min.js"></script> <script src="/static/js/currency_graphs.js"></script> <script> $(document).ready(function() { use_price_btc = true; $(".nav-pills a").click(function() { var timespan = ($(this).data("timespan-days")); fetchDatapoints("navajo", timespan, use_price_btc) }); $(".nav-pills a[data-timespan-days='7']").click() $(function(){ var hash = window.location.hash; if (!hash) { hash="#charts" } $('ul.nav a[href="' + hash + '"]').tab('show'); $('.nav-tabs a').click(function (e) { $(this).tab('show'); var scrollmem = $('body').scrollTop(); window.location.hash = this.hash; $('html,body').scrollTop(scrollmem); }); }); }); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-40475998-1', 'coinmarketcap.com'); ga('send', 'pageview'); </script> </body> </html>
{ "content_hash": "1ff8f0290a645f6731edc75f16d7b0a3", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 315, "avg_line_length": 53.666666666666664, "alnum_prop": 0.5002070393374741, "repo_name": "gogogoutham/coinmarketcap-scraper", "id": "f922fa901ecc2ea8bb9699c9e4fb5fae057ad907", "size": "19320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/currency_navajo.html", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "27090" } ], "symlink_target": "" }
typedef signed char base_type; typedef std::vector<base_type> chromosome_type; typedef std::vector<chromosome_type> genome_type;
{ "content_hash": "33825d44ea68d1bbec20221a47d7ef7d", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 49, "avg_line_length": 32.5, "alnum_prop": 0.7923076923076923, "repo_name": "msmania/loop", "id": "da72dd0eeec53d03a68e5b7753f1ab6c58e8a664", "size": "130", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/bridge.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "90514" }, { "name": "Makefile", "bytes": "2973" } ], "symlink_target": "" }
import { connect } from 'react-redux'; import { fetchOrders, setFilter } from '../actions'; import Filter from './components/fields'; const mapStateToProps = state => { return { isClosed: state.orders.filter.closed, isCancelled: state.orders.filter.cancelled, isDelivered: state.orders.filter.delivered, isPaid: state.orders.filter.paid, isHold: state.orders.filter.hold, isDraft: state.orders.filter.draft }; }; const mapDispatchToProps = dispatch => { return { setCancelled: value => { dispatch(setFilter({ cancelled: value })); dispatch(fetchOrders()); }, setDelivered: value => { dispatch(setFilter({ delivered: value })); dispatch(fetchOrders()); }, setPaid: value => { dispatch(setFilter({ paid: value })); dispatch(fetchOrders()); }, setHold: value => { dispatch(setFilter({ hold: value })); dispatch(fetchOrders()); }, setDraft: value => { dispatch(setFilter({ draft: value })); dispatch(fetchOrders()); }, setClosed: value => { dispatch(setFilter({ closed: value })); dispatch(fetchOrders()); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(Filter);
{ "content_hash": "0dda5a592dd7a08eca8e76dbb1a1c410", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 52, "avg_line_length": 24.208333333333332, "alnum_prop": 0.6703958691910499, "repo_name": "cezerin/cezerin", "id": "dfa4612bd3617e3aa575debaf2c91fd8816e2e08", "size": "1162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/admin/client/modules/orders/listFilter/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "62407" }, { "name": "HTML", "bytes": "6210" }, { "name": "JavaScript", "bytes": "1712641" }, { "name": "Shell", "bytes": "969" } ], "symlink_target": "" }
#include "cell_refine.hpp" #include <viennagrid/algorithm/refine.hpp> //////////////// // Triangular // //////////////// tuple TriangularCartesian2D_Domain_cell_refine(TriangularCartesian2D_Domain domain_in, TriangularCartesian2D_Segmentation segmentation_in, object predicate) { TriangularCartesian2D_Domain domain_out; TriangularCartesian2D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularCartesian2D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularCartesian2D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularCartesian2D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularCartesian2D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularCartesian2D_Domain, TriangularCartesian2D_Segmentation>(domain_out, segmentation_out); } tuple TriangularCartesian3D_Domain_cell_refine(TriangularCartesian3D_Domain domain_in, TriangularCartesian3D_Segmentation segmentation_in, object predicate) { TriangularCartesian3D_Domain domain_out; TriangularCartesian3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularCartesian3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularCartesian3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularCartesian3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularCartesian3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularCartesian3D_Domain, TriangularCartesian3D_Segmentation>(domain_out, segmentation_out); } tuple TriangularCylindrical3D_Domain_cell_refine(TriangularCylindrical3D_Domain domain_in, TriangularCylindrical3D_Segmentation segmentation_in, object predicate) { TriangularCylindrical3D_Domain domain_out; TriangularCylindrical3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularCylindrical3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularCylindrical3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularCylindrical3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularCylindrical3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularCylindrical3D_Domain, TriangularCylindrical3D_Segmentation>(domain_out, segmentation_out); } tuple TriangularPolar2D_Domain_cell_refine(TriangularPolar2D_Domain domain_in, TriangularPolar2D_Segmentation segmentation_in, object predicate) { TriangularPolar2D_Domain domain_out; TriangularPolar2D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularPolar2D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularPolar2D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularPolar2D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularPolar2D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularPolar2D_Domain, TriangularPolar2D_Segmentation>(domain_out, segmentation_out); } tuple TriangularSpherical3D_Domain_cell_refine(TriangularSpherical3D_Domain domain_in, TriangularSpherical3D_Segmentation segmentation_in, object predicate) { TriangularSpherical3D_Domain domain_out; TriangularSpherical3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TriangularSpherical3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TriangularSpherical3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TriangularSpherical3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TriangularSpherical3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TriangularSpherical3D_Domain, TriangularSpherical3D_Segmentation>(domain_out, segmentation_out); } ///////////////// // Tetrahedral // ///////////////// tuple TetrahedralCartesian3D_Domain_cell_refine(TetrahedralCartesian3D_Domain domain_in, TetrahedralCartesian3D_Segmentation segmentation_in, object predicate) { TetrahedralCartesian3D_Domain domain_out; TetrahedralCartesian3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TetrahedralCartesian3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TetrahedralCartesian3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TetrahedralCartesian3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TetrahedralCartesian3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TetrahedralCartesian3D_Domain, TetrahedralCartesian3D_Segmentation>(domain_out, segmentation_out); } tuple TetrahedralCylindrical3D_Domain_cell_refine(TetrahedralCylindrical3D_Domain domain_in, TetrahedralCylindrical3D_Segmentation segmentation_in, object predicate) { TetrahedralCylindrical3D_Domain domain_out; TetrahedralCylindrical3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TetrahedralCylindrical3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TetrahedralCylindrical3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TetrahedralCylindrical3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TetrahedralCylindrical3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TetrahedralCylindrical3D_Domain, TetrahedralCylindrical3D_Segmentation>(domain_out, segmentation_out); } tuple TetrahedralSpherical3D_Domain_cell_refine(TetrahedralSpherical3D_Domain domain_in, TetrahedralSpherical3D_Segmentation segmentation_in, object predicate) { TetrahedralSpherical3D_Domain domain_out; TetrahedralSpherical3D_Segmentation segmentation_out(domain_out); // Vector of marks/flags that indicate which cells should be refined CellRefinementFlagContainerType cell_refinement_flag_container; viennagrid::result_of::field<CellRefinementFlagContainerType, TetrahedralSpherical3D_Cell_t>::type cell_refinement_flag_field(cell_refinement_flag_container); // Marks which edges should be refined TetrahedralSpherical3D_CellRange_t cells = viennagrid::elements(domain_in.get_domain()); for (TetrahedralSpherical3D_CellRange_t::iterator it = cells.begin(); it != cells.end(); ++it) { if (predicate(TetrahedralSpherical3D_Cell(*it))) cell_refinement_flag_field(*it) = true; } // Refine marked edges viennagrid::cell_refine(domain_in.get_domain(), segmentation_in.get_segmentation(), domain_out.get_domain(), segmentation_out.get_segmentation(), cell_refinement_flag_field); // Return refined domain and segmentation as a tuple: (refined_domain, refined_segmentation) return make_tuple<TetrahedralSpherical3D_Domain, TetrahedralSpherical3D_Segmentation>(domain_out, segmentation_out); }
{ "content_hash": "45500adc210693dcaac45980c068eb0e", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 165, "avg_line_length": 45.72924187725632, "alnum_prop": 0.6654298571090235, "repo_name": "jonancm/viennagrid-python", "id": "765a0528ec078efcce9df73cfff534d98abe3617", "size": "12844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/algorithms/cell_refine.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1287098" }, { "name": "Python", "bytes": "434735" }, { "name": "Shell", "bytes": "1916" } ], "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 (version 1.7.0_72) on Sat Nov 22 23:36:39 CET 2014 --> <title>DataFormatManager (MaltParser 1.8.1)</title> <meta name="date" content="2014-11-22"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DataFormatManager (MaltParser 1.8.1)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DataFormatManager.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>MaltParser 1.8.1</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatInstance.html" title="class in org.maltparser.core.io.dataformat"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/maltparser/core/io/dataformat/DataFormatManager.html" target="_top">Frames</a></li> <li><a href="DataFormatManager.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All 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><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&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">org.maltparser.core.io.dataformat</div> <h2 title="Class DataFormatManager" class="title">Class DataFormatManager</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.maltparser.core.io.dataformat.DataFormatManager</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.10">DataFormatManager</a> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#DataFormatManager(java.net.URL,%20java.net.URL)">DataFormatManager</a></strong>(java.net.URL&nbsp;inputFormatUrl, java.net.URL&nbsp;outputFormatUrl)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#getDataFormatSpec(java.lang.String)">getDataFormatSpec</a></strong>(java.lang.String&nbsp;name)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#getInputDataFormatSpec()">getInputDataFormatSpec</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#getOutputDataFormatSpec()">getOutputDataFormatSpec</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a></code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#loadDataFormat(java.net.URL)">loadDataFormat</a></strong>(java.net.URL&nbsp;dataFormatUrl)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#setInputDataFormatSpec(org.maltparser.core.io.dataformat.DataFormatSpecification)">setInputDataFormatSpec</a></strong>(<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;inputDataFormatSpec)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatManager.html#setOutputDataFormatSpec(org.maltparser.core.io.dataformat.DataFormatSpecification)">setOutputDataFormatSpec</a></strong>(<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;outputDataFormatSpec)</code>&nbsp;</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>clone, equals, finalize, 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"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DataFormatManager(java.net.URL, java.net.URL)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DataFormatManager</h4> <pre>public&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.16">DataFormatManager</a>(java.net.URL&nbsp;inputFormatUrl, java.net.URL&nbsp;outputFormatUrl) throws <a href="../../../../../org/maltparser/core/exception/MaltChainedException.html" title="class in org.maltparser.core.exception">MaltChainedException</a></pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../../org/maltparser/core/exception/MaltChainedException.html" title="class in org.maltparser.core.exception">MaltChainedException</a></code></dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="loadDataFormat(java.net.URL)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadDataFormat</h4> <pre>public&nbsp;<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.23">loadDataFormat</a>(java.net.URL&nbsp;dataFormatUrl) throws <a href="../../../../../org/maltparser/core/exception/MaltChainedException.html" title="class in org.maltparser.core.exception">MaltChainedException</a></pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code><a href="../../../../../org/maltparser/core/exception/MaltChainedException.html" title="class in org.maltparser.core.exception">MaltChainedException</a></code></dd></dl> </li> </ul> <a name="getInputDataFormatSpec()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getInputDataFormatSpec</h4> <pre>public&nbsp;<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.42">getInputDataFormatSpec</a>()</pre> </li> </ul> <a name="getOutputDataFormatSpec()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getOutputDataFormatSpec</h4> <pre>public&nbsp;<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.46">getOutputDataFormatSpec</a>()</pre> </li> </ul> <a name="setInputDataFormatSpec(org.maltparser.core.io.dataformat.DataFormatSpecification)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setInputDataFormatSpec</h4> <pre>public&nbsp;void&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.50">setInputDataFormatSpec</a>(<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;inputDataFormatSpec)</pre> </li> </ul> <a name="setOutputDataFormatSpec(org.maltparser.core.io.dataformat.DataFormatSpecification)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setOutputDataFormatSpec</h4> <pre>public&nbsp;void&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.54">setOutputDataFormatSpec</a>(<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;outputDataFormatSpec)</pre> </li> </ul> <a name="getDataFormatSpec(java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getDataFormatSpec</h4> <pre>public&nbsp;<a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat">DataFormatSpecification</a>&nbsp;<a href="../../../../../src-html/org/maltparser/core/io/dataformat/DataFormatManager.html#line.58">getDataFormatSpec</a>(java.lang.String&nbsp;name)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/DataFormatManager.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>MaltParser 1.8.1</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatInstance.html" title="class in org.maltparser.core.io.dataformat"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../org/maltparser/core/io/dataformat/DataFormatSpecification.html" title="class in org.maltparser.core.io.dataformat"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/maltparser/core/io/dataformat/DataFormatManager.html" target="_top">Frames</a></li> <li><a href="DataFormatManager.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All 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><a href="#constructor_summary">Constr</a>&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><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright 2007-2014 Johan Hall, Jens Nilsson and Joakim Nivre.</small></p> </body> </html>
{ "content_hash": "1efec3b198856c6aa2a495def9429a94", "timestamp": "", "source": "github", "line_count": 332, "max_line_length": 447, "avg_line_length": 46.61144578313253, "alnum_prop": 0.6690791599353797, "repo_name": "jerryyeezus/nlp-summarization", "id": "bb991d44c544f95f173cec1db30c00d5deb6d674", "size": "15475", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "maltparser/docs/api/org/maltparser/core/io/dataformat/DataFormatManager.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "10226" }, { "name": "CSS", "bytes": "30720" }, { "name": "E", "bytes": "2831" }, { "name": "Forth", "bytes": "2657" }, { "name": "Java", "bytes": "1774038" }, { "name": "Perl", "bytes": "108222" }, { "name": "Python", "bytes": "98753" }, { "name": "Shell", "bytes": "924" }, { "name": "TeX", "bytes": "7823" }, { "name": "XSLT", "bytes": "11436" } ], "symlink_target": "" }
C -*- Mode: Fortran; -*- C C (C) 2013 by Argonne National Laboratory. C See COPYRIGHT in top-level directory. C program main implicit none include 'mpif.h' include 'addsize.h' include 'iooffset.h' integer ierr, rank, i integer errs external comm_errh_fn, win_errh_fn, file_errh_fn integer comm_errh, win_errh, file_errh integer winbuf(2), winh, wdup, wdsize, sizeofint, id integer fh, status(MPI_STATUS_SIZE) common /ec/ iseen integer iseen(3) save /ec/ iseen(1) = 0 iseen(2) = 0 iseen(3) = 0 ierr = -1 errs = 0 call mtest_init( ierr ) call mpi_type_size( MPI_INTEGER, sizeofint, ierr ) call mpi_comm_create_errhandler( comm_errh_fn, comm_errh, ierr ) if (ierr .ne. MPI_SUCCESS) then call mtestprinterrormsg( "Comm_create_errhandler:", ierr ) errs = errs + 1 endif call mpi_win_create_errhandler( win_errh_fn, win_errh, ierr ) if (ierr .ne. MPI_SUCCESS) then call mtestprinterrormsg( "Win_create_errhandler:", ierr ) errs = errs + 1 endif call mpi_file_create_errhandler( file_errh_fn, file_errh, ierr ) if (ierr .ne. MPI_SUCCESS) then call mtestprinterrormsg( "File_create_errhandler:", ierr ) errs = errs + 1 endif C call mpi_comm_dup( MPI_COMM_WORLD, wdup, ierr ) call mpi_comm_set_errhandler( wdup, comm_errh, ierr ) call mpi_comm_size( wdup, wdsize, ierr ) call mpi_send( id, 1, MPI_INTEGER, wdsize, -37, wdup, ierr ) if (ierr .eq. MPI_SUCCESS) then print *, ' Failed to detect error in use of MPI_SEND' errs = errs + 1 else if (iseen(1) .ne. 1) then errs = errs + 1 print *, ' Failed to increment comm error counter' endif endif asize = 2*sizeofint call mpi_win_create( winbuf, asize, sizeofint, MPI_INFO_NULL $ , wdup, winh, ierr ) if (ierr .ne. MPI_SUCCESS) then call mtestprinterrormsg( "Win_create:", ierr ) errs = errs + 1 endif call mpi_win_set_errhandler( winh, win_errh, ierr ) asize = 0 call mpi_put( winbuf, 1, MPI_INT, wdsize, asize, 1, MPI_INT, winh, $ ierr ) if (ierr .eq. MPI_SUCCESS) then print *, ' Failed to detect error in use of MPI_PUT' errs = errs + 1 else if (iseen(3) .ne. 1) then errs = errs + 1 print *, ' Failed to increment win error counter' endif endif call mpi_file_open( MPI_COMM_SELF, 'ftest', MPI_MODE_CREATE + $ MPI_MODE_RDWR + MPI_MODE_DELETE_ON_CLOSE, MPI_INFO_NULL, fh, $ ierr ) if (ierr .ne. MPI_SUCCESS) then call mtestprinterrormsg( "File_open:", ierr ) errs = errs + 1 endif call mpi_file_set_errhandler( fh, file_errh, ierr ) offset = -100 call mpi_file_read_at( fh, offset, winbuf, 1, MPI_INTEGER, status, $ ierr ) if (ierr .eq. MPI_SUCCESS) then print *, ' Failed to detect error in use of MPI_PUT' errs = errs + 1 else if (iseen(2) .ne. 1) then errs = errs + 1 print *, ' Failed to increment file error counter' endif endif call mpi_comm_free( wdup, ierr ) call mpi_win_free( winh, ierr ) call mpi_file_close( fh, ierr ) call mpi_errhandler_free( win_errh, ierr ) call mpi_errhandler_free( comm_errh, ierr ) call mpi_errhandler_free( file_errh, ierr ) call mtest_finalize( errs ) call mpi_finalize( ierr ) end C subroutine comm_errh_fn( comm, ec ) integer comm, ec common /ec/ iseen integer iseen(3) save /ec/ C iseen(1) = iseen(1) + 1 C end C subroutine win_errh_fn( win, ec ) integer win, ec common /ec/ iseen integer iseen(3) save /ec/ C iseen(3) = iseen(3) + 1 C end subroutine file_errh_fn( fh, ec ) integer fh, ec common /ec/ iseen integer iseen(3) save /ec/ C iseen(2) = iseen(2) + 1 C end
{ "content_hash": "50e67af4963a5121b6cea86191790a6a", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 72, "avg_line_length": 29.843971631205672, "alnum_prop": 0.560361216730038, "repo_name": "syftalent/dist-sys-exercises-1", "id": "26eef2b190925cbe5b89c8a376a623d1246288cb", "size": "4208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lec-6/mpi/mpich-3.1.4/test/mpi/errors/f77/io/uerrhandf.f", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "18527504" }, { "name": "C++", "bytes": "371333" }, { "name": "CSS", "bytes": "2594" }, { "name": "FORTRAN", "bytes": "1807643" }, { "name": "Groff", "bytes": "82714" }, { "name": "HTML", "bytes": "115" }, { "name": "Java", "bytes": "50567" }, { "name": "Makefile", "bytes": "291868" }, { "name": "Objective-C", "bytes": "2350" }, { "name": "PHP", "bytes": "51" }, { "name": "Perl", "bytes": "288111" }, { "name": "Python", "bytes": "2429" }, { "name": "Ruby", "bytes": "2922" }, { "name": "Shell", "bytes": "169588" }, { "name": "TeX", "bytes": "262609" }, { "name": "XSLT", "bytes": "3178" } ], "symlink_target": "" }
/** * tests/api/v1/subjects/postChild.js */ 'use strict'; const supertest = require('supertest'); const api = supertest(require('../../../../express').app); const constants = require('../../../../api/v1/constants'); const tu = require('../../../testUtils'); const u = require('./utils'); const Subject = tu.db.Subject; const path = '/v1/subjects/{key}/child'; const expect = require('chai').expect; const featureToggles = require('feature-toggles'); describe(`tests/api/v1/subjects/postChild.js, POST ${path} >`, () => { let token; const n0 = { name: `${tu.namePrefix}NorthAmerica` }; const n1 = { name: `${tu.namePrefix}Canada` }; let i0 = 0; before((done) => { tu.createToken() .then((returnedToken) => { token = returnedToken; done(); }) .catch(done); }); beforeEach('create parent', (done) => { Subject.create(n0) .then((o) => { i0 = o.id; done(); }) .catch(done); }); beforeEach(u.populateRedis); afterEach(u.forceDelete); after(tu.forceDeleteUser); it('posting child to parent_absolute_path/child url returns ' + 'expected parentAbsolutePath value', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: 'USA' }) .expect(constants.httpStatus.CREATED) .expect((res) => { if (res.body.parentId !== i0) { throw new Error('wrong parent?'); } }) .end((err, res) => { if (err) { return done(err); } const subject = JSON.parse(res.text); expect(Object.keys(subject)).to.contain('parentAbsolutePath'); expect(subject.parentAbsolutePath).to.equal(n0.name); done(); }); }); it('posting child to parent_id/child url returns' + 'expected parentAbsolutePath value', (done) => { api.post(path.replace('{key}', i0)) .set('Authorization', token) .send(n1) .expect(constants.httpStatus.CREATED) .expect((res) => { if (res.body.parentId !== i0) { throw new Error('wrong parent?'); } }) .end((err, res) => { if (err) { return done(err); } const subject = JSON.parse(res.text); expect(Object.keys(subject)).to.contain('parentAbsolutePath'); expect(subject.parentAbsolutePath).to.equal(n0.name); done(); }); }); it('post child with parent id in url', (done) => { api.post(path.replace('{key}', i0)) .set('Authorization', token) .send(n1) .expect(constants.httpStatus.CREATED) .expect((res) => { if (res.body.parentId !== i0) { throw new Error('wrong parent?'); } }) .end(done); }); it('post child with parent name in url', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send(n1) .expect(constants.httpStatus.CREATED) .expect((res) => { if (res.body.parentId !== i0) { throw new Error('wrong parent?'); } }) .end(done); }); it('post child with published true while parent is unpublished', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: 'test', isPublished: true }) .expect(constants.httpStatus.BAD_REQUEST) .end((err, res) => { if (err) { return done(err); } expect(res.body.errors[0].message).to .equal('You cannot insert a subject with isPublished = true ' + 'unless all its ancestors are also published.'); done(); }); }); it('posting child with hierarchy level field should fail', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: 'test', hierarchyLevel: -1 }) .expect(constants.httpStatus.BAD_REQUEST) .end((err, res) => { if (err) { return done(err); } expect(res.body.errors[0].description) .to.contain('You cannot modify the read-only field'); return done(); }); }); describe('validate helpEmail/helpUrl required >', () => { const toggleOrigValue = featureToggles.isFeatureEnabled( 'requireHelpEmailOrHelpUrl' ); before(() => tu.toggleOverride('requireHelpEmailOrHelpUrl', true)); after(() => tu.toggleOverride( 'requireHelpEmailOrHelpUrl', toggleOrigValue) ); afterEach(u.forceDelete); it('NOT OK, post subject with no helpEmail or helpUrl', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: `${tu.namePrefix}s1` }) .expect(constants.httpStatus.BAD_REQUEST) .expect((res) => { expect(res.body.errors[0].type).to.equal('ValidationError'); expect(res.body.errors[0].description).to.equal( 'At least one these attributes are required: helpEmail,helpUrl' ); }) .end(done); }); it('NOT OK, post subject with empty helpEmail or helpUrl', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: `${tu.namePrefix}s1`, helpEmail: '' }) .expect(constants.httpStatus.BAD_REQUEST) .expect((res) => { expect(res.body.errors[0].type).to.equal('ValidationError'); expect(res.body.errors[0].description).to.equal( 'At least one these attributes are required: helpEmail,helpUrl' ); }) .end(done); }); it('OK, post subject with only helpEmail', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: `${tu.namePrefix}s1`, helpEmail: 'abc@xyz.com' }) .expect(constants.httpStatus.CREATED) .expect((res) => { expect(res.body.helpEmail).to.be.equal('abc@xyz.com'); }) .end(done); }); it('OK, post subject with only helpUrl', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: `${tu.namePrefix}s1`, helpUrl: 'http://xyz.com' }) .expect(constants.httpStatus.CREATED) .expect((res) => { expect(res.body.helpUrl).to.be.equal('http://xyz.com'); }) .end(done); }); it('OK, post subject with both helpUrl and helpEmail', (done) => { api.post(path.replace('{key}', `${tu.namePrefix}NorthAmerica`)) .set('Authorization', token) .send({ name: `${tu.namePrefix}s1`, helpUrl: 'http://xyz.com', helpEmail: 'abc@xyz.com', }) .expect(constants.httpStatus.CREATED) .expect((res) => { expect(res.body.helpUrl).to.be.equal('http://xyz.com'); expect(res.body.helpEmail).to.be.equal('abc@xyz.com'); }) .end(done); }); }); });
{ "content_hash": "b5b48fdb9f0f8060cea58b69d94b745e", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 74, "avg_line_length": 29.69396551724138, "alnum_prop": 0.5833938162287705, "repo_name": "salesforce/refocus", "id": "cf5ae003181ee610a0d64e36d118ea96565e001a", "size": "7123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/api/v1/subjects/postChild.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "5777" }, { "name": "Dockerfile", "bytes": "773" }, { "name": "HTML", "bytes": "634084" }, { "name": "JavaScript", "bytes": "3850030" }, { "name": "Procfile", "bytes": "258" }, { "name": "Pug", "bytes": "18553" }, { "name": "SCSS", "bytes": "1110" }, { "name": "Shell", "bytes": "772" } ], "symlink_target": "" }
import {Component, OnInit, Output, EventEmitter, Input, ViewChild, AfterViewInit} from "@angular/core"; import {DomSanitizer} from "@angular/platform-browser"; import {ArrayUtils} from "../../shared/utils/ArrayUtils"; import {AudioPlayerComponent} from "../audio-player/audio-player.component"; import {Subject} from "rxjs"; import {RepeatableTest} from "../base/RepeatableTest"; import {MdRadioButton} from "@angular/material"; import {Sample} from "../base/Sample"; @Component({ selector: 'abx-test-player', templateUrl: './abx-test-player.component.html', styleUrls: ['./abx-test-player.component.scss'] }) export class AbxTestPlayerComponent implements OnInit, RepeatableTest { @Input() private test; @Input() private iteration: number; @Input() private commandEmmiter: Subject<string>; @ViewChild(AudioPlayerComponent) audioPlayer: AudioPlayerComponent; @ViewChild('bRadioButton') bRadioButton: MdRadioButton; @ViewChild('aRadioButton') aRadioButton: MdRadioButton; @Output() private onFinish = new EventEmitter<any>(); private selectedSample: string; private isAplayed = false; private isBplayed = false; private isXplayed = false; private blindSampleKey: string; private samplesKeyMap: any[] = []; private resultGroup: any; private submitted = false; private samples: Sample[] = []; constructor(private domSanitizer: DomSanitizer) { this.resultGroup = { "type": "ABX", "results": [] }; } public clearContext() { this.isAplayed = false; this.isBplayed = false; this.isXplayed = false; this.samplesKeyMap = []; this.selectedSample = null; this.submitted = false; this.aRadioButton.checked = false; this.bRadioButton.checked = false; this.aRadioButton.disabled = true; this.bRadioButton.disabled = true; } ngOnInit() { this.commandEmmiter.subscribe(event => { if (event === 'iteration') { this.audioPlayer.stop(); this.clearContext(); this.initSamplesOrder(); } }); this.aRadioButton.disabled = true; this.bRadioButton.disabled = true; this.initSamplesOrder(); } public initSamplesOrder() { if (Math.random() < 0.5) { this.blindSampleKey = 'A'; } else { this.blindSampleKey = 'B'; } console.log("Samples"); console.log(this.samples); let samplesKeyShuffled = ArrayUtils.shuffle(this.test.samples.map((s) => s.sampleKey)); console.log("Shuffled:"); console.log(samplesKeyShuffled); this.samplesKeyMap = this.test.samples .sort((a, b) => { let lca = a.sampleKey.toLowerCase(), lcb = b.sampleKey.toLowerCase(); return lca > lcb ? 1 : lca < lcb ? -1 : 0; }) .map((sample, index) => { console.log(samplesKeyShuffled[index] + "->" + sample.sampleKey); return { currentSampleKey: samplesKeyShuffled[index], originalSampleKey: sample.sampleKey, }; }).sort((a, b) => { let lca = a.currentSampleKey.toLowerCase(), lcb = b.currentSampleKey.toLowerCase(); return lca > lcb ? 1 : lca < lcb ? -1 : 0; }); console.log(this.samplesKeyMap); console.log("BLIND KEY: " + this.blindSampleKey); this.samples = this.test.samples.map((s) => { return { key: s.sampleKey, url: (this.test.samples as any[]) .find((sample) => sample.sampleKey === this.samplesKeyMap .find((v) => v.currentSampleKey === s.sampleKey).originalSampleKey).blobUrl } }); this.samples.push({ key: 'X', url: (this.test.samples as any[]) .find((sample) => sample.sampleKey === this.samplesKeyMap .find((v) => v.currentSampleKey === this.blindSampleKey).originalSampleKey).blobUrl }); } public onSampleSelectToPlay(sampleKey: string) { this.audioPlayer.play(sampleKey); if (sampleKey === 'A') { this.isAplayed = true; } if (sampleKey === 'B') { this.isBplayed = true; } if (sampleKey === 'X') { sampleKey = this.blindSampleKey; this.isXplayed = true; this.aRadioButton.disabled = false; this.bRadioButton.disabled = false; } } onTestAnswer(sampleKey: string) { if (this.isXplayed) { this.selectedSample = sampleKey; } } public onSubmit() { let result = { abxBlindSampleKey: this.samplesKeyMap.find((v) => v.currentSampleKey === this.blindSampleKey).originalSampleKey, abxResult: this.samplesKeyMap.find((v) => v.currentSampleKey === this.selectedSample).originalSampleKey, iteration: this.iteration }; this.resultGroup.results.push(result); console.log(result); this.submitted = true; this.onFinish.emit(this.resultGroup); } }
{ "content_hash": "e1469143fd75d483b76c25b33e9770cf", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 118, "avg_line_length": 30.343949044585987, "alnum_prop": 0.6442065491183879, "repo_name": "MarcinMilewski/sqap", "id": "1aada5f66009d01f0cde322113bb46bf13aba1dc", "size": "4764", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sqap-ui/src/main/frontend/app/sound-test-player/abx-test-player/abx-test-player.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "CSS", "bytes": "4400" }, { "name": "Groovy", "bytes": "12852" }, { "name": "HTML", "bytes": "87909" }, { "name": "Java", "bytes": "167325" }, { "name": "JavaScript", "bytes": "83811" }, { "name": "PLpgSQL", "bytes": "328" }, { "name": "Python", "bytes": "3282" }, { "name": "Shell", "bytes": "66" }, { "name": "TypeScript", "bytes": "140323" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <head> <title>Etherlynk Docs</title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="favicon.ico"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- Global CSS --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <!-- Plugins CSS --> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css"> <link rel="stylesheet" href="assets/plugins/prism/prism.css"> <link rel="stylesheet" href="assets/plugins/elegant_font/css/style.css"> <!-- Theme CSS --> <link id="theme-style" rel="stylesheet" href="assets/css/styles.css"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[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 class="body-orange"> <div class="page-wrapper"> <!-- ******Header****** --> <header id="header" class="header"> <div class="container"> <div class="branding"> <h1 class="logo"> <a href="index.html"> <span aria-hidden="true" class="icon"><img src="favicon.ico" /></span> <span class="text-highlight">Etherlynk</span> </a> </h1> </div><!--//branding--> <ol class="breadcrumb"> <li><a href="index.html">Home</a></li> <li class="active">Quick Start</li> </ol> </div><!--//container--> </header><!--//header--> <div class="doc-wrapper"> <div class="container"> <div id="doc-header" class="doc-header text-center"> <h1 class="doc-title"><i class="icon fa icon_puzzle_alt"></i> Components</h1> <div class="meta"><i class="fa fa-clock-o"></i> Last updated: June 12th, 2018</div> </div><!--//doc-header--> <div class="doc-body"> <div class="doc-content"> <div class="content-inner"> </div><!--//content-inner--> </div><!--//doc-content--> <div class="doc-sidebar hidden-xs"> <nav id="doc-nav"> <ul id="doc-menu" class="nav doc-menu" data-spy="affix"> </ul><!--//doc-menu--> </nav> </div><!--//doc-sidebar--> </div><!--//doc-body--> </div><!--//container--> </div><!--//doc-wrapper--> </div><!--//page-wrapper--> <footer id="footer" class="footer text-center"> <div class="container"> <!--/* This template is released under the Creative Commons Attribution 3.0 License. Please keep the attribution link below when using for your own project. Thank you for your support. :) If you'd like to use the template without the attribution, you can check out other license options via our website: themes.3rdwavemedia.com */--> <small class="copyright">Designed with <i class="fa fa-heart"></i> by <a href="http://themes.3rdwavemedia.com/" targe="_blank">Xiaoying Riley</a> for developers</small> </div><!--//container--> </footer><!--//footer--> <!-- Main Javascript --> <script type="text/javascript" src="assets/plugins/jquery-1.12.3.min.js"></script> <script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="assets/plugins/prism/prism.js"></script> <script type="text/javascript" src="assets/plugins/jquery-scrollTo/jquery.scrollTo.min.js"></script> <script type="text/javascript" src="assets/plugins/jquery-match-height/jquery.matchHeight-min.js"></script> <script type="text/javascript" src="assets/js/main.js"></script> </body> </html>
{ "content_hash": "07c0c28d4b1877ae334c21abdfe76aa3", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 345, "avg_line_length": 49.191489361702125, "alnum_prop": 0.5503892733564014, "repo_name": "Traderlynk/Etherlynk", "id": "c695fb2c3baa26bf17c27cded82ac152220f3448", "size": "4624", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/components.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1640" }, { "name": "CSS", "bytes": "1375573" }, { "name": "HTML", "bytes": "1283668" }, { "name": "Java", "bytes": "1756839" }, { "name": "JavaScript", "bytes": "28131035" }, { "name": "PHP", "bytes": "27273" } ], "symlink_target": "" }
define({ "addDistance": "Dodaj jedinicu dužine", "addArea": "Dodaj jedinicu površine", "label": "Oznaka", "abbr": "Skraćenica", "conversion": "Konverzija", "actions": "Radnje", "areaUnits": "Jedinice površine", "distanceUnits": "Jedinice dužine", "kilometers": "Kilometri", "miles": "Milje", "meters": "Metri", "feet": "Stope", "yards": "Jardi", "squareKilometers": "Kvadratni kilometri", "squareMiles": "Kvadratne milje", "acres": "Ari", "hectares": "Hektari", "squareMeters": "Kvadratni metri", "squareFeet": "Kvadratne stope", "squareYards": "Kvadratne jarde", "distance": "Rastojanja", "area": "Površine", "kilometersAbbreviation": "km", "milesAbbreviation": "mi", "metersAbbreviation": "m", "feetAbbreviation": "ft", "yardsAbbreviation": "yd", "squareKilometersAbbreviation": "km²", "squareMilesAbbreviation": "mi²", "acresAbbreviation": "a", "hectaresAbbreviation": "ha", "squareMetersAbbreviation": "m²", "squareFeetAbbreviation": "ft²", "squareYardsAbbreviation": "yd²", "defineUnits": "Definišite jedinice mere.", "operationalLayer": "Dodajte crtež kao operativni sloj mape." });
{ "content_hash": "51aef46b6034c782e01554f4b3f4e2fb", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 63, "avg_line_length": 30.526315789473685, "alnum_prop": 0.6681034482758621, "repo_name": "cmccullough2/cmv-wab-widgets", "id": "144f1fa1abfbc190c532761b81aad14174e3304d", "size": "1173", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wab/2.2/widgets/Draw/setting/nls/sr/strings.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1198579" }, { "name": "HTML", "bytes": "946692" }, { "name": "JavaScript", "bytes": "22190423" }, { "name": "Pascal", "bytes": "4207" }, { "name": "TypeScript", "bytes": "102918" } ], "symlink_target": "" }
import ma = require('azure-pipelines-task-lib/mock-answer'); import tmrm = require('azure-pipelines-task-lib/mock-run'); import path = require('path'); let taskPath = path.join(__dirname, '..', 'deployiiswebapp.js'); let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath); tr.setInput('WebSiteName','mytestwebsite'); tr.setInput('VirtualApplication', 'mytestapp'); tr.setInput('Package', 'webAppPkg.zip'); process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"] = "DefaultWorkingDirectory"; // provide answers for task mock let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{ "which": { "msdeploy": "msdeploy" }, "stats": { "webAppPkg.zip": { "isFile": true } }, "checkPath": { "msdeploy": true }, "exec": { "msdeploy -verb:sync -source:package='webAppPkg.zip' -dest:auto -setParam:name='IIS Web Application Name',value='mytestwebsite/mytestapp' -enableRule:DoNotDeleteRule":{ "code": 0, "stdout": "Executed Successfully" }, "msdeploy -verb:getParameters -source:package=\'webAppPkg.zip\'": { "code": 0, "stdout": "Executed Successfully" } }, "exist": { "webAppPkg.zip": true } }; import mockTask = require('azure-pipelines-task-lib/mock-task'); var msDeployUtility = require('webdeployment-common-v2/msdeployutility.js'); tr.registerMock('webdeployment-common-v2/ziputility.js', { getArchivedEntries: function(webDeployPkg) { return { "entries": [ "systemInfo.xml", "parameters.xml" ] }; } }); tr.registerMock('./msdeployutility.js', { getMSDeployCmdArgs : msDeployUtility.getMSDeployCmdArgs, getMSDeployFullPath : function() { var msDeployFullPath = "msdeploypath\\msdeploy.exe"; return msDeployFullPath; } }); var fs = require('fs'); tr.registerMock('fs', { createWriteStream: function (filePath, options) { return { "isWriteStreamObj": true, "on": (event) => { console.log("event: " + event + " has been triggered"); }, "end" : () => { return true; } }; }, ReadStream: fs.ReadStream, WriteStream: fs.WriteStream, openSync: function (fd, options) { return true; }, closeSync: function (fd) { return true; }, fsyncSync: function(fd) { return true; } }); tr.setAnswers(a); tr.run();
{ "content_hash": "f9d8209a1b064c8f5b3eab967c0e6dfd", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 176, "avg_line_length": 28.397727272727273, "alnum_prop": 0.5958383353341337, "repo_name": "dylan-smith/vso-agent-tasks", "id": "ab0f554c3bc6b6b249ddfba60de3ce118f0bcb45", "size": "2499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tasks/IISWebAppDeploymentOnMachineGroupV0/Tests/L0WindowsDefault.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1636" }, { "name": "CSS", "bytes": "3780" }, { "name": "HTML", "bytes": "46009" }, { "name": "Java", "bytes": "1575" }, { "name": "JavaScript", "bytes": "142044" }, { "name": "PowerShell", "bytes": "2502976" }, { "name": "Shell", "bytes": "39518" }, { "name": "TSQL", "bytes": "7822" }, { "name": "TypeScript", "bytes": "7982928" } ], "symlink_target": "" }
extern QList<unsigned> size_now_no; extern QMutex mutex_process; extern QSemaphore bar_list_queen; extern FTPManager *ftpmanager; UploadThread::UploadThread(MainWindow *mainwindow, SOCKET data_sock, QString filename, long long offset) { UploadThread::mainwindow = mainwindow; UploadThread::data_sock = data_sock; UploadThread::filename = filename; UploadThread::offset = offset; connect(this,SIGNAL(fileupload(QString)),mainwindow,SLOT(file_uploaded(QString))); connect(this,SIGNAL(finished()),this,SLOT(deleteLater())); } UploadThread::~UploadThread() { } void UploadThread::run() { QFile file(filename); if(!file.open(QIODevice::ReadOnly)) { qDebug("读取文件失败"); } else { int aaa; char hehe[10]; qDebug("读取文件成功"); file.seek(offset); bar_list_queen.acquire(); char send_content[514]; int size = 0,locate; mutex_process.lock(); size_now_no.push_back(0); locate = size_now_no.size(); mutex_process.unlock(); DUProgressBar *duprogressbar = new DUProgressBar(mainwindow,filename,file.size(),locate-1); duprogressbar->start(); while((size = file.read(send_content,512)) > 0) { aaa = send(data_sock,send_content,size,0); itoa(aaa,hehe,10); qDebug(hehe); mutex_process.lock(); size_now_no[locate-1] += (unsigned)size; mutex_process.unlock(); memset(send_content,0,sizeof(send_content)); } file.close(); closesocket(data_sock); recv(ftpmanager->getcontrolsock(),send_content,195,0); mainwindow->add_log(send_content); memset(send_content,0,sizeof(send_content)); emit fileupload(filename); bar_list_queen.release(); } }
{ "content_hash": "c45b4b864b988bd3575303550c01efbd", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 106, "avg_line_length": 32.625, "alnum_prop": 0.6201423097974822, "repo_name": "chaohu/DUAO", "id": "c9e87b8ed1c4d78b5912f3db7f816da77ed503ca", "size": "1951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FTPClient/uploadthread.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9617" }, { "name": "C++", "bytes": "57022" }, { "name": "Makefile", "bytes": "25967" }, { "name": "QMake", "bytes": "1229" } ], "symlink_target": "" }
package com.sdm.ide.component.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FXColumn { String label() default ""; boolean visible() default true; boolean editable() default false; boolean sortable() default true; double width() default 75.0; }
{ "content_hash": "ac1887fb827c2e53f88b356d9d256e92", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 44, "avg_line_length": 22.80952380952381, "alnum_prop": 0.7620041753653445, "repo_name": "Htoonlin/MasterIDE", "id": "a5f633c713db5a077d49b76126e1f179f81a121a", "size": "479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sdm/ide/component/annotation/FXColumn.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "695" }, { "name": "Java", "bytes": "240571" } ], "symlink_target": "" }
package objectDeregister; import es.bsc.compss.types.annotations.Parameter; import es.bsc.compss.types.annotations.parameter.Type; import es.bsc.compss.types.annotations.parameter.Direction; import es.bsc.compss.types.annotations.task.Method; public interface ObjectDeregisterItf { @Method(declaringClass = "objectDeregister.ObjectDeregisterImpl") void task1(@Parameter(type = Type.INT, direction = Direction.IN) int n, @Parameter(type = Type.OBJECT, direction = Direction.INOUT) Dummy d1); @Method(declaringClass = "objectDeregister.ObjectDeregisterImpl") void task2(@Parameter(type = Type.INT, direction = Direction.IN) int n, @Parameter(type = Type.OBJECT, direction = Direction.INOUT) Dummy d2); @Method(declaringClass = "objectDeregister.ObjectDeregisterImpl") void task3(@Parameter(type = Type.OBJECT, direction = Direction.IN) Dummy d3); @Method(declaringClass = "objectDeregister.ObjectDeregisterImpl") void task4(); }
{ "content_hash": "888b113dbcf024f3c07790d662f369a7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 82, "avg_line_length": 39.32, "alnum_prop": 0.7558494404883012, "repo_name": "mF2C/COMPSs", "id": "fb777e921c47a73256184a2bbbb1d9d2e585dd88", "size": "983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/sources/java/3_object_deregister/src/main/java/objectDeregister/ObjectDeregisterItf.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1595" }, { "name": "C", "bytes": "222477" }, { "name": "C++", "bytes": "200186" }, { "name": "Dockerfile", "bytes": "901" }, { "name": "Gnuplot", "bytes": "4195" }, { "name": "Java", "bytes": "4213323" }, { "name": "JavaScript", "bytes": "16906" }, { "name": "Jupyter Notebook", "bytes": "10514" }, { "name": "Lex", "bytes": "1356" }, { "name": "M4", "bytes": "5538" }, { "name": "Makefile", "bytes": "14740" }, { "name": "Python", "bytes": "635267" }, { "name": "Shell", "bytes": "1241476" }, { "name": "XSLT", "bytes": "177323" }, { "name": "Yacc", "bytes": "3655" } ], "symlink_target": "" }
package com.vijaysharma.ehyo.api.utils; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.Scanner; import com.google.common.base.Function; import com.vijaysharma.ehyo.api.GentleMessageException; import com.vijaysharma.ehyo.api.logging.Output; import com.vijaysharma.ehyo.api.logging.TextOutput; public class OptionSelector<T> { private final Scanner scanner; private final Function<T, String> renderer; private final String header; private final TextOutput out; public OptionSelector(String header, Function<T, String> renderer) { this(header, renderer, System.in, Output.out); } OptionSelector(String header, Function<T, String> renderer, InputStream in, TextOutput out) { this.renderer = renderer; this.header = header; this.scanner = new Scanner(new InputStreamReader(in)); this.out = out; } public T selectOne(List<T> items) { List<T> selection = select(items, false); if ( selection.size() != 1 ) throw new IllegalStateException("Expected only a single result"); return selection.get(0); } public List<T> select(List<T> items, boolean multiselect) { if ( items.size() == 1 ) return items; StringBuilder dialog = new StringBuilder(); int max = items.size() + (multiselect ? 1 : 0); dialog.append(header + "\n"); for ( int index = 0; index < items.size(); index++ ) { T item = items.get(index); dialog.append("[" + (index + 1) + "] " + renderer.apply(item) + "\n"); } if ( multiselect ) dialog.append("[" + max + "] Apply to all\n"); dialog.append("Select: "); out.println(dialog.toString()); int selection = read(1, max); if ( selection < 1 || selection > max ) throw new GentleMessageException("Your selection is out of range!"); if ( multiselect && selection == max ) return items; return Arrays.asList(items.get(selection-1)); } public List<T> select(List<T> items) { return this.select(items, true); } private int read(int min, int max) { String selection = scanner.next(); try { int parseInt = Integer.parseInt(selection); if ( parseInt < min || parseInt > max ) return -1; return parseInt; } catch ( NumberFormatException nfe ) { return -1; } } }
{ "content_hash": "1b73f645f1253f35811e458f4f350712", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 94, "avg_line_length": 26.75294117647059, "alnum_prop": 0.6838170624450308, "repo_name": "vijaysharm/ehyo-android", "id": "51f45362d2aed25b9cacf7106c21e58098738a37", "size": "2274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/vijaysharma/ehyo/api/utils/OptionSelector.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "5685" }, { "name": "Java", "bytes": "341202" }, { "name": "Shell", "bytes": "99" } ], "symlink_target": "" }
"""The Virtual File System (VFS) resolver helper interface.""" from dfvfs.lib import errors class ResolverHelper(object): """Resolver helper interface.""" # pylint: disable=redundant-returns-doc,unused-argument def __init__(self): """Initializes a resolver helper. Raises: ValueError: if a derived resolver helper class does not define a type indicator. """ super(ResolverHelper, self).__init__() if not getattr(self, 'TYPE_INDICATOR', None): raise ValueError('Missing type indicator.') @property def type_indicator(self): """str: type indicator.""" # pylint: disable=no-member return self.TYPE_INDICATOR def NewFileObject(self, resolver_context, path_spec): """Creates a new file input/output (IO) object. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification. Returns: FileIO: file input/output (IO) object. Raises: NotSupported: if there is no implementation to create a file input/output (IO) object. """ raise errors.NotSupported( 'Missing implementation to create file input/output (IO) object.') def NewFileSystem(self, resolver_context, path_spec): """Creates a new file system. Args: resolver_context (Context): resolver context. path_spec (PathSpec): a path specification. Returns: FileSystem: file system. Raises: NotSupported: if there is no implementation to create a file system. """ # pylint: disable=no-member raise errors.NotSupported(( f'Missing implementation to create file system: ' f'{self.TYPE_INDICATOR:s}.'))
{ "content_hash": "65e7f471f4060739aff2885278c24969", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 75, "avg_line_length": 27.306451612903224, "alnum_prop": 0.6645008860011813, "repo_name": "log2timeline/dfvfs", "id": "de5eabf3b7bd74f6dd9ab3d44044d53ab3d65966", "size": "1717", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "dfvfs/resolver_helpers/resolver_helper.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14212" }, { "name": "Makefile", "bytes": "122" }, { "name": "PowerShell", "bytes": "1021" }, { "name": "Python", "bytes": "2176548" }, { "name": "Shell", "bytes": "19355" } ], "symlink_target": "" }
/** * @author Alberto Siena **/ package eu.riscoss.client.riskanalysis; import com.google.gwt.core.client.GWT; import com.google.gwt.json.client.JSONObject; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; public class RiskWidget implements IsWidget { VerticalPanel panel = new VerticalPanel(); Image img; public RiskWidget( JSONObject o ) { if( o.get( "label" ) != null ) panel.add( new Label( o.get( "label" ).isString().stringValue() )); else panel.add( new Label( o.get( "id" ).isString().stringValue() )); img = new Image(); img.setSize( "100px", "50px" ); panel.add( img ); } @Override public Widget asWidget() { return panel; } public void setValue( String p, String m ) { img.setUrl( GWT.getHostPageBaseURL() + "gauge?type=e&p=" + p + "&m=" + m + "&w=100&h=50" ); } }
{ "content_hash": "66da338a092f38ddc5c5cba47e2b37ae", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 93, "avg_line_length": 24.5609756097561, "alnum_prop": 0.6782522343594836, "repo_name": "RISCOSS/riscoss-corporate", "id": "dea213b27733e0fda52455548a00bf611c047bfa", "size": "1624", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "riscoss-webapp/src/main/java/eu/riscoss/client/riskanalysis/RiskWidget.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10534" }, { "name": "Java", "bytes": "1198930" }, { "name": "Python", "bytes": "31028" }, { "name": "TeX", "bytes": "20970" }, { "name": "XSLT", "bytes": "15755" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <!-- [[! Document Settings ]] --> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- [[! Page Meta ]] --> <title>Fountain Pen Highlighters</title> <meta name="description" content="Zian "Zane" Liu - Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." /> <meta name="HandheldFriendly" content="True" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="/assets/images/favicon.ico" > <!-- [[! Styles'n'Scripts ]] --> <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" /> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" /> <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" /> <!-- [[! highlight.js ]] --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css"> <style>.hljs { background: none; }</style> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <!-- [[! Ghost outputs important style and meta data with this tag ]] --> <link rel="canonical" href="/" /> <meta name="referrer" content="origin" /> <link rel="next" href="/page2/" /> <meta property="og:site_name" content="Zian "Zane" Liu" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Zian "Zane" Liu" /> <meta property="og:description" content="Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." /> <meta property="og:url" content="/" /> <meta property="og:image" content="/assets/images/cover1.jpg" /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:title" content="Zian "Zane" Liu" /> <meta name="twitter:description" content="Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." /> <meta name="twitter:url" content="/" /> <meta name="twitter:image:src" content="/assets/images/cover1.jpg" /> <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Website", "publisher": "The Style of a Chairman", "url": "/", "image": "/assets/images/cover1.jpg", "description": "Bioengineer, synthetic biologist, regulatory consultant, STEM outreach organizer, political junkie, menswear enthusiast, fountain pen user, coffee addict, and more..." } </script> <meta name="generator" content="Jekyll 3.0.0" /> <link rel="alternate" type="application/rss+xml" title="Zian "Zane" Liu" href="/feed.xml" /> </head> <body class="home-template nav-closed"> <div class="nav"> <h3 class="nav-title">Menu</h3> <a href="#" class="nav-close"> <span class="hidden">Close</span> </a> <ul> <li class="nav-home " role="presentation"><a href="/">Home</a></li> <li class="nav-about " role="presentation"><a href="/about">About Zian</a></li> <li class="nav-about " role="presentation"><a href="/resume">Resume</a></li> <li class="nav-projects " role="presentation"><a href="/tag/projects">Projects</a></li> <li class="nav-leadership " role="presentation"><a href="/tag/leadership">Leadership</a></li> <li class="nav-style " role="presentation"><a href="/tag/style">Menswear Advice</a></li> <li class="nav-interests " role="presentation"><a href="/tag/interests">Interests</a></li> <li class="nav-author " role="presentation"><a href="/author/zian">Contact Me</a></li> </ul> <center> <a href="https://twitter.com/chairmanzian" class="twitter-follow-button" data-show-count="false">Follow @chairmanzian</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> </center> </div> <span class="nav-cover"></span> <div class="site-wrapper"> <!-- [[! Everything else gets inserted here ]] --> <!-- < default --> <!-- The comment above "< default" means - insert everything in this file into --> <!-- the [body] of the default.hbs template, which contains our header/footer. --> <!-- Everything inside the #post tags pulls data from the post --> <!-- #post --> <header class="main-header post-head " style="background-image: url(/assets/images/fphighlighter.jpg) "> <nav class="main-nav overlay clearfix"> <a class="menu-button icon-menu" href="#"><span class="word">Menu</span></a> </nav> </header> <main class="content" role="main"> <article class="post tag-interests"> <header class="post-header"> <h1 class="post-title">Fountain Pen Highlighters</h1> <section class="post-meta"> <!-- <a href='/'>Zian Liu</a> --> <time class="post-date" datetime="2016-11-05">05 Nov 2016</time> <!-- [[tags prefix=" on "]] --> on <a href='/tag/interests'>Interests</a>, <a href='/tag/fountainpen'>Fountainpen</a> </section> </header> <section class="post-content"> <p>Recently I bought myself some <a href="http://www.gouletpens.com/platinum-preppy-highlighters/c/288">Platinum Preppy highlighters</a>. Instead of using the free ink cartridges that came with the pen, I eyedroppered them with the matching <a href="http://www.gouletpens.com/bottled-ink/c/14/?sortBy=productName%2Basc&amp;facetValueFilter=Tenant~Brand%3Anoodlers%2CTenant~Ink_Color%3Ahighlighter">highlighter inks from Noodlers</a>.</p> <p>Pretty much, these pens are a hybrid of markers and fountain pens, since it sports the latter’s capillary action ink mechanism and the former’s easy-to-use tip. Filled with water-based yet fluorescent ink, it works quite well, easily drawing emphasis on written documents upon every streak.</p> <p>The drawback of these highlighters, however, is that it’s quite “wet,” and that the ink can sometimes take awhile to dry atop the page. These properties, desired by users of fountain pens, might not be as useful for highlighters. I’ve had many instances where a too-slow stream with the highlighter not only bled through the back of a page, but stayed on the page long enough to stain the back of the previous page too.</p> <p>Overall, I’m satisfied with the Platinum Preppy highlighter. Fountain pen fans should consider getting one to complete their entire fountain pen experience!</p> </section> <footer class="post-footer"> <!-- Everything inside the #author tags pulls data from the author --> <!-- #author--> <figure class="author-image"> <a class="img" href="/author/zian" style="background-image: url(/assets/images/zian.png)"><span class="hidden">'s Picture</span></a> </figure> <section class="author"> <h4><a href="/author/zian">Zian Liu</a></h4> <p> Bioengineer, synthetic biologist, and medical device regulatory professional. Constantly caffeinated. Owner of way too many navy suits.</p> <div class="author-meta"> <span class="author-location icon-location"> Silicon Valley</span> <span class="author-link icon-link"><a href="mailto:zane@chairmanzian.com"> zane@chairmanzian.com</a></span> </div> </section> <!-- /author --> <section class="share"> <h4>Share this post</h4> <a class="icon-twitter" href="http://twitter.com/share?text=Fountain Pen Highlighters&amp;url=mailto:zane@chairmanzian.comfp-highlighter" onclick="window.open(this.href, 'twitter-share', 'width=550,height=235');return false;"> <span class="hidden">Twitter</span> </a> <a class="icon-facebook" href="https://www.facebook.com/sharer/sharer.php?u=mailto:zane@chairmanzian.comfp-highlighter" onclick="window.open(this.href, 'facebook-share','width=580,height=296');return false;"> <span class="hidden">Facebook</span> </a> <a class="icon-google-plus" href="https://plus.google.com/share?url=mailto:zane@chairmanzian.comfp-highlighter" onclick="window.open(this.href, 'google-plus-share', 'width=490,height=530');return false;"> <span class="hidden">Google+</span> </a> </section> <!-- Add Disqus Comments --> </footer> </article> </main> <aside class="read-next"> <!-- [[! next_post ]] --> <a class="read-next-story " style="background-image: url(/assets/images/blue_3.jpg)" href="/toomuchblue"> <section class="post"> <h2>Is There Such a Thing As Too Much Blue?</h2> <p>I love the color blue - it's probably my favorite - and I wear it...</p> </section> </a> <!-- [[! /next_post ]] --> <!-- [[! prev_post ]] --> <a class="read-next-story prev " style="background-image: url(/assets/images/frankenpen.jpg)" href="/fountain-pen-day"> <section class="post"> <h2>Happy Fountain Pen Day!</h2> <p>A photo posted by Zian Liu (@chairmanzian) on Nov 4, 2016 at 3:30pm PDT It’s...</p> </section> </a> <!-- [[! /prev_post ]] --> </aside> <!-- /post --> <footer class="site-footer clearfix"> <section class="copyright"><a href="/">Zian "Zane" Liu</a> &copy; 2018</section> <section class="poweredby">Proudly published with <a href="https://jekyllrb.com/">Jekyll</a> using <a href="https://github.com/biomadeira/jasper">Jasper</a></section> </footer> </div> <!-- [[! Ghost outputs important scripts and data with this tag ]] --> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <!-- [[! The main JavaScript file for Casper ]] --> <script type="text/javascript" src="/assets/js/jquery.fitvids.js"></script> <script type="text/javascript" src="/assets/js/index.js"></script> <!-- Add Google Analytics --> <!-- Google Analytics Tracking code --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '', 'auto'); ga('send', 'pageview'); </script> </body> </html>
{ "content_hash": "7b58e8384efae00d819a7c26146c4d0f", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 449, "avg_line_length": 46.1566265060241, "alnum_prop": 0.6030627338379884, "repo_name": "zianliu/zianliu.github.io", "id": "b013746ff12ee6f9617ca5957733acf289f8957b", "size": "11509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fp-highlighter.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46727" }, { "name": "HTML", "bytes": "855466" }, { "name": "JavaScript", "bytes": "4424" } ], "symlink_target": "" }
/* tslint:disable */ // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: SitePageQuery // ==================================================== export interface SitePageQuery_me { __typename: "User"; /** * Id */ id: number; } export interface SitePageQuery { /** * Current logged in user */ me: SitePageQuery_me | null; }
{ "content_hash": "44c204ca3911a644099e38a39047d8ea", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 66, "avg_line_length": 21.19047619047619, "alnum_prop": 0.4943820224719101, "repo_name": "clinwiki-org/cw-app", "id": "32910ec598981efbe59ce010712fdc166fc63b36", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "front/app/types/SitePageQuery.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "154" }, { "name": "HTML", "bytes": "12630" }, { "name": "JavaScript", "bytes": "43587" }, { "name": "Shell", "bytes": "636" }, { "name": "TypeScript", "bytes": "446325" } ], "symlink_target": "" }
import {Injectable} from '@angular/core'; import {Body} from '../body/body.service'; import {Engine} from '../engine/engine.service'; import {Tires} from '../tires/tires.service'; @Injectable() export class Car{ constructor(public body: Body, public engine: Engine, public tires: Tires){ } }
{ "content_hash": "001b27dc065d824cee1f01aef8ab1f4f", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 79, "avg_line_length": 27.363636363636363, "alnum_prop": 0.6976744186046512, "repo_name": "oshry/ng2", "id": "0e789f71d66bf4cf431108b1718a0baa25a54e95", "size": "301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/services/car/car.service.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2347" }, { "name": "HTML", "bytes": "733" }, { "name": "JavaScript", "bytes": "13516" }, { "name": "TypeScript", "bytes": "9406" } ], "symlink_target": "" }
require 'fpm/cookery/path' module FPM module Cookery module PathHelper attr_accessor :installing, :omnibus_installing def installing? installing end def omnibus_installing? omnibus_installing end # Most of the path helper stuff comes from brew2deb and homebrew. def prefix(path = nil) current_pathname_for(default_prefix || '/usr')/path end def etc(path = nil) current_pathname_for('etc')/path end def opt(path = nil) current_pathname_for('opt')/path end def var(path = nil) current_pathname_for('var')/path end def root(path = nil) current_pathname_for(nil)/path end alias_method :root_prefix, :root def bin(path = nil) prefix/'bin'/path end def doc(path = nil) prefix/'share/doc'/path end def include(path = nil) prefix/'include'/path end def info(path = nil) prefix/'share/info'/path end def lib(path = nil) prefix/'lib'/path end def libexec(path = nil) prefix/'libexec'/path end def man(path = nil) prefix/'share/man'/path end def man1(path = nil) man/'man1'/path end def man2(path = nil) man/'man2'/path end def man3(path = nil) man/'man3'/path end def man4(path = nil) man/'man4'/path end def man5(path = nil) man/'man5'/path end def man6(path = nil) man/'man6'/path end def man7(path = nil) man/'man7'/path end def man8(path = nil) man/'man8'/path end def sbin(path = nil) prefix/'sbin'/path end def share(path = nil) prefix/'share'/path end # Return real paths for the scope of the given block. # # prefix('usr') # => /../software/tmp-dest/usr # # with_trueprefix do # prefix('usr') # => /usr # end def with_trueprefix old_value = installing self.installing = false yield ensure self.installing = old_value end private def current_pathname_for(dir) dir.gsub!(%r{^/}, '') if dir if omnibus_installing? Path.new("/#{dir}") else installing? ? destdir/dir : Path.new("/#{dir}") end end end end end
{ "content_hash": "f38a87983267e6198bc7864b25675917", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 71, "avg_line_length": 29.771084337349397, "alnum_prop": 0.5252934034803723, "repo_name": "ryansch/fpm-cookery", "id": "ccba3af05cd8cd4b18211fb43e943574ad275b17", "size": "2471", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "lib/fpm/cookery/path_helper.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "126862" }, { "name": "Shell", "bytes": "2370" } ], "symlink_target": "" }
<?php namespace Tmdb\Model\Common; use Tmdb\Model\Filter\LanguageFilter; /** * Class Translation * @package Tmdb\Model\Common */ class Translation extends SpokenLanguage implements LanguageFilter { private $englishName; public static $properties = array( 'iso_639_1', 'name', 'english_name' ); /** * @param string $englishName * @return $this */ public function setEnglishName($englishName) { $this->englishName = $englishName; return $this; } /** * @return string */ public function getEnglishName() { return $this->englishName; } }
{ "content_hash": "abdcf4cef05b640be32190bc1e66c9c2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 66, "avg_line_length": 16.974358974358974, "alnum_prop": 0.5936555891238671, "repo_name": "gaea/infopelis", "id": "bcc513b04f893f2f15ff57b2a1ccc7f2031a25d2", "size": "995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/wtfzdotnet/php-tmdb-api/lib/Tmdb/Model/Common/Translation.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1232" }, { "name": "JavaScript", "bytes": "2555" }, { "name": "PHP", "bytes": "47053" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pt"> <head> <!-- Generated by javadoc (1.8.0_92) on Sat Sep 08 22:43:00 BRT 2018 --> <title>Uses of Class org.epctagcoder.result.CPI</title> <meta name="date" content="2018-09-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="Uses of Class org.epctagcoder.result.CPI"; } } 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><a href="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">Class</a></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-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/epctagcoder/result/class-use/CPI.html" target="_top">Frames</a></li> <li><a href="CPI.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"> <h2 title="Uses of Class org.epctagcoder.result.CPI" class="title">Uses of Class<br>org.epctagcoder.result.CPI</h2> </div> <div class="classUseContainer"> <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="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">CPI</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="#org.epctagcoder.parse.CPI">org.epctagcoder.parse.CPI</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.epctagcoder.parse.CPI"> <!-- --> </a> <h3>Uses of <a href="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">CPI</a> in <a href="../../../../org/epctagcoder/parse/CPI/package-summary.html">org.epctagcoder.parse.CPI</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/epctagcoder/parse/CPI/package-summary.html">org.epctagcoder.parse.CPI</a> that return <a href="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">CPI</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">CPI</a></code></td> <td class="colLast"><span class="typeNameLabel">ParseCPI.</span><code><span class="memberNameLink"><a href="../../../../org/epctagcoder/parse/CPI/ParseCPI.html#getCPI--">getCPI</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/epctagcoder/result/CPI.html" title="class in org.epctagcoder.result">Class</a></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-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/epctagcoder/result/class-use/CPI.html" target="_top">Frames</a></li> <li><a href="CPI.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 ======= --> </body> </html>
{ "content_hash": "4a4d0777d454f25feced9f80ccbd23f8", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 289, "avg_line_length": 38.46951219512195, "alnum_prop": 0.6130924076715802, "repo_name": "jlcout/epctagcoder", "id": "6df872beec4e6363dc8c60d4940d7cb170fe0dd9", "size": "6309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "epctagcoder/doc/org/epctagcoder/result/class-use/CPI.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "174528" } ], "symlink_target": "" }
'' Copyright (c) 2013, Kcchouette and b-dauphin on Github '' 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 the <ORGANIZATION> 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. <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class FrmInscripRens Inherits System.Windows.Forms.Form 'Form remplace la méthode Dispose pour nettoyer la liste des composants. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Requise par le Concepteur Windows Form Private components As System.ComponentModel.IContainer 'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form 'Elle peut être modifiée à l'aide du Concepteur Windows Form. 'Ne la modifiez pas à l'aide de l'éditeur de code. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.lblNom = New System.Windows.Forms.Label() Me.lblPre = New System.Windows.Forms.Label() Me.lblAdr = New System.Windows.Forms.Label() Me.lblCP = New System.Windows.Forms.Label() Me.lblVille = New System.Windows.Forms.Label() Me.lblAge = New System.Windows.Forms.Label() Me.txtNom = New System.Windows.Forms.TextBox() Me.txtPre = New System.Windows.Forms.TextBox() Me.txtAdr = New System.Windows.Forms.TextBox() Me.txtVille = New System.Windows.Forms.TextBox() Me.txtCP = New System.Windows.Forms.TextBox() Me.btnSuiv = New System.Windows.Forms.Button() Me.btnAband = New System.Windows.Forms.Button() Me.hscAge = New System.Windows.Forms.HScrollBar() Me.txtAge = New System.Windows.Forms.TextBox() Me.tmrReste = New System.Windows.Forms.Timer(Me.components) Me.LblNum = New System.Windows.Forms.Label() Me.LblLibelléNum = New System.Windows.Forms.Label() Me.SuspendLayout() ' 'lblNom ' Me.lblNom.AutoSize = True Me.lblNom.Location = New System.Drawing.Point(12, 9) Me.lblNom.Name = "lblNom" Me.lblNom.Size = New System.Drawing.Size(42, 13) Me.lblNom.TabIndex = 0 Me.lblNom.Text = "* Nom :" ' 'lblPre ' Me.lblPre.AutoSize = True Me.lblPre.Location = New System.Drawing.Point(12, 35) Me.lblPre.Name = "lblPre" Me.lblPre.Size = New System.Drawing.Size(56, 13) Me.lblPre.TabIndex = 1 Me.lblPre.Text = "* Prénom :" ' 'lblAdr ' Me.lblAdr.AutoSize = True Me.lblAdr.Location = New System.Drawing.Point(12, 61) Me.lblAdr.Name = "lblAdr" Me.lblAdr.Size = New System.Drawing.Size(69, 13) Me.lblAdr.TabIndex = 2 Me.lblAdr.Text = "Adresse rue :" ' 'lblCP ' Me.lblCP.AutoSize = True Me.lblCP.Location = New System.Drawing.Point(12, 87) Me.lblCP.Name = "lblCP" Me.lblCP.Size = New System.Drawing.Size(76, 13) Me.lblCP.TabIndex = 3 Me.lblCP.Text = "* Code postal :" ' 'lblVille ' Me.lblVille.AutoSize = True Me.lblVille.Location = New System.Drawing.Point(12, 113) Me.lblVille.Name = "lblVille" Me.lblVille.Size = New System.Drawing.Size(39, 13) Me.lblVille.TabIndex = 4 Me.lblVille.Text = "* Ville :" ' 'lblAge ' Me.lblAge.AutoSize = True Me.lblAge.Location = New System.Drawing.Point(12, 139) Me.lblAge.Name = "lblAge" Me.lblAge.Size = New System.Drawing.Size(39, 13) Me.lblAge.TabIndex = 5 Me.lblAge.Text = "* Âge :" ' 'txtNom ' Me.txtNom.Location = New System.Drawing.Point(104, 6) Me.txtNom.MaxLength = 15 Me.txtNom.Name = "txtNom" Me.txtNom.Size = New System.Drawing.Size(137, 20) Me.txtNom.TabIndex = 6 Me.txtNom.Tag = "" ' 'txtPre ' Me.txtPre.Location = New System.Drawing.Point(104, 32) Me.txtPre.MaxLength = 10 Me.txtPre.Name = "txtPre" Me.txtPre.Size = New System.Drawing.Size(137, 20) Me.txtPre.TabIndex = 7 Me.txtPre.Tag = "" ' 'txtAdr ' Me.txtAdr.Location = New System.Drawing.Point(104, 58) Me.txtAdr.MaxLength = 20 Me.txtAdr.Name = "txtAdr" Me.txtAdr.Size = New System.Drawing.Size(137, 20) Me.txtAdr.TabIndex = 8 Me.txtAdr.Tag = "" ' 'txtVille ' Me.txtVille.Location = New System.Drawing.Point(104, 110) Me.txtVille.MaxLength = 15 Me.txtVille.Name = "txtVille" Me.txtVille.Size = New System.Drawing.Size(137, 20) Me.txtVille.TabIndex = 10 Me.txtVille.Tag = "" ' 'txtCP ' Me.txtCP.Location = New System.Drawing.Point(104, 84) Me.txtCP.MaxLength = 5 Me.txtCP.Name = "txtCP" Me.txtCP.Size = New System.Drawing.Size(137, 20) Me.txtCP.TabIndex = 9 Me.txtCP.Tag = "" ' 'btnSuiv ' Me.btnSuiv.Location = New System.Drawing.Point(153, 195) Me.btnSuiv.Name = "btnSuiv" Me.btnSuiv.Size = New System.Drawing.Size(89, 23) Me.btnSuiv.TabIndex = 12 Me.btnSuiv.Text = "Suivant ->" Me.btnSuiv.UseVisualStyleBackColor = True ' 'btnAband ' Me.btnAband.Location = New System.Drawing.Point(12, 195) Me.btnAband.Name = "btnAband" Me.btnAband.Size = New System.Drawing.Size(135, 23) Me.btnAband.TabIndex = 13 Me.btnAband.Text = "Abandonner l'inscription" Me.btnAband.UseVisualStyleBackColor = True ' 'hscAge ' Me.hscAge.Location = New System.Drawing.Point(104, 138) Me.hscAge.Name = "hscAge" Me.hscAge.Size = New System.Drawing.Size(100, 17) Me.hscAge.TabIndex = 14 ' 'txtAge ' Me.txtAge.Enabled = False Me.txtAge.Location = New System.Drawing.Point(208, 138) Me.txtAge.Name = "txtAge" Me.txtAge.Size = New System.Drawing.Size(33, 20) Me.txtAge.TabIndex = 15 Me.txtAge.Tag = "" ' 'tmrReste ' Me.tmrReste.Interval = 1000 ' 'LblNum ' Me.LblNum.AutoSize = True Me.LblNum.Location = New System.Drawing.Point(101, 170) Me.LblNum.Name = "LblNum" Me.LblNum.Size = New System.Drawing.Size(16, 13) Me.LblNum.TabIndex = 32 Me.LblNum.Text = "..." ' 'LblLibelléNum ' Me.LblLibelléNum.AutoSize = True Me.LblLibelléNum.Location = New System.Drawing.Point(12, 170) Me.LblLibelléNum.Name = "LblLibelléNum" Me.LblLibelléNum.Size = New System.Drawing.Size(91, 13) Me.LblLibelléNum.TabIndex = 31 Me.LblLibelléNum.Text = "Numéro d'inscrit : " ' 'FrmInscripRens ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(253, 230) Me.ControlBox = False Me.Controls.Add(Me.LblNum) Me.Controls.Add(Me.LblLibelléNum) Me.Controls.Add(Me.txtAge) Me.Controls.Add(Me.hscAge) Me.Controls.Add(Me.btnAband) Me.Controls.Add(Me.btnSuiv) Me.Controls.Add(Me.txtCP) Me.Controls.Add(Me.txtVille) Me.Controls.Add(Me.txtAdr) Me.Controls.Add(Me.txtPre) Me.Controls.Add(Me.txtNom) Me.Controls.Add(Me.lblAge) Me.Controls.Add(Me.lblVille) Me.Controls.Add(Me.lblCP) Me.Controls.Add(Me.lblAdr) Me.Controls.Add(Me.lblPre) Me.Controls.Add(Me.lblNom) Me.Name = "FrmInscripRens" Me.Text = "Inscription" Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents lblNom As System.Windows.Forms.Label Friend WithEvents lblPre As System.Windows.Forms.Label Friend WithEvents lblAdr As System.Windows.Forms.Label Friend WithEvents lblCP As System.Windows.Forms.Label Friend WithEvents lblVille As System.Windows.Forms.Label Friend WithEvents lblAge As System.Windows.Forms.Label Friend WithEvents txtNom As System.Windows.Forms.TextBox Friend WithEvents txtPre As System.Windows.Forms.TextBox Friend WithEvents txtAdr As System.Windows.Forms.TextBox Friend WithEvents txtVille As System.Windows.Forms.TextBox Friend WithEvents txtCP As System.Windows.Forms.TextBox Friend WithEvents btnSuiv As System.Windows.Forms.Button Friend WithEvents btnAband As System.Windows.Forms.Button Friend WithEvents hscAge As System.Windows.Forms.HScrollBar Friend WithEvents txtAge As System.Windows.Forms.TextBox Friend WithEvents tmrReste As System.Windows.Forms.Timer Friend WithEvents LblNum As System.Windows.Forms.Label Friend WithEvents LblLibelléNum As System.Windows.Forms.Label End Class
{ "content_hash": "6abc0e0fe5e909a46e856e2843218b8a", "timestamp": "", "source": "github", "line_count": 260, "max_line_length": 758, "avg_line_length": 41.35, "alnum_prop": 0.6398474560505999, "repo_name": "Kcchouette/Inscription-au-bac", "id": "b280177da0a0f5723bce9c08e933ec72a950f5ed", "size": "10775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FrmInscripRens.Designer.vb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Visual Basic", "bytes": "147171" } ], "symlink_target": "" }
import sys from Foundation import * sys.dont_write_bytecode = True class QCPicLinkInfo(NSObject): def init(self): self = super(QCPicLinkInfo, self).init() if self is None: print "init None" return self def initWithCoder_(self, inCoder): self = super(QCPicLinkInfo, self).init() if self is None: print "initWithCoder_ None" self.fileSize = inCoder.decodeObjectForKey_("_fileSize") self.progress = inCoder.decodeObjectForKey_("_progress") self.picWidth = inCoder.decodeObjectForKey_("_picWidth") self.picHeight = inCoder.decodeObjectForKey_("_picHeight") self.sizeType = inCoder.decodeObjectForKey_("_sizeType") self.picTranStatus = inCoder.decodeObjectForKey_("_picTranStatus") self.picUrl = inCoder.decodeObjectForKey_("_picUrl") return self def description(self): return "\t{\n\t\tfileSize = %d\n\t\tprogress = %d\n\t\tpicWidth = %d\n\t\tpicHeight = %d\n\t\tsizeType = %d\n\t\tpicTranStatus = %d\n\t\tpicUrl = %s\n\t}" % (self.fileSize, self.progress, self.picWidth, self.picHeight, self.sizeType, self.picTranStatus, self.picUrl)
{ "content_hash": "4c9b744e26bdf3ddc6f2e5979166b806", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 274, "avg_line_length": 47.24, "alnum_prop": 0.6621507197290432, "repo_name": "foreverwind/Script", "id": "a7a802a059609ad737d04a6ceda1872a2c5f53be", "size": "1205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QCall/QCPicLinkInfo.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "58722" } ], "symlink_target": "" }
""" tests for magic_gui """ import wx import unittest import os #import dialogs.pmag_widgets as pmag_widgets from pmagpy import pmag from pmagpy import contribution_builder as cb from pmagpy import data_model3 as data_model from pmagpy import controlled_vocabularies3 as cv3 # set constants DMODEL = data_model.DataModel() WD = pmag.get_test_WD() PROJECT_WD = os.path.join(WD, "data_files", "magic_gui", "3_0") class TestVocabularies(unittest.TestCase): def setUp(self): self.vocab = cv3.Vocabulary() def tearDown(self): pass def test_vocabularies(self): self.assertIn('timescale_era', self.vocab.vocabularies.index) self.assertIn('Neoproterozoic', self.vocab.vocabularies.loc['timescale_era']) def test_suggested(self): self.assertIn('fossil_class', self.vocab.suggested.index) self.assertIn('Anthozoa', self.vocab.suggested.loc['fossil_class']) def test_methods(self): self.assertIn('sample_preparation', list(self.vocab.methods.keys())) for item in self.vocab.methods['sample_preparation']: self.assertTrue(item.startswith('SP-')) def test_all_codes(self): self.assertIn('SM-TTEST', self.vocab.all_codes.index) self.assertEqual('statistical_method', self.vocab.all_codes.loc['SM-TTEST']['dtype'])
{ "content_hash": "32225e60be8d70f40a50e2b0114fb034", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 85, "avg_line_length": 30.044444444444444, "alnum_prop": 0.6834319526627219, "repo_name": "lfairchild/PmagPy", "id": "9db4b355399e1267bd307a39f7eaf703672609d2", "size": "1352", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pmagpy_tests/test_dialog_components.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "33903" }, { "name": "Inno Setup", "bytes": "3675" }, { "name": "Jupyter Notebook", "bytes": "29090864" }, { "name": "Python", "bytes": "15912726" }, { "name": "Rich Text Format", "bytes": "1104" }, { "name": "Shell", "bytes": "9167" }, { "name": "TeX", "bytes": "3146" } ], "symlink_target": "" }
// TypeScript Version: 2.0 /// <reference types="@stdlib/types"/> import { NumericArray } from '@stdlib/types/array'; /** * Interface describing `nanmaxabs`. */ interface Routine { /** * Computes the maximum absolute value of a strided array, ignoring `NaN` values. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @returns maximum absolute value * * @example * var x = [ 1.0, -2.0, NaN, 2.0 ]; * * var v = nanmaxabs( x.length, x, 1 ); * // returns 2.0 */ ( N: number, x: NumericArray, stride: number ): number; /** * Computes the maximum absolute value of a strided array, ignoring `NaN` values and using alternative indexing semantics. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @param offset - starting index * @returns maximum absolute value * * @example * var x = [ 1.0, -2.0, NaN, 2.0 ]; * * var v = nanmaxabs.ndarray( x.length, x, 1, 0 ); * // returns 2.0 */ ndarray( N: number, x: NumericArray, stride: number, offset: number ): number; // tslint:disable-line:max-line-length } /** * Computes the maximum absolute value of a strided array, ignoring `NaN` values. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @returns maximum absolute value * * @example * var x = [ 1.0, -2.0, NaN, 2.0 ]; * * var v = nanmaxabs( x.length, x, 1 ); * // returns 2.0 * * @example * var x = [ 1.0, -2.0, NaN, 2.0 ]; * * var v = nanmaxabs.ndarray( x.length, x, 1, 0 ); * // returns 2.0 */ declare var nanmaxabs: Routine; // EXPORTS // export = nanmaxabs;
{ "content_hash": "3b72b6d069d591eeb43cd51662307de3", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 122, "avg_line_length": 22.875, "alnum_prop": 0.639344262295082, "repo_name": "stdlib-js/stdlib", "id": "359cc0534cb6bcbdf5498d2b0355d146bb28847c", "size": "2262", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/node_modules/@stdlib/stats/base/nanmaxabs/docs/types/index.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "21739" }, { "name": "C", "bytes": "15336495" }, { "name": "C++", "bytes": "1349482" }, { "name": "CSS", "bytes": "58039" }, { "name": "Fortran", "bytes": "198059" }, { "name": "HTML", "bytes": "56181" }, { "name": "Handlebars", "bytes": "16114" }, { "name": "JavaScript", "bytes": "85975525" }, { "name": "Julia", "bytes": "1508654" }, { "name": "Makefile", "bytes": "4806816" }, { "name": "Python", "bytes": "3343697" }, { "name": "R", "bytes": "576612" }, { "name": "Shell", "bytes": "559315" }, { "name": "TypeScript", "bytes": "19309407" }, { "name": "WebAssembly", "bytes": "5980" } ], "symlink_target": "" }
FROM balenalib/i386-nlp-ubuntu:eoan-build LABEL io.balena.device-type="iot2000" RUN apt-get update && apt-get install -y --no-install-recommends \ less \ kmod \ nano \ net-tools \ ifupdown \ iputils-ping \ i2c-tools \ usbutils \ && rm -rf /var/lib/apt/lists/* RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 32-bit (x86) for Intel Quark \nOS: Ubuntu eoan \nVariant: build variant \nDefault variable(s): UDEV=off \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "9f8303579b1bb09df9282edf95de6d51", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 639, "avg_line_length": 55.75, "alnum_prop": 0.7022421524663677, "repo_name": "nghiant2710/base-images", "id": "25abacd9c4f74ed3d886b19b04fa8f3da8a9e65a", "size": "1115", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/device-base/iot2000/ubuntu/eoan/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
#import "SBAlertItem.h" @class BKSProcessAssertion, NSDictionary, NSObject<OS_dispatch_source>, NSString, NSTimer, SBUISound; @interface SBUserNotificationAlert : SBAlertItem { unsigned int _replyPort; NSObject<OS_dispatch_source> *_portWatcher; NSObject<OS_dispatch_source> *_expirationTimer; _Bool _cleanedUp; int _token; int _timeout; unsigned long long _requestFlags; NSString *_alertHeader; id _alertMessage; NSString *_alertMessageDelimiter; NSString *_defaultButtonTitle; NSString *_alternateButtonTitle; NSString *_otherButtonTitle; NSString *_soundPath; NSDictionary *_avControllerAttributes; NSDictionary *_avItemAttributes; double _soundRepeatDuration; NSTimer *_soundStopTimer; id _keyboardTypes; id _autocapitalizationTypes; id _autocorrectionTypes; id _textFieldButtonDisplayDefaultButtonURLs; id _textFieldButtonImagePaths; id _textFieldTitles; id _textFieldValues; id _textFieldButtonDisplayTitles; id _textFieldButtonDisplayDefaultButtonTitles; long long _currentTextFieldButtonDisplayIndex; double _creationTime; int _defaultButtonTag; int _unlockActionButtonTag; unsigned int _replyFlags; long long _defaultButtonIndex; long long _alternateButtonIndex; long long _otherButtonIndex; NSString *_defaultResponseLaunchBundleID; unsigned int _cancel:1; unsigned int _isActivated:1; unsigned int _aboveLock:1; unsigned int _displayActionButtonOnLockScreen:1; unsigned int _dismissOnLock:1; unsigned int _dontDismissOnUnlock:1; unsigned int _behavesSuperModally:1; unsigned int _allowMenuButtonDismissal:1; unsigned int _forcesModalAlertAppearance:1; unsigned int _oneButtonPerLine:1; unsigned int _groupsTextFields:1; unsigned int _usesUndoStyle:1; unsigned int _configuredLocked:1; unsigned int _configuredNeedsPasscode:1; unsigned int _defaultResponseAppLaunchWaitingForPasscode:1; SBUISound *_sound; BKSProcessAssertion *_processAssertion; } @property(retain) NSString *defaultResponseLaunchBundleID; // @synthesize defaultResponseLaunchBundleID=_defaultResponseLaunchBundleID; @property(retain) NSString *otherButtonTitle; // @synthesize otherButtonTitle=_otherButtonTitle; @property(retain) NSString *alternateButtonTitle; // @synthesize alternateButtonTitle=_alternateButtonTitle; @property(retain) NSString *defaultButtonTitle; // @synthesize defaultButtonTitle=_defaultButtonTitle; @property(retain) NSString *alertMessageDelimiter; // @synthesize alertMessageDelimiter=_alertMessageDelimiter; @property(retain) NSString *alertMessage; // @synthesize alertMessage=_alertMessage; @property(retain) NSString *alertHeader; // @synthesize alertHeader=_alertHeader; @property(retain) NSDictionary *avItemAttributes; // @synthesize avItemAttributes=_avItemAttributes; @property(retain) NSDictionary *avControllerAttributes; // @synthesize avControllerAttributes=_avControllerAttributes; @property(retain) NSString *soundPath; // @synthesize soundPath=_soundPath; @property(retain) id textFieldButtonDisplayDefaultButtonTitles; // @synthesize textFieldButtonDisplayDefaultButtonTitles=_textFieldButtonDisplayDefaultButtonTitles; @property(retain) id textFieldButtonDisplayTitles; // @synthesize textFieldButtonDisplayTitles=_textFieldButtonDisplayTitles; @property(retain) id textFieldValues; // @synthesize textFieldValues=_textFieldValues; @property(retain) id textFieldTitles; // @synthesize textFieldTitles=_textFieldTitles; @property(retain) id textFieldButtonDisplayDefaultButtonURLs; // @synthesize textFieldButtonDisplayDefaultButtonURLs=_textFieldButtonDisplayDefaultButtonURLs; @property(retain) id textFieldButtonImagePaths; // @synthesize textFieldButtonImagePaths=_textFieldButtonImagePaths; @property(retain) id autocorrectionTypes; // @synthesize autocorrectionTypes=_autocorrectionTypes; @property(retain) id autocapitalizationTypes; // @synthesize autocapitalizationTypes=_autocapitalizationTypes; @property(retain) id keyboardTypes; // @synthesize keyboardTypes=_keyboardTypes; - (void)didFailToActivate; - (void)didDeactivateForReason:(int)arg1; - (void)willDeactivateForReason:(int)arg1; - (void)noteVolumeOrLockPressed; - (_Bool)reappearsAfterUnlock; - (_Bool)reappearsAfterLock; - (_Bool)forcesModalAlertAppearance; - (_Bool)behavesSuperModally; - (void)alertView:(id)arg1 clickedButtonAtIndex:(long long)arg2; - (_Bool)alertView:(id)arg1 shouldDismissForButtonAtIndex:(long long)arg2; - (void)performUnlockAction; - (_Bool)_needsDismissalWithClickedButtonIndex:(long long)arg1; - (void)_sendResponse:(int)arg1; - (void)_textFieldButtonPressed:(id)arg1; - (void)_setSheetDefaultButtonTitle:(id)arg1; - (void)cancel; - (void)_cleanup; - (void)_setActivated:(_Bool)arg1; - (void)configure:(_Bool)arg1 requirePasscodeForActions:(_Bool)arg2; - (id)sound; - (void)willActivate; - (_Bool)displayActionButtonOnLockScreen; - (_Bool)allowMenuButtonDismissal; - (_Bool)dismissOnLock; - (_Bool)shouldShowInLockScreen; - (int)token; - (Class)alertSheetClass; - (void)dealloc; - (void)updateWithMessage:(id)arg1 requestFlags:(int)arg2; - (id)initWithMessage:(id)arg1 replyPort:(unsigned int)arg2 requestFlags:(int)arg3 auditToken:(CDStruct_6ad76789)arg4; - (id)_safeLocalizedValue:(id)arg1 withBundle:(id)arg2; @end
{ "content_hash": "339963808be03a85527b0ff353fa233d", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 164, "avg_line_length": 46.189655172413794, "alnum_prop": 0.7902202314296379, "repo_name": "matthewsot/CocoaSharp", "id": "8d938b4a2be481ccd4ba8b226195cb17565927c4", "size": "5498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Headers/SpringBoard/SBUserNotificationAlert.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259784" }, { "name": "C#", "bytes": "2789005" }, { "name": "C++", "bytes": "252504" }, { "name": "Objective-C", "bytes": "24301417" }, { "name": "Smalltalk", "bytes": "167909" } ], "symlink_target": "" }
input, label, select, textarea { vertical-align: middle; margin: 0; padding: 0; } input[type=text], input[type=password], select, textarea { background-color: #f4f4f5; border: 1px inset #ccc; padding: 2px; } input[disabled], select[disabled], textarea[disabled] { border-color: #ddc; background-color: #ddc; } input[type=button], input[type=submit], input[type=reset] { color: white; background-color: #3876C1; border: 1px outset #3876C1; } input[type=button]:active, input[type=submit]:active, input[type=reset]:active { border-style: inset; } .error input { border-color: #c03; } /* Styles for scriptaculous-generated autocompleters */ div.autocomplete { position: absolute; background-color: white; border: 1px solid #888; border-top-width: 0; margin: 0; padding: 0; } div.autocomplete ul { list-style-type: none; margin: 0; padding: 0; } div.autocomplete ul li.selected { background-color: #ffb;} div.autocomplete ul li { list-style-type: none; display: block; margin: 0; padding: 2px; border-style: solid; border-color: #888; border-width: 1px 0 0 0; cursor: pointer; } /* SELECT-equivalent groups of radio buttons */ .longselect { border: 1px inset #ccc; } .longselect label { display: block; padding: 0.2em 0.5em; /* next two properties combine to give a hanging indent */ text-indent: -1.3em; padding-left: 1.8em; background-color: #f4f4f5; } .longselect label:hover { background-color: #D7E7ED; }
{ "content_hash": "2046602e2eec8b09458c9b9c5fbd026a", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 80, "avg_line_length": 21.732394366197184, "alnum_prop": 0.6642903434867142, "repo_name": "NCIP/ctms-commons", "id": "747a8b8325b58ff70e70622e4437dc1c8627f40a", "size": "1543", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "laf/src/main/resources/gov/nih/nci/cabig/ctms/lookandfeel/assets/css/fields.css", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1516015" }, { "name": "JavaScript", "bytes": "107388" }, { "name": "Ruby", "bytes": "15618" }, { "name": "Shell", "bytes": "1664" }, { "name": "XSLT", "bytes": "243925" } ], "symlink_target": "" }
package uk.co.harrymartland.multijmx.domain.optionvalue.connectionarg; import com.google.inject.Inject; import org.apache.commons.cli.Option; import uk.co.harrymartland.multijmx.domain.ValidationException; import uk.co.harrymartland.multijmx.domain.connection.JMXConnection; import uk.co.harrymartland.multijmx.domain.optionvalue.AbstractMultiOptionValue; import uk.co.harrymartland.multijmx.service.commandline.CommandLineService; import uk.co.harrymartland.multijmx.service.connection.ConnectionService; import java.util.List; import java.util.stream.Collectors; public class ConnectionArgOptionValueImpl extends AbstractMultiOptionValue<List<JMXConnection>> implements ConnectionArgOptionValue { private ConnectionService connectionService; @Inject public ConnectionArgOptionValueImpl(CommandLineService commandLineService, ConnectionService connectionService) { super(commandLineService); this.connectionService = connectionService; } @Override public String getArg() { return null; } @Override protected List<JMXConnection> lazyLoadValue() { return getCommandLine().getArgList().stream() .map(connectionString -> connectionService.createConnection(connectionString)) .collect(Collectors.toList()); } @Override public int getNumberOfValues() { return getCommandLine().getArgList().size(); } @Override protected boolean hasOption() { return getCommandLine().getArgList().size() > 0; } @Override public void validate() throws ValidationException { if (hasOption()) { for (String connectionString : getCommandLine().getArgList()) { connectionService.validate(connectionString); } } } @Override protected Option lazyLoadOption() { return null; } }
{ "content_hash": "14c2f90d4f1e4b15dd8fbb9ea2b93ac8", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 133, "avg_line_length": 31.533333333333335, "alnum_prop": 0.7219873150105708, "repo_name": "HarryEMartland/multi-jmx", "id": "d2364cb9a8cef3385537dca77896e96a09f7ae1d", "size": "1892", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/uk/co/harrymartland/multijmx/domain/optionvalue/connectionarg/ConnectionArgOptionValueImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "80792" } ], "symlink_target": "" }
<?php namespace OwenIt\Auditing; use Illuminate\Support\ServiceProvider; use OwenIt\Auditing\Console\AuditDriverMakeCommand; use OwenIt\Auditing\Console\AuditTableCommand; use OwenIt\Auditing\Console\InstallCommand; use OwenIt\Auditing\Contracts\Auditor; class AuditingServiceProvider extends ServiceProvider { /** * {@inheritdoc} */ protected $defer = true; /** * Bootstrap the service provider. * * @return void */ public function boot() { $this->setupConfig($this->app); } /** * Setup the config. * * @param $app * * @return void */ protected function setupConfig($app) { $config = realpath(__DIR__.'/../config/audit.php'); if ($app->runningInConsole()) { $this->publishes([ $config => base_path('config/audit.php'), ]); } $this->mergeConfigFrom($config, 'audit'); } /** * Register the service provider. * * @return void */ public function register() { $this->commands([ AuditTableCommand::class, AuditDriverMakeCommand::class, InstallCommand::class, ]); $this->app->singleton(Auditor::class, function ($app) { return new \OwenIt\Auditing\Auditor($app); }); } /** * {@inheritdoc} */ public function provides() { return [ Auditor::class, ]; } }
{ "content_hash": "00ce2aac9af4b4adf54ecfa656cb0a21", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 63, "avg_line_length": 19.842105263157894, "alnum_prop": 0.5437665782493368, "repo_name": "KaanErkol/laravelAuditTranslatable", "id": "c073eed772d4919b70e08d7fa94e398145c01241", "size": "1900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AuditingServiceProvider.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "40413" } ], "symlink_target": "" }
using System; using System.Collections.Generic; namespace Stitch.Chart.Axis.Algorithms { /// <summary> /// Interface for Axis algorithms. /// </summary> /// <typeparam name="T"></typeparam> public interface ITickAlgorithm<T> : IComparer<T> where T : IComparable<T> { /// <summary> /// Suggest possible tick values based upon the number of desired intervals and the set of values. /// </summary> /// <param name="set"></param> /// <param name="intervals"></param> /// <returns></returns> IEnumerable<T> SuggestTicks( IEnumerable<T> set, int intervals ); /// <summary> /// Compute a numeric distance between the two values a,b. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> double Subtract( IEnumerable<T> set, T a, T b ); /// <summary> /// Compute a numeric value greater than or equal to 0 and less than or equal to 1 that /// represents the percentage of the value on the range [limitMinimum, limitMaximum] /// </summary> /// <param name="limitMinimum">The minimum limit value.</param> /// <param name="limitMaximum">The maximum limit value.</param> /// <param name="value">The value to evaluate.</param> /// <returns></returns> double Percentage( IEnumerable<T> range, T value ); /// <summary> /// Identify the minimum value in the set. /// </summary> /// <param name="set">The set.</param> /// <returns>The set's minimum value.</returns> T Min( IEnumerable<T> set ); /// <summary> /// Identify the maximum value in the set. /// </summary> /// <param name="set">The set.</param> /// <returns>The set's maximum value.</returns> T Max( IEnumerable<T> set ); } }
{ "content_hash": "628b975e39b56587dbd4d9885403feb2", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 106, "avg_line_length": 37.05769230769231, "alnum_prop": 0.568759730150493, "repo_name": "jherink/Stitch", "id": "e23727668451430557d5d1344eacfd9794081904", "size": "1929", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Stitch/Chart/Axis/Algorithms/ITickAlgorithm.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "842261" }, { "name": "CSS", "bytes": "87886" }, { "name": "HTML", "bytes": "5444760" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import Inventationery.apps.Vendor.models class Migration(migrations.Migration): dependencies = [ ('DirParty', '0001_initial'), ] operations = [ migrations.CreateModel( name='VendorModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('AccountNum', models.CharField(default=Inventationery.apps.Vendor.models.Get_Account_Num, unique=True, max_length=45)), ('AccountType', models.CharField(default=b'PER', max_length=3, choices=[(b'PER', b'Persona'), (b'PAR', b'Organizaci\xc3\xb3n')])), ('OneTimeVendor', models.BooleanField(default=False)), ('VendGroup', models.CharField(default=b'Loc', max_length=3, choices=[(b'Loc', b'Local'), (b'Nat', b'Nacional'), (b'Int', b'Internacional')])), ('CreditLimit', models.DecimalField(null=True, max_digits=15, decimal_places=2, blank=True)), ('CurrencyCode', models.CharField(default=b'MXN', max_length=3)), ('VATNum', models.CharField(max_length=13, blank=True)), ('Notes', models.TextField(max_length=200, blank=True)), ('Party', models.OneToOneField(related_name='VendorParty', null=True, default=None, blank=True, to='DirParty.DirPartyModel')), ], options={ 'abstract': False, }, ), ]
{ "content_hash": "b95a321075743156dc5d437b44d51dc5", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 159, "avg_line_length": 49.61764705882353, "alnum_prop": 0.5963248369887374, "repo_name": "alexharmenta/Inventationery", "id": "a27457e3e5662dafa330950ad82e7821238a9e8b", "size": "1711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Inventationery/apps/Vendor/migrations/0001_initial.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "127726" }, { "name": "HTML", "bytes": "170879" }, { "name": "JavaScript", "bytes": "118056" }, { "name": "Python", "bytes": "243110" } ], "symlink_target": "" }
<?php namespace NetSuite\Classes; class BomRevisionSearchRow extends SearchRow { public $basic; public $billOfMaterialsJoin; public $componentJoin; public $transactionJoin; public $customSearchJoin; static $paramtypesmap = array( "basic" => "BomRevisionSearchRowBasic", "billOfMaterialsJoin" => "BomSearchRowBasic", "componentJoin" => "BomRevisionComponentSearchRowBasic", "transactionJoin" => "TransactionSearchRowBasic", "customSearchJoin" => "CustomSearchRowBasic[]", ); }
{ "content_hash": "85a3f3415ae6146ee4b44f3f3b2b5709", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 64, "avg_line_length": 28.789473684210527, "alnum_prop": 0.6928702010968921, "repo_name": "fungku/netsuite-php", "id": "ae360ed1a818b1855f1816fbc8b07534c4d1ac41", "size": "1267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Classes/BomRevisionSearchRow.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "2828253" } ], "symlink_target": "" }
package org.apereo.portal.portlet.container.services; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.Cookie; import org.easymock.EasyMock; import org.apereo.portal.portlet.dao.IPortletCookieDao; import org.apereo.portal.portlet.om.IPortalCookie; import org.apereo.portal.portlet.om.IPortletCookie; import org.apereo.portal.portlet.om.IPortletWindowId; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; /** * Tests for {@link PortletCookieServiceImpl}. * * @author Nicholas Blair * @version $Id$ */ public class PortletCookieServiceImplTest { /** * Control test invocation of {@link PortletCookieServiceImpl#updatePortalCookie(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. */ @Test public void testUpdatePortletCookieControl() { IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); EasyMock.expect(portletCookieDao.updatePortalCookieExpiration(portalCookie, PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); EasyMock.replay(portletCookieDao); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); cookieService.updatePortalCookie(request, response); Cookie [] cookies = response.getCookies(); Assert.assertNotNull(cookies); Assert.assertEquals(1, cookies.length); EasyMock.verify(portletCookieDao); } /** * Test {@link PortletCookieServiceImpl#getOrCreatePortalCookie(javax.servlet.http.HttpServletRequest)}. * that results in creating a new PortalCookie. */ @Test public void testGetOrCreatePortalCookieCreate() { IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); EasyMock.replay(portletCookieDao); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); MockHttpServletRequest request = new MockHttpServletRequest(); cookieService.getOrCreatePortalCookie(request); EasyMock.verify(portletCookieDao); } /** * Test {@link PortletCookieServiceImpl#getOrCreatePortalCookie(javax.servlet.http.HttpServletRequest)}. * that results in returning an existing portalcookie from the request cookies */ @Test public void testGetOrCreatePortalCookieGetExistingFromRequestCookies() { IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.getPortalCookie("ABCDEF")).andReturn(portalCookie); EasyMock.replay(portletCookieDao); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); MockHttpServletRequest request = new MockHttpServletRequest(); Cookie [] cookies = new Cookie[1]; Cookie cookie = new Cookie(IPortletCookieService.DEFAULT_PORTAL_COOKIE_NAME, "ABCDEF"); cookies[0] = cookie; request.setCookies(cookies); IPortalCookie result = cookieService.getOrCreatePortalCookie(request); Assert.assertEquals(portalCookie, result); EasyMock.verify(portletCookieDao); } /** * Test {@link PortletCookieServiceImpl#getOrCreatePortalCookie(javax.servlet.http.HttpServletRequest)}. * that results in returning an existing portalcookie from the id stored in the session. */ @Test public void testGetOrCreatePortalCookieGetExistingFromSession() { IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.getPortalCookie("ABCDEF")).andReturn(portalCookie); EasyMock.replay(portletCookieDao); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(PortletCookieServiceImpl.SESSION_ATTRIBUTE__PORTAL_COOKIE_ID, "ABCDEF"); IPortalCookie result = cookieService.getOrCreatePortalCookie(request); Assert.assertEquals(portalCookie, result); EasyMock.verify(portletCookieDao); } /** * Control test for adding a portlet cookie: no existing portalCookie, portlet cookie requires persistence. */ @Test public void testAddCookieControl() { Cookie portletCookie = new Cookie("somePortletCookieName", "somePortletCookieValue"); // max age will trigger persistence portletCookie.setMaxAge(360); IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); EasyMock.expect(portletCookieDao.addOrUpdatePortletCookie(portalCookie, portletCookie)).andReturn(portalCookie); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); IPortletWindowId mockWindowId = EasyMock.createMock(IPortletWindowId.class); EasyMock.replay(portletCookieDao, mockWindowId); MockHttpServletRequest request = new MockHttpServletRequest(); cookieService.addCookie(request, mockWindowId, portletCookie); EasyMock.verify(portletCookieDao, mockWindowId); } /** * Control test for removing a portlet cookie. * Logic is nearly identical to create, as both {@link IPortletCookieDao#addOrUpdatePortletCookie(IPortalCookie, Cookie)} is used * in both scenarios. */ @Test public void testAddCookieRemove() { Cookie portletCookie = new Cookie("somePortletCookieName", "somePortletCookieValue"); // max age will trigger persistence removal portletCookie.setMaxAge(0); IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); EasyMock.expect(portletCookieDao.addOrUpdatePortletCookie(portalCookie, portletCookie)).andReturn(portalCookie); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); IPortletWindowId mockWindowId = EasyMock.createMock(IPortletWindowId.class); EasyMock.replay(portletCookieDao, mockWindowId); MockHttpServletRequest request = new MockHttpServletRequest(); cookieService.addCookie(request, mockWindowId, portletCookie); EasyMock.verify(portletCookieDao, mockWindowId); } /** * Control test for adding a portlet cookie with maxAge == -1, which results in a session-only cookie. */ @Test public void testAddCookieSessionOnly() { Cookie portletCookie = new Cookie("somePortletCookieName", "somePortletCookieValue"); // max age will trigger persistence portletCookie.setMaxAge(-1); IPortletCookieDao portletCookieDao = EasyMock.createMock(IPortletCookieDao.class); MockPortalCookie portalCookie = new MockPortalCookie(); portalCookie.setValue("ABCDEF"); EasyMock.expect(portletCookieDao.createPortalCookie(PortletCookieServiceImpl.DEFAULT_MAX_AGE)).andReturn(portalCookie); PortletCookieServiceImpl cookieService = new PortletCookieServiceImpl(); cookieService.setPortletCookieDao(portletCookieDao); IPortletWindowId mockWindowId = EasyMock.createMock(IPortletWindowId.class); EasyMock.replay(portletCookieDao, mockWindowId); MockHttpServletRequest request = new MockHttpServletRequest(); cookieService.addCookie(request, mockWindowId, portletCookie); Map<String, SessionOnlyPortletCookieImpl> sessionOnlyMap = cookieService.getSessionOnlyPortletCookieMap(request); SessionOnlyPortletCookieImpl sessionOnlyCookie = sessionOnlyMap.get("somePortletCookieName"); Assert.assertNotNull(sessionOnlyCookie); Assert.assertEquals(-1, sessionOnlyCookie.getMaxAge()); Assert.assertEquals("somePortletCookieValue", sessionOnlyCookie.getValue()); EasyMock.verify(portletCookieDao, mockWindowId); } /** * Mock {@link IPortalCookie} used in these tests. * * @author Nicholas Blair * @version $Id$ */ class MockPortalCookie implements IPortalCookie { private DateTime created = DateTime.now(); private DateTime expires = DateTime.now().plusHours(1); private Set<IPortletCookie> portletCookies = new HashSet<IPortletCookie>(); private String value; @Override public DateTime getCreated() { return this.created; } @Override public DateTime getExpires() { return this.expires; } @Override public Set<IPortletCookie> getPortletCookies() { return this.portletCookies; } @Override public String getValue() { return this.value; } @Override public void setExpires(DateTime expires) { this.expires = expires; } public void setCreated(DateTime created) { this.created = created; } public void setPortletCookies(Set<IPortletCookie> portletCookies) { this.portletCookies = portletCookies; } public void setValue(String value) { this.value = value; } } }
{ "content_hash": "1e9c0eb06bd7e446f872347a53ac6b7a", "timestamp": "", "source": "github", "line_count": 268, "max_line_length": 162, "avg_line_length": 37.42910447761194, "alnum_prop": 0.7935400259196491, "repo_name": "apetro/uPortal", "id": "7b0462ae59c41ec3dbaf249d5e9681d576547dc7", "size": "10830", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "uportal-war/src/test/java/org/apereo/portal/portlet/container/services/PortletCookieServiceImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "907" }, { "name": "CSS", "bytes": "437607" }, { "name": "Groovy", "bytes": "56703" }, { "name": "HTML", "bytes": "262695" }, { "name": "Java", "bytes": "9511611" }, { "name": "JavaScript", "bytes": "813747" }, { "name": "Perl", "bytes": "1769" }, { "name": "Shell", "bytes": "7292" }, { "name": "XSLT", "bytes": "298340" } ], "symlink_target": "" }
[![Latest Stable Version](https://poser.pugx.org/serendipity_hq/phpunit_profiler/v/stable)](https://packagist.org/packages/serendipity_hq/phpunit_profiler) [![Build Status](https://travis-ci.org/SerendipityHQ/SHQ_PHPUnit_Profiler.svg?branch=master)](https://travis-ci.org/SerendipityHQ/SHQ_PHPUnit_Profiler) [![Total Downloads](https://poser.pugx.org/serendipity_hq/phpunit_profiler/downloads)](https://packagist.org/packages/serendipity_hq/phpunit_profiler) [![License](https://poser.pugx.org/serendipity_hq/phpunit_profiler/license)](https://packagist.org/packages/serendipity_hq/phpunit_profiler) [![Code Climate](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler/badges/gpa.svg)](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler) [![Test Coverage](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler/badges/coverage.svg)](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler/coverage) [![Issue Count](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler/badges/issue_count.svg)](https://codeclimate.com/github/SerendipityHQ/SHQ_PHPUnit_Profiler) [![StyleCI](https://styleci.io/repos/49488856/shield)](https://styleci.io/repos/49488856) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/0ad683e4-b29b-4d8b-b968-cfb61e6117e3/mini.png)](https://insight.sensiolabs.com/projects/0ad683e4-b29b-4d8b-b968-cfb61e6117e3) [![Dependency Status](https://www.versioneye.com/user/projects/56ae2a7d7e03c7003db69697/badge.svg?style=flat)](https://www.versioneye.com/user/projects/56ae2a7d7e03c7003db69697) [![Coverage Status](https://coveralls.io/repos/github/SerendipityHQ/SHQ_PHPUnit_Profiler/badge.svg?branch=master)](https://coveralls.io/github/SerendipityHQ/SHQ_PHPUnit_Profiler?branch=master) # SHQ_PHPUnit_Profiler A PHPUnit listener to profile the execution of test suites and tests inside them. This listener can show the time needed by each test and each test suite to complete and the memory used by each one of them. ## Installation Use Composer to install this listener: $ composer require serendipity_hq/phpunit_profiler To [configure the listener](https://phpunit.de/manual/current/en/appendixes.configuration.html#appendixes.configuration.test-listeners) you have to pass an array of options: <listeners> <listener class="SerendipityHQ\Library\PHPUnit_Profiler\Profiler"> <arguments> <array> <element key="time"><boolean>true</boolean></element> <element key="profileTimeWithStopwatch"><boolean>true</boolean></element> <element key="profileMemoryUsage"><boolean>true</boolean></element> <element key="profileMemoryDetailedUsage"><boolean>true</boolean></element> </array> </arguments> </listener> </listeners> The listener will output the profiling information. NOTE: As this is a [listener](https://phpunit.de/manual/current/en/extending-phpunit.html#extending-phpunit.PHPUnit_Framework_TestListener) and not a `ResultsPrinter`, it doesn't take care of the use of `--verbose` or `--debug` options.
{ "content_hash": "1477d123e5f7c4dce855a2a1eacb9d3c", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 236, "avg_line_length": 75.42857142857143, "alnum_prop": 0.7541035353535354, "repo_name": "SerendipityHQ/SHQ_PHPUnit_Profiler", "id": "e15713c11551a85d1301c16d8036210f7d0eac79", "size": "3168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "9548" } ], "symlink_target": "" }
#ifndef CPP_JSONNET_H_ #define CPP_JSONNET_H_ #include <cstdint> #include <cstring> #include <functional> #include <map> #include <string> extern "C" { #include "libjsonnet.h" } namespace jsonnet { class Jsonnet { public: Jsonnet(); ~Jsonnet(); /// Return the version string of the Jsonnet interpreter. Conforms to /// semantic versioning https://semver.org/. If this does not match /// LIB_JSONNET_VERSION then there is a mismatch between header and compiled /// library. static std::string version(); /// Initializes the Jsonnet VM. This method must be called before calling any /// of the other methods. /// /// @return true if the Jsonnet VM was successfully initialized, false /// otherwise. bool init(); /// Sets the maximum stack depth. void setMaxStack(uint32_t depth); /// Sets the number of objects required before a garbage collection cycle is /// allowed. void setGcMinObjects(uint32_t objects); /// Run the garbage collector after this amount of growth in the number of /// objects. void setGcGrowthTrigger(double growth); /// Set whether to expect a string as output and don't JSON encode it. void setStringOutput(bool string_output); /// Set the number of lines of stack trace to display (0 to display all). void setMaxTrace(uint32_t lines); /// Add to the default import callback's library search path. void addImportPath(const std::string& path); /// Bind a string top-level argument for a top-level parameter. /// /// Argument values are copied so memory should be managed by caller. void bindTlaVar(const std::string& key, const std::string& value); /// Bind a code top-level argument for a top-level parameter. /// /// Argument values are copied so memory should be managed by caller. void bindTlaCodeVar(const std::string& key, const std::string& value); /// Bind a Jsonnet external variable to the given value. /// /// Argument values are copied so memory should be managed by caller. void bindExtVar(const std::string& key, const std::string& value); /// Bind a Jsonnet external code variable to the given value. /// /// Argument values are copied so memory should be managed by caller. void bindExtCodeVar(const std::string& key, const std::string& value); /// Evaluate a file containing Jsonnet code to return a JSON string. /// /// This method returns true if the Jsonnet code is successfully evaluated. /// Otherwise, it returns false, and the error output can be returned by /// calling LastError(); /// /// @param filename Path to a file containing Jsonnet code. /// @param output Pointer to string to contain the output. /// @return true if the Jsonnet code was successfully evaluated, false /// otherwise. bool evaluateFile(const std::string& filename, std::string* output); /// Evaluate a string containing Jsonnet code to return a JSON string. /// /// This method returns true if the Jsonnet code is successfully evaluated. /// Otherwise, it returns false, and the error output can be returned by /// calling LastError(); /// /// @param filename Path to a file (used in error message). /// @param snippet Jsonnet code to execute. /// @param output Pointer to string to contain the output. /// @return true if the Jsonnet code was successfully evaluated, false /// otherwise. bool evaluateSnippet(const std::string& filename, const std::string& snippet, std::string* output); /// Evaluate a file containing Jsonnet code, return a number of JSON files. /// /// This method returns true if the Jsonnet code is successfully evaluated. /// Otherwise, it returns false, and the error output can be returned by /// calling LastError(); /// /// @param filename Path to a file containing Jsonnet code. /// @param outputs Pointer to map which will store the output map of filename /// to JSON string. bool evaluateFileMulti(const std::string& filename, std::map<std::string, std::string>* outputs); /// Evaluate a string containing Jsonnet code, return a number of JSON files. /// /// This method returns true if the Jsonnet code is successfully evaluated. /// Otherwise, it returns false, and the error output can be returned by /// calling LastError(); /// /// @param filename Path to a file containing Jsonnet code. /// @param snippet Jsonnet code to execute. /// @param outputs Pointer to map which will store the output map of filename /// to JSON string. /// @return true if the Jsonnet code was successfully evaluated, false /// otherwise. bool evaluateSnippetMulti(const std::string& filename, const std::string& snippet, std::map<std::string, std::string>* outputs); /// Returns the last error raised by Jsonnet. std::string lastError() const; private: struct JsonnetVm* vm_; std::string last_error_; }; } // namespace jsonnet #endif // CPP_JSONNET_H_
{ "content_hash": "4d157a16561a5b229224da476460fbf6", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 86, "avg_line_length": 37.81159420289855, "alnum_prop": 0.6661556151782292, "repo_name": "google/jsonnet", "id": "ed14f31c16e3b56def4e35da83bf78c51de5346d", "size": "5796", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/libjsonnet++.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "45689" }, { "name": "C++", "bytes": "563087" }, { "name": "CMake", "bytes": "12877" }, { "name": "CSS", "bytes": "4684" }, { "name": "Dockerfile", "bytes": "332" }, { "name": "HTML", "bytes": "15889" }, { "name": "Java", "bytes": "8813" }, { "name": "Jsonnet", "bytes": "1011828" }, { "name": "Makefile", "bytes": "7378" }, { "name": "Python", "bytes": "86888" }, { "name": "Shell", "bytes": "36046" }, { "name": "Starlark", "bytes": "6219" } ], "symlink_target": "" }
module Rubotium module Adb module Commands class InstrumentCommand COMMAND = 'am instrument -w -e class' def initialize(package_name, test_name, test_package_name, test_runner) @package_name = package_name @test_name = test_name @test_package_name = test_package_name @test_runner = test_runner end def executable_command [COMMAND, ].join(' ') end private attr_reader :package_name def test_case [package_name, test_name].join('#') end end end end end
{ "content_hash": "781dcfcd3deb72b885c90f04a01af417", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 79, "avg_line_length": 23.51851851851852, "alnum_prop": 0.5417322834645669, "repo_name": "ssmiech/rubotium", "id": "b6fa4f94fc6e011eccbe1784dee1298592a137e7", "size": "635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rubotium/adb/commands/instrument_command.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1599" }, { "name": "Ruby", "bytes": "100422" } ], "symlink_target": "" }
load("test/mjsunit/wasm/wasm-module-builder.js"); // The stack trace contains file path, only keep "stack.js". function stripPath(s) { return s.replace(/[^ (]*stack\.js/g, "stack.js"); } function verifyStack(frames, expected) { assertEquals(expected.length, frames.length, "number of frames mismatch"); expected.forEach(function(exp, i) { assertEquals(exp[1], frames[i].getFunctionName(), "["+i+"].getFunctionName()"); assertEquals(exp[2], frames[i].getLineNumber(), "["+i+"].getLineNumber()"); if (exp[0]) assertEquals(exp[3], frames[i].getPosition(), "["+i+"].getPosition()"); assertContains(exp[4], frames[i].getFileName(), "["+i+"].getFileName()"); var toString; if (exp[0]) { toString = "<anonymous>:wasm-function[" + exp[6] + "]:" + exp[5]; if (exp[1] !== null) toString = exp[1] + " (" + toString + ")"; } else { toString = exp[4] + ":" + exp[2] + ":"; } assertContains(toString, frames[i].toString(), "["+i+"].toString()"); }); } var stack; function STACK() { var e = new Error(); stack = e.stack; } var builder = new WasmModuleBuilder(); builder.addMemory(0, 1, false); builder.addImport("mod", "func", kSig_v_v); builder.addFunction("main", kSig_v_v) .addBody([kExprCallFunction, 0]) .exportAs("main"); builder.addFunction("exec_unreachable", kSig_v_v) .addBody([kExprUnreachable]) .exportAs("exec_unreachable"); // Make this function unnamed, just to test also this case. var mem_oob_func = builder.addFunction(undefined, kSig_i_v) // Access the memory at offset -1, to provoke a trap. .addBody([kExprI32Const, 0x7f, kExprI32LoadMem8S, 0, 0]) .exportAs("mem_out_of_bounds"); // Call the mem_out_of_bounds function, in order to have two wasm stack frames. builder.addFunction("call_mem_out_of_bounds", kSig_i_v) .addBody([kExprCallFunction, mem_oob_func.index]) .exportAs("call_mem_out_of_bounds"); var module = builder.instantiate({mod: {func: STACK}}); (function testSimpleStack() { var expected_string = 'Error\n' + // The line numbers below will change as this test gains / loses lines.. ' at STACK (stack.js:38:11)\n' + // -- ' at main (<anonymous>:wasm-function[1]:0x86)\n' + // -- ' at testSimpleStack (stack.js:77:18)\n' + // -- ' at stack.js:79:3'; // -- module.exports.main(); assertEquals(expected_string, stripPath(stack)); })(); // For the remaining tests, collect the Callsite objects instead of just a // string: Error.prepareStackTrace = function(error, frames) { return frames; }; (function testStackFrames() { module.exports.main(); verifyStack(stack, [ // isWasm function line pos file offset funcIndex [ false, "STACK", 38, 0, "stack.js"], [ true, "main", 0, 1, null, '0x86', 1], [ false, "testStackFrames", 88, 0, "stack.js"], [ false, null, 97, 0, "stack.js"] ]); })(); (function testWasmUnreachable() { try { module.exports.exec_unreachable(); fail("expected wasm exception"); } catch (e) { assertContains("unreachable", e.message); verifyStack(e.stack, [ // isWasm function line pos file offset funcIndex [ true, "exec_unreachable", 0, 1, null, '0x8b', 2], [ false, "testWasmUnreachable", 101, 0, "stack.js"], [ false, null, 112, 0, "stack.js"] ]); } })(); (function testWasmMemOutOfBounds() { try { module.exports.call_mem_out_of_bounds(); fail("expected wasm exception"); } catch (e) { assertContains("out of bounds", e.message); verifyStack(e.stack, [ // isWasm function line pos file offset funcIndex [ true, "mem_out_of_bounds", 0, 3, null, '0x91', 3], [ true, "call_mem_out_of_bounds", 0, 1, null, '0x97', 4], [ false, "testWasmMemOutOfBounds", 116, 0, "stack.js"], [ false, null, 128, 0, "stack.js"] ]); } })(); (function testStackOverflow() { print("testStackOverflow"); var builder = new WasmModuleBuilder(); var sig_index = builder.addType(kSig_v_v); builder.addFunction("recursion", sig_index) .addBody([ kExprI32Const, 0, kExprCallIndirect, sig_index, kTableZero ]) .exportFunc(); builder.appendToTable([0]); try { builder.instantiate().exports.recursion(); fail("expected wasm exception"); } catch (e) { assertEquals("Maximum call stack size exceeded", e.message, "trap reason"); assertTrue(e.stack.length >= 4, "expected at least 4 stack entries"); verifyStack(e.stack.splice(0, 4), [ // isWasm function line pos file offset funcIndex [ true, "recursion", 0, 0, null, '0x34', 0], [ true, "recursion", 0, 3, null, '0x37', 0], [ true, "recursion", 0, 3, null, '0x37', 0], [ true, "recursion", 0, 3, null, '0x37', 0] ]); } })(); (function testBigOffset() { print('testBigOffset'); var builder = new WasmModuleBuilder(); let body = [kExprI32Const, 0, kExprI32Add]; while (body.length <= 65536) body = body.concat(body); body.unshift(kExprI32Const, 0); body.push(kExprUnreachable); let unreachable_pos = body.length - 1; builder.addFunction('main', kSig_v_v).addBody(body).exportFunc(); try { builder.instantiate().exports.main(); fail('expected wasm exception'); } catch (e) { assertEquals('unreachable', e.message, 'trap reason'); let hexOffset = '0x' + (unreachable_pos + 0x25).toString(16); verifyStack(e.stack, [ // isWasm function line pos file offset funcIndex [ true, 'main', 0, unreachable_pos + 1, null, hexOffset, 0], [ false, 'testBigOffset', 172, 0, 'stack.js'], [ false, null, 184, 0, 'stack.js'] ]); } })();
{ "content_hash": "9fc8b0ba47c28157d95e4ce799b22294", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 93, "avg_line_length": 34.87640449438202, "alnum_prop": 0.567493556701031, "repo_name": "youtube/cobalt", "id": "1f3b8146dab52a77725dd2a0a00a854d3ae5d5c6", "size": "6422", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/v8/test/mjsunit/wasm/stack.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
class Admin::DeliveriesController < AdminController before_action :set_delivery, only: [:show, :edit, :update, :destroy] set_tab :deliveries # GET /admin/deliveries # GET /admin/deliveries.json def index params[:delivery] ||= {} @deliveries = Delivery.includes(:custom).order(signed_at: :desc) if params[:delivery][:username].present? if params[:username_like_match] #changed by kailaichao, 不需要关联custom,因为delivery的receiver等于custom的username或者mobile # @deliveries = @deliveries.includes(:custom) # .where('customs.username like ?', "%#{params[:delivery][:username]}%") # .references(:customs) # end change @deliveries = @deliveries.where('reciever like ?', "%#{params[:delivery][:username]}%") else #changed by kailaichao, 不需要关联custom,因为delivery的receiver等于custom的username或者mobile # @deliveries = @deliveries.includes(:custom) # .where('customs.username = ?', params[:delivery][:username]) # .references(:customs) # end change @deliveries = @deliveries.where('reciever = ?', params[:delivery][:username]) end end # 新增了验证码快件类型,即手机用户,手机用户都是自提 if params[:need_service].present? if params[:need_service] == "2" @deliveries = @deliveries.where.not(verify_code: nil) else @deliveries = @deliveries.where(need_service: params[:need_service] == '1') end end #todo timezone https://ruby-china.org/topics/3254 @deliveries = @deliveries.after_day(params[:delivery][:after_date], :created_at) .before_day(params[:delivery][:before_date], :created_at) @deliveries = @deliveries.includes(:station).stations_match( province: params[:province], city: params[:city], district: params[:district], service_code: params[:delivery][:service_code] ) if params[:signed].present? @deliveries = @deliveries.where(status: 4) end @deliveries = @deliveries.includes(:station).page params[:page] end # GET /admin/deliveries/1 # GET /admin/deliveries/1.json def show end # GET /admin/deliveries/new def new @delivery = Delivery.new end # GET /admin/deliveries/1/edit def edit end # POST /admin/deliveries # POST /admin/deliveries.json def create @delivery = Delivery.new(delivery_params) respond_to do |format| if @delivery.save format.html { redirect_to [:admin, @delivery], notice: '创建成功!' } format.json { render action: 'show', status: :created, location: @delivery } else format.html { render action: 'new' } format.json { render json: @delivery.errors, status: :unprocessable_entity } end end end # PATCH/PUT /admin/deliveries/1 # PATCH/PUT /admin/deliveries/1.json def update respond_to do |format| if @delivery.update(delivery_params) format.html { redirect_to [:admin, @delivery], notice: '更新成功!' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @delivery.errors, status: :unprocessable_entity } end end end # DELETE /admin/deliveries/1 # DELETE /admin/deliveries/1.json def destroy #todo 删除的话统计信息会不准,如何处理? @delivery.destroy respond_to do |format| format.html { redirect_to admin_deliveries_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_delivery @delivery = Delivery.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def delivery_params params.require(:delivery).permit(:username) end end
{ "content_hash": "7dd6eef71b339dd4d468b9964fea3fca", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 95, "avg_line_length": 30.296, "alnum_prop": 0.6464219698970161, "repo_name": "sefier/doubanfang", "id": "6046ecdb6660f08c7a3a6a85dd111f5b5d51f8b9", "size": "3945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/admin/deliveries_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "125984" }, { "name": "CoffeeScript", "bytes": "1117" }, { "name": "HTML", "bytes": "162817" }, { "name": "JavaScript", "bytes": "6361" }, { "name": "Ruby", "bytes": "204934" }, { "name": "Shell", "bytes": "1257" } ], "symlink_target": "" }
#ifndef __LAYOUT_H #define __LAYOUT_H #include <math.h> #ifndef __cplusplus #include <stdbool.h> #endif // Not defined in MSVC++ #ifndef NAN static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; #define NAN (*(const float *)__nan) #endif #define CSS_UNDEFINED NAN typedef enum { CSS_DIRECTION_INHERIT = 0, CSS_DIRECTION_LTR, CSS_DIRECTION_RTL } css_direction_t; typedef enum { CSS_FLEX_DIRECTION_COLUMN = 0, CSS_FLEX_DIRECTION_COLUMN_REVERSE, CSS_FLEX_DIRECTION_ROW, CSS_FLEX_DIRECTION_ROW_REVERSE } css_flex_direction_t; typedef enum { CSS_JUSTIFY_PADDING = 0, // Just here so it lines up with CSS_ALIGN CSS_JUSTIFY_FLEX_START, CSS_JUSTIFY_CENTER, CSS_JUSTIFY_FLEX_END, CSS_JUSTIFY_SPACE_BETWEEN, CSS_JUSTIFY_SPACE_AROUND } css_justify_t; // Note: auto is only a valid value for alignSelf. It is NOT a valid value for // alignItems. typedef enum { CSS_ALIGN_AUTO = 0, CSS_ALIGN_FLEX_START, CSS_ALIGN_CENTER, CSS_ALIGN_FLEX_END, CSS_ALIGN_STRETCH } css_align_t; typedef enum { CSS_POSITION_RELATIVE = 0, CSS_POSITION_ABSOLUTE } css_position_type_t; typedef enum { CSS_NOWRAP = 0, CSS_WRAP } css_wrap_type_t; // Note: left and top are shared between position[2] and position[4], so // they have to be before right and bottom. typedef enum { CSS_LEFT = 0, CSS_TOP, CSS_RIGHT, CSS_BOTTOM, CSS_START, CSS_END, CSS_POSITION_COUNT } css_position_t; typedef enum { CSS_WIDTH = 0, CSS_HEIGHT } css_dimension_t; typedef struct { float position[4]; float dimensions[2]; css_direction_t direction; // Instead of recomputing the entire layout every single time, we // cache some information to break early when nothing changed bool should_update; float last_requested_dimensions[2]; float last_parent_max_width; float last_dimensions[2]; float last_position[2]; css_direction_t last_direction; } css_layout_t; typedef struct { float dimensions[2]; } css_dim_t; typedef struct { css_direction_t direction; css_flex_direction_t flex_direction; css_justify_t justify_content; css_align_t align_content; css_align_t align_items; css_align_t align_self; css_position_type_t position_type; css_wrap_type_t flex_wrap; float flex; float margin[6]; float position[4]; /** * You should skip all the rules that contain negative values for the * following attributes. For example: * {padding: 10, paddingLeft: -5} * should output: * {left: 10 ...} * the following two are incorrect: * {left: -5 ...} * {left: 0 ...} */ float padding[6]; float border[6]; float dimensions[2]; float minDimensions[2]; float maxDimensions[2]; } css_style_t; typedef struct css_node { css_style_t style; css_layout_t layout; int children_count; int line_index; css_dim_t (*measure)(void *context, float width); void (*print)(void *context); struct css_node* (*get_child)(void *context, int i); bool (*is_dirty)(void *context); void *context; } css_node_t; // Lifecycle of nodes and children css_node_t *new_css_node(void); void init_css_node(css_node_t *node); void free_css_node(css_node_t *node); // Print utilities typedef enum { CSS_PRINT_LAYOUT = 1, CSS_PRINT_STYLE = 2, CSS_PRINT_CHILDREN = 4, } css_print_options_t; void print_css_node(css_node_t *node, css_print_options_t options); // Function that computes the layout! void layoutNode(css_node_t *node, float maxWidth, css_direction_t parentDirection); bool isUndefined(float value); #endif
{ "content_hash": "93bdee03021655507dea9c4d53446099", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 83, "avg_line_length": 22.414012738853504, "alnum_prop": 0.6928104575163399, "repo_name": "judofyr/ImbaKit", "id": "81fb24bc5e97fb69245eea67ef8cca0276dd921e", "size": "3819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pod/Deps/Layout.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "46313" }, { "name": "Objective-C", "bytes": "9052" }, { "name": "Ruby", "bytes": "794" } ], "symlink_target": "" }
/** * Module dependencies. */ var express = require('express') , user = require('./lib/user') , game = require('./lib/game') , auth = require('./lib/auth') , http = require('http') , cors = require('cors') , SessionStore = require('connect-mongo-store')(express) , passportSocketIo = require("passport.socketio") , passport = require("passport") , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy , path = require('path'); var app = express(); var server = http.createServer(app); var io = require('socket.io').listen(server); var conf = require('./conf'); var sessionStore = new SessionStore(conf.sessionStoreURL,conf.sessionStoreOptions); // all environments var User = require('./lib/persistence').User; app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(cors({origin: '*'})); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({secret:conf.cookieSecret,store: sessionStore, cookie: {httpOnly: false}})); app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); passport.use(new GoogleStrategy(conf.googleOAuth, function(accessToken, refreshToken, profile, done) { User.findOne({'provider':profile.provider,'id':profile.id}, function (err, user) { console.log('found',profile._json.email); if (!user) { user = new User(profile); console.log('created',user); } user.provider = profile.provider user.id = profile.id; user.verified_email = profile._json.verified_email; user.name = profile._json.name; user.family_name = profile._json.family_name; user.given_name = profile._json.given_name; user.middle_name = profile._json.middle_name; user.email = profile._json.email; user.picture = profile._json.picture; user.gender = profile._json.gender; user.locale = profile._json.locale; user.token = accessToken; user.lastActive = new Date().getTime(); user.save( function (err, user, num) { if (err) { console.log('error saving token.'); } else { console.log('updated user',user); } }); process.nextTick(function () { return done(null,profile); }); }); } )); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } var authParams = {scope: [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ]}; var googlePrepare = passport.authenticate('google', authParams); function myPrepare (req,res,next) { req.session.authRedirect = req.query.redirect; console.log('prepare', req.query.redirect); return googlePrepare (req,res,next); }; app.get('/auth/logout', auth.logout); app.get('/api/users', user.list); app.get('/api/game/:id', game.get); app.post('/api/game', game.createGame); app.get('/api/game', game.list); app.get('/auth', function (req,res) { res.json(req.user);} ); app.get('/auth/google', myPrepare); app.get('/auth/google/callback', passport.authenticate('google'), auth.googleSignInCallback); server.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); io.sockets.on('connection', game.setupConnection); io.set('log level', 2); var utils = require ('./node_modules/express/node_modules/connect/lib/utils'); // set authorization for socket.io io.set('authorization', myAuthorizer(passportSocketIo.authorize({ cookieParser: express.cookieParser, passport: passport, // user serialization fails without this, mystical? key: 'connect.sid', secret: conf.cookieSecret, store: sessionStore, success: onAuthorizeSuccess, fail: onAuthorizeFail, }))); function myAuthorizer (fn) { // We need to manually parse signed cookie in query because of CORS. return function(data, accept) { // There is a bug in connect that make + int ' ' in cookies. // var sid = query.session_id; // workaround: "/socket.io/1/?session_id=s:9watfbDjRha_IkJG0EpWBuOe.SrbK3r7IG+Yvg/pCmGu2RGoWKs5O9HftSehugmkg3uA&t=1393450474684" var sid = (data.url.split('session_id=')[1]).split('&t=')[0]; if (sid && sid.substring(0,2) == 's:') { data.query.session_id = utils.parseSignedCookie(sid,conf.cookieSecret); } console.log('socket io auth',sid); console.log('=>',data.query.session_id); return fn(data, accept); } } function onAuthorizeSuccess(data, accept) { console.log('successful connection to socket.io'); // The accept-callback still allows us to decide whether to // accept the connection or not. accept(null, true); } function onAuthorizeFail(data, message, error, accept) { console.log('failed connection to socket.io:', message); if (error) { throw new Error(message); } // We use this callback to log all of our failed connections. accept(null, false); } passport.serializeUser(auth.serializeUser); passport.deserializeUser(auth.deserializeUser);
{ "content_hash": "3a42c3bb179f543813caf4112ae6a6f1", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 119, "avg_line_length": 30.436781609195403, "alnum_prop": 0.6659743202416919, "repo_name": "juhovuori/webgo", "id": "a4aaf417005b2c99bc00d73c0d3b242f92252ccd", "size": "5296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4324" }, { "name": "JavaScript", "bytes": "108058" } ], "symlink_target": "" }
<?php return array( 'does_not_exist' => 'Product does not exist.', 'create' => array( 'error' => 'Product was not created, please try again.', 'success' => 'Product created successfully.' ), 'update' => array( 'error' => 'Product was not updated, please try again', 'success' => 'Product updated successfully.' ), 'delete' => array( 'error' => 'There was an issue deleting the Product. Please try again.', 'success' => 'The Product was deleted successfully.' ) );
{ "content_hash": "3a2bb14357e4080036e31a6215d35c82", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 76, "avg_line_length": 22.5, "alnum_prop": 0.6323232323232323, "repo_name": "Askedio/LaravelCP-v1", "id": "9e9f72334136e745d8eb8d1907b74ffea90e4b02", "size": "495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/lang/en/admin/products/messages.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "470250" }, { "name": "HTML", "bytes": "890380" }, { "name": "JavaScript", "bytes": "140906" }, { "name": "PHP", "bytes": "327851" } ], "symlink_target": "" }
/* @ 0xCCCCCCCC */ #include "blocking_queue_with_nt_cond.h" #include <iostream> #include <random> #include <thread> // We skip any possible wrappers and manipulate on raw Windows API level. MTQueue::MTQueue(size_t capacity) : capacity_(capacity) { InitializeCriticalSection(&queue_mutex_); InitializeConditionVariable(&not_empty_); InitializeConditionVariable(&not_full_); } MTQueue::~MTQueue() { DeleteCriticalSection(&queue_mutex_); } void MTQueue::Put(int data) { auto tid = std::this_thread::get_id(); EnterCriticalSection(&queue_mutex_); while (full()) { std::cout << "Queue is full; block thread " << tid << std::endl; SleepConditionVariableCS(&not_full_, &queue_mutex_, INFINITE); } std::cout << "Thread " << tid << " enqueue " << data << std::endl; queue_.push(data); LeaveCriticalSection(&queue_mutex_); WakeConditionVariable(&not_empty_); } int MTQueue::Pop() { auto tid = std::this_thread::get_id(); EnterCriticalSection(&queue_mutex_); while (empty()) { std::cout << "Queue is empty; block thread " << tid << std::endl; SleepConditionVariableCS(&not_empty_, &queue_mutex_, INFINITE); } int data = queue_.back(); queue_.pop(); std::cout << "Thread " << tid << " retrieve data " << data << std::endl; LeaveCriticalSection(&queue_mutex_); WakeConditionVariable(&not_full_); return data; } // Both not thread-safe bool MTQueue::empty() const { return queue_.empty(); } bool MTQueue::full() const { return queue_.size() >= capacity_; } // -*- test stub code -*- constexpr size_t kCap = 10; void Produce(MTQueue& mtq) { std::random_device rd; std::default_random_engine engine (rd()); std::uniform_int_distribution<> dist(1, 1000); for (size_t i = 0; i < kCap * 2; ++i) { mtq.Put(dist(engine)); std::this_thread::sleep_for(std::chrono::milliseconds(300)); } for (size_t i = 0; i < kCap * 2; ++i) { mtq.Put(dist(engine)); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } // Signal to exit. mtq.Put(-1); mtq.Put(-1); } void Consumer(MTQueue& mtq) { // Stage 1 for (size_t i = 0; i < 8; ++i) { mtq.Pop(); std::this_thread::sleep_for(std::chrono::milliseconds(1500)); } // Stage 2 while (true) { auto data = mtq.Pop(); if (data == -1) { std::cout << "Consumer exit!" << std::endl; return; } std::this_thread::sleep_for(std::chrono::milliseconds(300)); } } void TestMTQueue() { MTQueue mtq(kCap); std::thread producer(Produce, std::ref(mtq)); std::thread consumers[2] {std::thread(Consumer, std::ref(mtq)), std::thread(Consumer, std::ref(mtq))}; producer.join(); consumers[0].join(); consumers[1].join(); std::cout << "All complete!" << std::endl; }
{ "content_hash": "69a4bf9c5db51d900b31deaad0f3fb5c", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 76, "avg_line_length": 21.442028985507246, "alnum_prop": 0.5839810746873944, "repo_name": "kingsamchen/Eureka", "id": "246a78300aa3931c3024ae6c7528a25437ce308c", "size": "2959", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Books/WindowsSystemProgramming/advanced_thread_synchronization/blocking_queue_with_nt_cond.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "320" }, { "name": "Assembly", "bytes": "1523" }, { "name": "C", "bytes": "115900" }, { "name": "C#", "bytes": "21241" }, { "name": "C++", "bytes": "1125565" }, { "name": "CMake", "bytes": "645800" }, { "name": "Dockerfile", "bytes": "717" }, { "name": "Go", "bytes": "111089" }, { "name": "HTML", "bytes": "3869" }, { "name": "Java", "bytes": "101720" }, { "name": "Makefile", "bytes": "110" }, { "name": "PowerShell", "bytes": "9136" }, { "name": "Python", "bytes": "210011" }, { "name": "Shell", "bytes": "9338" } ], "symlink_target": "" }
import get from 'lodash/get'; import { DisplayModes } from '../consts'; /** * Return page title: * “Style Guide Title” for all components view; * “Component Name — Style Guide Title” for isolated component or example view. * “Section Name — Style Guide Title” for isolated section view. * * @param {object} sections * @param {string} baseTitle * @param {string} displayMode * @return {string} */ export default function getPageTitle(sections, baseTitle, displayMode) { if (displayMode === DisplayModes.notFound) { return 'Page not found'; } if (sections.length) { if ( displayMode === DisplayModes.component || (displayMode === DisplayModes.example && sections[0].components) ) { const name = get(sections[0], 'components.0.name', sections[0].name); return `${name} — ${baseTitle}`; } else if (displayMode === DisplayModes.section || displayMode === DisplayModes.example) { return `${sections[0].name} — ${baseTitle}`; } } return baseTitle; }
{ "content_hash": "8a6eda8b19420df217c06615e5c644d8", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 92, "avg_line_length": 31.741935483870968, "alnum_prop": 0.6808943089430894, "repo_name": "bluetidepro/react-styleguidist", "id": "38f02ef3d711e0ff2120d8e87746ad5841a000b4", "size": "1004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils/getPageTitle.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "374709" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imgItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:src="@drawable/default_image" > </ImageView> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1.0" android:orientation="vertical" android:paddingTop="5dp" android:paddingRight="5dp" android:paddingLeft="5dp" > <TextView android:id="@+id/txtItemName" android:text="[Task Name]" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:singleLine="true" android:ellipsize="end" > </TextView> <TextView android:id="@+id/txtItemInfo" android:text="[Task Info]" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" > </TextView> </LinearLayout> <CheckBox android:id="@+id/chkCompleted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" > </CheckBox> </LinearLayout>
{ "content_hash": "934889e122e558aad43761134b3bfbf7", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 59, "avg_line_length": 26, "alnum_prop": 0.7066365007541479, "repo_name": "hanguyenhuu/DTUI_201105_Android", "id": "5857ae2cf600117ce579346d197508ede528d2c0", "size": "1326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout/view_task.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "208920" } ], "symlink_target": "" }
<?php namespace Opencasts\Exceptions; use Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ HttpException::class, ModelNotFoundException::class, ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { if ($e instanceof ModelNotFoundException) { $e = new NotFoundHttpException($e->getMessage(), $e); } return parent::render($request, $e); } }
{ "content_hash": "088f5764944b793f5072ac253e20c719", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 71, "avg_line_length": 24.84313725490196, "alnum_prop": 0.6377269139700079, "repo_name": "andela-doladosu/opencasts", "id": "24b90312192c379810c90b71dad636a8ac6ab6b2", "size": "1267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Exceptions/Handler.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "72" }, { "name": "JavaScript", "bytes": "4012" }, { "name": "PHP", "bytes": "101427" } ], "symlink_target": "" }
package org.routeservice.controller; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.routeservice.entity.*; import org.routeservice.service.AuthenticationService; import org.routeservice.service.PersistenceService; import static org.hamcrest.core.Is.is;import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.mockito.Matchers.any; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class FilterFindingsControllerTest { private AuthenticationService authenticationService; private PersistenceService persistenceService; private FilterFindingsController filterFindingsController; private MockMvc mockMvc; private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); Route exampleRoute ; AdditionalInfo exampleAdditionalInfo; ProblemDescription exampleProblemDescription; private List<FilterFindings> findings; private Route buildExampleRoute(){ return Route.builder() .routeName("https://bla.com") .service(new ServiceInstanceEntity()) .bindingId("1") .build(); } private AdditionalInfo buildExampleAdditionalInformation(){ return AdditionalInfo.builder() .timeOfProblem(new Date(1000)) .destinationUrl("www.bla.com") .build(); } private ProblemDescription buildProblemDescription(){ return ProblemDescription.builder() .description("test") .filterEntity(new FilterEntity(1,"directory_traversal")) .build(); } @Before public void init(){ filterFindingsController = new FilterFindingsController(); authenticationService = mock(AuthenticationService.class); filterFindingsController.setAuthenticationService(authenticationService); persistenceService = mock(PersistenceService.class); filterFindingsController.setPersistenceService(persistenceService); mockMvc = MockMvcBuilders.standaloneSetup(filterFindingsController).build(); findings = new ArrayList<>(); exampleRoute = buildExampleRoute(); exampleAdditionalInfo = buildExampleAdditionalInformation(); exampleProblemDescription =buildProblemDescription(); FilterFindings find1 = FilterFindings.builder() .route(exampleRoute) .fixed(false) .additionalInfo(exampleAdditionalInfo) .problemDescription(exampleProblemDescription) .build(); findings.add(find1); } @Test public void TestGetByRoute() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(1); when(persistenceService.GetInformationByRoute(1,"https://a",null,null,0,0)).thenReturn((List)findings); mockMvc.perform(get("/finding/route/a") .header("serviceGuid","a") .header("secret","a")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$[0].route.Bound_route", is(exampleRoute.getRouteName()))) .andExpect(jsonPath("$[0].additionalInfo.Destination_url", is(exampleAdditionalInfo.getDestinationUrl()))) .andExpect(jsonPath("$[0].problemDescription.Problem", is(exampleProblemDescription.getDescription()))) .andExpect(jsonPath("$[0].problemDescription.filterEntity.Filter", is(exampleProblemDescription.getFilterEntity().getFilterName()))); } @Test public void TestGetByRouteWithNoAuthorization() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(-1); mockMvc.perform(get("/finding/route/a") .header("serviceGuid","a") .header("secret","a")) .andExpect(status().isUnauthorized()); } @Test public void TestGetByRouteWithNWrongParameters() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(1); mockMvc.perform(get("/finding/route/a") .header("serviceGuid","a") .header("secret","a").param("startDate","1")) .andExpect(status().isBadRequest()); } @Test public void TestGetBySpace() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(1); when(persistenceService.GetInformationBySpace(1,"a",null,null,0,0)).thenReturn((List)findings); mockMvc.perform(get("/finding/space/a") .header("serviceGuid","a") .header("secret","a")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$[0].route.Bound_route", is(exampleRoute.getRouteName()))) .andExpect(jsonPath("$[0].additionalInfo.Destination_url", is(exampleAdditionalInfo.getDestinationUrl()))) .andExpect(jsonPath("$[0].problemDescription.Problem", is(exampleProblemDescription.getDescription()))) .andExpect(jsonPath("$[0].problemDescription.filterEntity.Filter", is(exampleProblemDescription.getFilterEntity().getFilterName()))); } @Test public void TestGetBySpaceWithNoAuthorization() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(-1); mockMvc.perform(get("/finding/space/a") .header("serviceGuid","a") .header("secret","a")) .andExpect(status().isUnauthorized()); } @Test public void TestGetBySpaceWithNWrongParameters() throws Exception{ when(authenticationService.Authenticate(any(),any())).thenReturn(1); mockMvc.perform(get("/finding/space/a") .header("serviceGuid","a") .header("secret","a").param("startDate","1")) .andExpect(status().isBadRequest()); } }
{ "content_hash": "8374c667b89aef636ce32a57467c7430", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 149, "avg_line_length": 42.19875776397515, "alnum_prop": 0.6667647924639387, "repo_name": "cher233/route-service", "id": "ff47d34992da53f262de4558a02e0c5fd3e2bb7b", "size": "6794", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/test/java/org/routeservice/controller/FilterFindingsControllerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5043" }, { "name": "Java", "bytes": "84925" }, { "name": "Shell", "bytes": "7112" } ], "symlink_target": "" }
package qualitycheck //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // Recording is a nested struct in qualitycheck response type Recording struct { Name string `json:"Name" xml:"Name"` Remark5 int64 `json:"Remark5" xml:"Remark5"` CallTime string `json:"CallTime" xml:"CallTime"` DurationAudio int64 `json:"DurationAudio" xml:"DurationAudio"` CallId string `json:"CallId" xml:"CallId"` Caller string `json:"Caller" xml:"Caller"` Remark7 string `json:"Remark7" xml:"Remark7"` Remark9 string `json:"Remark9" xml:"Remark9"` Remark11 string `json:"Remark11" xml:"Remark11"` Remark2 string `json:"Remark2" xml:"Remark2"` Id string `json:"Id" xml:"Id"` Remark4 string `json:"Remark4" xml:"Remark4"` Duration int64 `json:"Duration" xml:"Duration"` Business string `json:"Business" xml:"Business"` DialogueSize int `json:"DialogueSize" xml:"DialogueSize"` Remark6 string `json:"Remark6" xml:"Remark6"` Remark13 string `json:"Remark13" xml:"Remark13"` Callee string `json:"Callee" xml:"Callee"` Remark1 string `json:"Remark1" xml:"Remark1"` PrimaryId string `json:"PrimaryId" xml:"PrimaryId"` CallType int `json:"CallType" xml:"CallType"` Url string `json:"Url" xml:"Url"` Remark12 string `json:"Remark12" xml:"Remark12"` Remark8 string `json:"Remark8" xml:"Remark8"` DataSetName string `json:"DataSetName" xml:"DataSetName"` Remark10 string `json:"Remark10" xml:"Remark10"` Remark3 string `json:"Remark3" xml:"Remark3"` }
{ "content_hash": "255e003adada065f74e2af19b3c0e22e", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 84, "avg_line_length": 47.702127659574465, "alnum_prop": 0.6909009812667262, "repo_name": "aliyun/alibaba-cloud-sdk-go", "id": "6419ba354632a00ad306ac3ed1ac306c59be1848", "size": "2242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/qualitycheck/struct_recording.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "734307" }, { "name": "Makefile", "bytes": "183" } ], "symlink_target": "" }
module Azure::CognitiveServices::ImageSearch::V1_0 module Models # # A utility class that serves as the umbrella for a number of 'intangible' # things such as quantities, structured values, etc. # class Intangible < Thing include MsRestAzure def initialize @_type = "Intangible" end attr_accessor :_type # # Mapper for Intangible class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Intangible', type: { name: 'Composite', class_name: 'Intangible', model_properties: { _type: { client_side_validation: true, required: true, serialized_name: '_type', type: { name: 'String' } }, id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, read_link: { client_side_validation: true, required: false, read_only: true, serialized_name: 'readLink', type: { name: 'String' } }, web_search_url: { client_side_validation: true, required: false, read_only: true, serialized_name: 'webSearchUrl', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, url: { client_side_validation: true, required: false, read_only: true, serialized_name: 'url', type: { name: 'String' } }, image: { client_side_validation: true, required: false, read_only: true, serialized_name: 'image', type: { name: 'Composite', class_name: 'ImageObject' } }, description: { client_side_validation: true, required: false, read_only: true, serialized_name: 'description', type: { name: 'String' } }, alternate_name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'alternateName', type: { name: 'String' } }, bing_id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'bingId', type: { name: 'String' } } } } } end end end end
{ "content_hash": "c70b3891c4d89c13c130582be28acfa1", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 78, "avg_line_length": 27.828125, "alnum_prop": 0.38433464345873103, "repo_name": "Azure/azure-sdk-for-ruby", "id": "1180e0126e29b130fc78d4a02aa95fa19cb5c8b4", "size": "3726", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/azure_cognitiveservices_imagesearch/lib/1.0/generated/azure_cognitiveservices_imagesearch/models/intangible.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
@interface ViewController : UIViewController @end
{ "content_hash": "582fd98a695095ad7de9231db2b2f0aa", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 44, "avg_line_length": 17, "alnum_prop": 0.8235294117647058, "repo_name": "Zedenem/ExpandableTableView", "id": "521933db2966b6069afc0d7987cdf4eaa6875061", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo_project/ExpandableTableView/ViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "16417" } ], "symlink_target": "" }
import sys import os from os.path import dirname, abspath from optparse import OptionParser import django from django.conf import settings, global_settings # For convenience configure settings if they are not pre-configured or if we # haven't been provided settings to use by environment variable. if not settings.configured and not os.environ.get('DJANGO_SETTINGS_MODULE'): settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, STATIC_ROOT='static/', INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django.contrib.humanize', 'haystack', 'slimbb', ), MIDDLEWARE_CLASSES=[ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.locale.LocaleMiddleware', 'slimbb.middleware.TimezoneMiddleware', ], TEMPLATES=[{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {'context_processors': list(global_settings.TEMPLATE_CONTEXT_PROCESSORS) + [ 'slimbb.context_processors.forum_settings'], } }], TIME_ZONE = 'Europe/Kiev', USE_TZ = True, PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF='slimbb.tests.urls', DEBUG=False, SITE_ID=1, HAYSTACK_CONNECTIONS={ 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine' } }, ) django.setup() from django.test.runner import DiscoverRunner def runtests(*test_args, **kwargs): if not test_args: test_args = ['slimbb'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) test_runner = DiscoverRunner(verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast')) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--failfast', action='store_true', default=False, dest='failfast') (options, args) = parser.parse_args() runtests(failfast=options.failfast, *args)
{ "content_hash": "585298e25e494f7adc0534f87db187a9", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 149, "avg_line_length": 35.523809523809526, "alnum_prop": 0.5918230563002681, "repo_name": "hsoft/slimbb", "id": "2be7e08f881b213520aed5c2d3c1940c81b682e1", "size": "3006", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "runtests.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "34173" }, { "name": "HTML", "bytes": "44779" }, { "name": "JavaScript", "bytes": "1767" }, { "name": "Makefile", "bytes": "280" }, { "name": "Python", "bytes": "111142" } ], "symlink_target": "" }
/** * Andrea Tino - 2016 * compilerOptions.ts */ namespace organon.theorygen { /** * Options for compiling. */ export interface CompilerOptions { silentErrors?: boolean; } }
{ "content_hash": "1d1bc2a60c36294bd76b01775d0de55e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 36, "avg_line_length": 14.923076923076923, "alnum_prop": 0.6391752577319587, "repo_name": "andry-tino/Organon", "id": "10ab5fd2d5636d58aa60ef28fe9fbe1de5f6b3e8", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/theorygen/compilerOptions.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Standard ML", "bytes": "47" }, { "name": "TypeScript", "bytes": "3143" } ], "symlink_target": "" }