text
stringlengths
1
1.05M
<reponame>haba-sensei/abogados /** List of void (self-closing) HTML tags. @example ``` import voidHtmlTags = require('html-tags/void'); console.log(voidHtmlTags); //=> ['area', 'base', 'br', …] ``` */ declare const voidHtmlTags: readonly string[]; export = voidHtmlTags;
const sortedArray = unsortedArray.sort((a, b) => a.age - b.age); console.log(sortedArray);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.hadoop.rdf.io.input; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat; import org.apache.hadoop.mapreduce.task.JobContextImpl; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.apache.jena.hadoop.rdf.io.HadoopIOConstants; import org.apache.jena.hadoop.rdf.io.RdfIOConstants; import org.apache.jena.hadoop.rdf.types.AbstractNodeTupleWritable; import org.junit.* ; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract node tuple input format tests * * * * @param <TValue> * @param <T> */ public abstract class AbstractNodeTupleInputFormatTests<TValue, T extends AbstractNodeTupleWritable<TValue>> { private static final Logger LOG = LoggerFactory.getLogger(AbstractNodeTupleInputFormatTests.class); protected static final int EMPTY_SIZE = 0, SMALL_SIZE = 100, LARGE_SIZE = 10000, BAD_SIZE = 100, MIXED_SIZE = 100; protected static final String EMPTY = "empty"; protected static final String SMALL = "small"; protected static final String LARGE = "large"; protected static final String BAD = "bad"; protected static final String MIXED = "mixed"; /** * Temporary folder for the tests */ @Rule public TemporaryFolder folder = new TemporaryFolder(); protected File empty, small, large, bad, mixed; /** * Prepares the inputs for the tests * * @throws IOException */ @Before public void beforeTest() throws IOException { this.prepareInputs(); } /** * Cleans up the inputs after each test */ @After public void afterTest() { // Should be unnecessary since JUnit will clean up the temporary folder // anyway but best to do this regardless if (empty != null) empty.delete(); if (small != null) small.delete(); if (large != null) large.delete(); if (bad != null) bad.delete(); if (mixed != null) mixed.delete(); } /** * Prepares a fresh configuration * * @return Configuration */ protected Configuration prepareConfiguration() { Configuration config = new Configuration(true); // Nothing else to do return config; } /** * Prepares the inputs * * @throws IOException */ protected void prepareInputs() throws IOException { String ext = this.getFileExtension(); empty = folder.newFile(EMPTY + ext); this.generateTuples(empty, EMPTY_SIZE); small = folder.newFile(SMALL + ext); this.generateTuples(small, SMALL_SIZE); large = folder.newFile(LARGE + ext); this.generateTuples(large, LARGE_SIZE); bad = folder.newFile(BAD + ext); this.generateBadTuples(bad, BAD_SIZE); mixed = folder.newFile(MIXED + ext); this.generateMixedTuples(mixed, MIXED_SIZE); } /** * Gets the extra file extension to add to the filenames * * @return File extension */ protected abstract String getFileExtension(); /** * Generates tuples used for tests * * @param f * File * @param num * Number of tuples to generate * @throws IOException */ protected final void generateTuples(File f, int num) throws IOException { this.generateTuples(this.getOutputStream(f), num); } /** * Gets the output stream to use for generating tuples * * @param f * File * @return Output Stream * @throws IOException */ protected OutputStream getOutputStream(File f) throws IOException { return new FileOutputStream(f, false); } /** * Generates tuples used for tests * * @param output * Output Stream to write to * @param num * Number of tuples to generate * @throws IOException */ protected abstract void generateTuples(OutputStream output, int num) throws IOException; /** * Generates bad tuples used for tests * * @param f * File * @param num * Number of bad tuples to generate * @throws IOException */ protected final void generateBadTuples(File f, int num) throws IOException { this.generateBadTuples(this.getOutputStream(f), num); } /** * Generates bad tuples used for tests * * @param output * Output Stream to write to * @param num * Number of bad tuples to generate * @throws IOException */ protected abstract void generateBadTuples(OutputStream output, int num) throws IOException; /** * Generates a mixture of good and bad tuples used for tests * * @param f * File * @param num * Number of tuples to generate, they should be a 50/50 mix of * good and bad tuples * @throws IOException */ protected final void generateMixedTuples(File f, int num) throws IOException { this.generateMixedTuples(this.getOutputStream(f), num); } /** * Generates a mixture of good and bad tuples used for tests * * @param output * Output Stream to write to * @param num * Number of tuples to generate, they should be a 50/50 mix of * good and bad tuples * @throws IOException */ protected abstract void generateMixedTuples(OutputStream output, int num) throws IOException; /** * Adds an input path to the job configuration * * @param f * File * @param config * Configuration * @param job * Job * @throws IOException */ protected void addInputPath(File f, Configuration config, Job job) throws IOException { FileSystem fs = FileSystem.getLocal(config); Path inputPath = fs.makeQualified(new Path(f.getAbsolutePath())); FileInputFormat.addInputPath(job, inputPath); } protected final int countTuples(RecordReader<LongWritable, T> reader) throws IOException, InterruptedException { int count = 0; // Check initial progress LOG.info(String.format("Initial Reported Progress %f", reader.getProgress())); float progress = reader.getProgress(); if (Float.compare(0.0f, progress) == 0) { Assert.assertEquals(0.0d, reader.getProgress(), 0.0d); } else if (Float.compare(1.0f, progress) == 0) { // If reader is reported 1.0 straight away then we expect there to // be no key values Assert.assertEquals(1.0d, reader.getProgress(), 0.0d); Assert.assertFalse(reader.nextKeyValue()); } else { Assert.fail(String.format( "Expected progress of 0.0 or 1.0 before reader has been accessed for first time but got %f", progress)); } // Count tuples boolean debug = LOG.isDebugEnabled(); while (reader.nextKeyValue()) { count++; progress = reader.getProgress(); if (debug) LOG.debug(String.format("Current Reported Progress %f", progress)); Assert.assertTrue(String.format("Progress should be in the range 0.0 < p <= 1.0 but got %f", progress), progress > 0.0f && progress <= 1.0f); } reader.close(); LOG.info(String.format("Got %d tuples from this record reader", count)); // Check final progress LOG.info(String.format("Final Reported Progress %f", reader.getProgress())); Assert.assertEquals(1.0d, reader.getProgress(), 0.0d); return count; } protected final void checkTuples(RecordReader<LongWritable, T> reader, int expected) throws IOException, InterruptedException { Assert.assertEquals(expected, this.countTuples(reader)); } /** * Runs a test with a single input * * @param input * Input * @param expectedTuples * Expected tuples * @throws IOException * @throws InterruptedException */ protected final void testSingleInput(File input, int expectedSplits, int expectedTuples) throws IOException, InterruptedException { // Prepare configuration Configuration config = this.prepareConfiguration(); this.testSingleInput(config, input, expectedSplits, expectedTuples); } /** * Runs a test with a single input * * @param config * Configuration * @param input * Input * @param expectedTuples * Expected tuples * @throws IOException * @throws InterruptedException */ protected final void testSingleInput(Configuration config, File input, int expectedSplits, int expectedTuples) throws IOException, InterruptedException { // Set up fake job InputFormat<LongWritable, T> inputFormat = this.getInputFormat(); Job job = Job.getInstance(config); job.setInputFormatClass(inputFormat.getClass()); this.addInputPath(input, job.getConfiguration(), job); JobContext context = new JobContextImpl(job.getConfiguration(), job.getJobID()); Assert.assertEquals(1, FileInputFormat.getInputPaths(context).length); NLineInputFormat.setNumLinesPerSplit(job, LARGE_SIZE); // Check splits List<InputSplit> splits = inputFormat.getSplits(context); Assert.assertEquals(expectedSplits, splits.size()); // Check tuples for (InputSplit split : splits) { TaskAttemptContext taskContext = new TaskAttemptContextImpl(job.getConfiguration(), new TaskAttemptID()); RecordReader<LongWritable, T> reader = inputFormat.createRecordReader(split, taskContext); reader.initialize(split, taskContext); this.checkTuples(reader, expectedTuples); } } protected abstract InputFormat<LongWritable, T> getInputFormat(); /** * Basic tuples input test * * @throws IOException * @throws InterruptedException */ @Test public final void single_input_01() throws IOException, InterruptedException { testSingleInput(empty, this.canSplitInputs() ? 0 : 1, EMPTY_SIZE); } /** * Basic tuples input test * * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ @Test public final void single_input_02() throws IOException, InterruptedException { testSingleInput(small, 1, SMALL_SIZE); } /** * Basic tuples input test * * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ @Test public final void single_input_03() throws IOException, InterruptedException { testSingleInput(large, 1, LARGE_SIZE); } /** * Basic tuples input test * * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ @Test public final void single_input_04() throws IOException, InterruptedException { testSingleInput(bad, 1, 0); } /** * Basic tuples input test * * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ @Test public final void single_input_05() throws IOException, InterruptedException { // JSON-LD overrides this because in JSON-LD parsing a bad document gives no triples. int x = single_input_05_expected() ; testSingleInput(mixed, 1, x); } /** Results exected for test single_input_05 */ protected int single_input_05_expected() { return MIXED_SIZE / 2 ; } /** * Tests behaviour when ignoring bad tuples is disabled * * @throws InterruptedException * @throws IOException */ @Test(expected = IOException.class) public final void fail_on_bad_input_01() throws IOException, InterruptedException { Configuration config = this.prepareConfiguration(); config.setBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, false); Assert.assertFalse(config.getBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, true)); testSingleInput(config, bad, 1, 0); } /** * Tests behaviour when ignoring bad tuples is disabled * * @throws InterruptedException * @throws IOException */ @Test(expected = IOException.class) public final void fail_on_bad_input_02() throws IOException, InterruptedException { Configuration config = this.prepareConfiguration(); config.setBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, false); Assert.assertFalse(config.getBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, true)); testSingleInput(config, mixed, 1, MIXED_SIZE / 2); } /** * Runs a multiple input test * * @param inputs * Inputs * @param expectedSplits * Number of splits expected * @param expectedTuples * Number of tuples expected * @throws IOException * @throws InterruptedException */ protected final void testMultipleInputs(File[] inputs, int expectedSplits, int expectedTuples) throws IOException, InterruptedException { // Prepare configuration and inputs Configuration config = this.prepareConfiguration(); // Set up fake job InputFormat<LongWritable, T> inputFormat = this.getInputFormat(); Job job = Job.getInstance(config); job.setInputFormatClass(inputFormat.getClass()); for (File input : inputs) { this.addInputPath(input, job.getConfiguration(), job); } JobContext context = new JobContextImpl(job.getConfiguration(), job.getJobID()); Assert.assertEquals(inputs.length, FileInputFormat.getInputPaths(context).length); NLineInputFormat.setNumLinesPerSplit(job, expectedTuples); // Check splits List<InputSplit> splits = inputFormat.getSplits(context); Assert.assertEquals(expectedSplits, splits.size()); // Check tuples int count = 0; for (InputSplit split : splits) { TaskAttemptContext taskContext = new TaskAttemptContextImpl(job.getConfiguration(), new TaskAttemptID()); RecordReader<LongWritable, T> reader = inputFormat.createRecordReader(split, taskContext); reader.initialize(split, taskContext); count += this.countTuples(reader); } Assert.assertEquals(expectedTuples, count); } /** * tuples test with multiple inputs * * @throws IOException * @throws InterruptedException */ @Test public final void multiple_inputs_01() throws IOException, InterruptedException { testMultipleInputs(new File[] { empty, small, large }, this.canSplitInputs() ? 2 : 3, EMPTY_SIZE + SMALL_SIZE + LARGE_SIZE); } /** * tuples test with multiple inputs * * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ @Test public final void multiple_inputs_02() throws IOException, InterruptedException { int expectedTriples = multiple_inputs_02_expected() ; testMultipleInputs(new File[] { folder.getRoot() }, this.canSplitInputs() ? 4 : 5, expectedTriples); } /** Results exected for test multiple_inputs_02. * JSON_LD has different characteristics on bad documents. * See {@link #single_input_05}. */ protected int multiple_inputs_02_expected() { return EMPTY_SIZE + SMALL_SIZE + LARGE_SIZE + (MIXED_SIZE / 2) ; } protected final void testSplitInputs(Configuration config, File[] inputs, int expectedSplits, int expectedTuples) throws IOException, InterruptedException { // Set up fake job InputFormat<LongWritable, T> inputFormat = this.getInputFormat(); Job job = Job.getInstance(config); job.setInputFormatClass(inputFormat.getClass()); for (File input : inputs) { this.addInputPath(input, job.getConfiguration(), job); } JobContext context = new JobContextImpl(job.getConfiguration(), job.getJobID()); Assert.assertEquals(inputs.length, FileInputFormat.getInputPaths(context).length); // Check splits List<InputSplit> splits = inputFormat.getSplits(context); Assert.assertEquals(expectedSplits, splits.size()); // Check tuples int count = 0; for (InputSplit split : splits) { // Validate split Assert.assertTrue(this.isValidSplit(split, config)); // Read split TaskAttemptContext taskContext = new TaskAttemptContextImpl(job.getConfiguration(), new TaskAttemptID()); RecordReader<LongWritable, T> reader = inputFormat.createRecordReader(split, taskContext); reader.initialize(split, taskContext); count += this.countTuples(reader); } Assert.assertEquals(expectedTuples, count); } /** * Determines whether an input split is valid * * @param split * Input split * @return True if a valid split, false otherwise */ protected boolean isValidSplit(InputSplit split, Configuration config) { return split instanceof FileSplit; } /** * Indicates whether inputs can be split, defaults to true * * @return Whether inputs can be split */ protected boolean canSplitInputs() { return true; } /** * Tests for input splitting * * @throws IOException * @throws InterruptedException * @throws ClassNotFoundException */ @Test public final void split_input_01() throws IOException, InterruptedException { Assume.assumeTrue(this.canSplitInputs()); Configuration config = this.prepareConfiguration(); config.setBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, false); Assert.assertEquals(Integer.MAX_VALUE, config.getInt(HadoopIOConstants.MAX_LINE_LENGTH, Integer.MAX_VALUE)); this.testSplitInputs(config, new File[] { small }, 100, SMALL_SIZE); } /** * Tests for input splitting * * @throws IOException * @throws InterruptedException * @throws ClassNotFoundException */ @Test public final void split_input_02() throws IOException, InterruptedException { Assume.assumeTrue(this.canSplitInputs()); Configuration config = this.prepareConfiguration(); config.setBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, false); config.setLong(NLineInputFormat.LINES_PER_MAP, 10); Assert.assertEquals(Integer.MAX_VALUE, config.getInt(HadoopIOConstants.MAX_LINE_LENGTH, Integer.MAX_VALUE)); this.testSplitInputs(config, new File[] { small }, 10, SMALL_SIZE); } /** * Tests for input splitting * * @throws IOException * @throws InterruptedException * @throws ClassNotFoundException */ @Test public final void split_input_03() throws IOException, InterruptedException { Assume.assumeTrue(this.canSplitInputs()); Configuration config = this.prepareConfiguration(); config.setBoolean(RdfIOConstants.INPUT_IGNORE_BAD_TUPLES, false); config.setLong(NLineInputFormat.LINES_PER_MAP, 100); Assert.assertEquals(Integer.MAX_VALUE, config.getInt(HadoopIOConstants.MAX_LINE_LENGTH, Integer.MAX_VALUE)); this.testSplitInputs(config, new File[] { large }, 100, LARGE_SIZE); } }
<filename>src/fixate/drivers/lcr/__init__.py """ lcr is the lcr meter driver. Use lcr.open to connect to a connected digital multi meter Functions are dictacted by the metaclass in helper.py """ from fixate.drivers.lcr.helper import open, LCR, TestResult
# Sets general shell options and defines environment variables. # # Smart URLs # autoload -Uz bracketed-paste-url-magic zle -N bracketed-paste bracketed-paste-url-magic autoload -Uz url-quote-magic zle -N self-insert url-quote-magic # # General # setopt COMBINING_CHARS # Combine zero-length punctuation characters (accents) # with the base character. setopt INTERACTIVE_COMMENTS # Enable comments in interactive shell. setopt RC_QUOTES # Allow 'Henry''s Garage' instead of 'Henry'\''s Garage'. unsetopt MAIL_WARNING # Don't print a warning message if a mail file has been accessed. # Allow mapping Ctrl+S and Ctrl+Q shortcuts [[ -r ${TTY:-} && -w ${TTY:-} && $+commands[stty] == 1 ]] && stty -ixon <$TTY >$TTY # # Jobs # setopt LONG_LIST_JOBS # List jobs in the long format by default. setopt AUTO_RESUME # Attempt to resume existing job before creating a new process. setopt NOTIFY # Report status of background jobs immediately. unsetopt BG_NICE # Don't run all background jobs at a lower priority. unsetopt HUP # Don't kill jobs on shell exit. unsetopt CHECK_JOBS # Don't report on jobs when shell exit. # # Termcap # if zstyle -t ':akarzim:environment:termcap' color; then export LESS_TERMCAP_mb=$'\E[01;31m' # Begins blinking. export LESS_TERMCAP_md=$'\E[01;31m' # Begins bold. export LESS_TERMCAP_me=$'\E[0m' # Ends mode. export LESS_TERMCAP_se=$'\E[0m' # Ends standout-mode. export LESS_TERMCAP_so=$'\E[00;47;30m' # Begins standout-mode. export LESS_TERMCAP_ue=$'\E[0m' # Ends underline. export LESS_TERMCAP_us=$'\E[01;32m' # Begins underline. fi
<filename>testeditor/src/main/java/org/museautomation/ui/steptask/UniqueIds.java package org.museautomation.ui.steptask; import org.museautomation.core.*; import org.museautomation.core.project.*; import org.museautomation.core.step.*; import org.museautomation.core.steptask.*; import java.util.*; /** * Ensures that each step in a SteppedTest has a unique ID (within the test). * * @author <NAME> (see LICENSE.txt for license details) */ public class UniqueIds { public static void addToStepsIfNeeded(SteppedTask task, MuseProject project) { StepConfiguration step = task.getStep(); addToStepIfNeeded(step, project, new IdTracker()); } private static void addToStepIfNeeded(StepConfiguration step, MuseProject project, IdTracker tracker) { checkAndRepairId(step, project, tracker); if (step.getStepId() == null) step.setStepId(StepIdGenerator.get(project).generateLongId()); if (step.getChildren() != null) for (StepConfiguration child : step.getChildren()) addToStepIfNeeded(child, project, tracker); } private static void checkAndRepairId(StepConfiguration step, MuseProject project, IdTracker tracker) { // upgrade tests that used the original id name. // TODO remove at some point (this was needed for 0.11 update) if (step.getMetadata() != null) { Object old_id = step.getMetadata().remove(StepConfiguration.META_ID_OLD); if (old_id != null) step.getMetadata().put(StepConfiguration.META_ID, old_id); } Long id = step.getStepId(); if (id == null) return; // nothing to repair if (tracker._existing_ids.contains(id)) { Long new_id = StepIdGenerator.get(project).generateLongId(); while (tracker._existing_ids.contains(new_id)) { StepIdGenerator.get(project).conflict(); new_id = StepIdGenerator.get(project).generateLongId(); } step.setStepId(new_id); tracker._existing_ids.add(new_id); } else tracker._existing_ids.add(id); } private static class IdTracker { Set<Long> _existing_ids = new HashSet<>(); } }
#!/bin/bash # Permission ## chmod +x secondScript.sh echo "The message from sendOutput is: $MESSAGE"
public class SelectFormFieldCell: BaseFormFieldCell<SelectFormField>, FormFieldCellSelectable { // Existing code // MARK: - Public Methods public func selectOption(_ option: String) { // Update the cell's UI to reflect the selected option // For example, update the cell's label or image based on the selected option // Notify the associated form field of the selected option guard let formField = self.formField else { // Handle the case where the form field is not set return } formField.value = option formField.delegate?.formFieldDidChangeValue(formField) } }
#!/bin/sh # Copyright (c) 2002, Intel Corporation. All rights reserved. # Created by: julie.n.fleischer REMOVE-THIS AT intel DOT com # This file is licensed under the GPL license. For the full content # of this license, see the COPYING file at the top level of this # source tree. # # Test that timer_getoverrun() returns the overrun count on success. # # This is tested implicitly via assertion 2. echo "Tested implicitly via assertion 2. Set output for status." exit 0
<filename>pdf_downloader.py<gh_stars>0 from neo4j import GraphDatabase import py2neo import urllib.request import re from youtube_api import jeb from googleapiclient.discovery import build api_key = "AIzaSyCaa-dKG3l0I4Uu-LyCH_qP611lRUl2THY" service = build('youtube','v3',developerKey=api_key) class dog: def __init__(self, uri, user, password): self._driver = GraphDatabase.driver(uri, auth=(user, password)) def add_person(self, subject,data_list): with self._driver.session() as session: session.write_transaction(self.create_obj, subject,data_list) session.write_transaction(self.match_connect, subject) session.write_transaction(self.topic_degree, subject,data_list) # session.write_transaction(self.video_connect, subject,data_list) # session.read_transaction(self.check) print("running") @staticmethod def check(tx): q1="MATCH()-[r:AHEAD_OF]->() return count(*)" nodes=tx.run(q1) print(nodes) @staticmethod def create_obj(tx,subject,data_list): subject query="CREATE(:subject{name:$subjec})" for i in range(len(data_list)): print(i) genny="'"+str(data_list[i])+"'" gon="'"+str(i)+"'" query +=","+"(:topic{name:"+genny+",subject:$match_query,degree:"+gon+"})" print(query) tx.run(query,subjec=subject,match_query=subject) @staticmethod def match_connect(tx,subject): match_querye="MATCH(x:topic{subject:$subjec}),(y:subject{name:$subjec})CREATE (x)-[:TOPIC_OF]->(y)" tx.run(match_querye,subjec=subject) @staticmethod def topic_degree(tx,subject,data_list): degree_query="" degre_match="MATCH" degre_create="CREATE" for i in range(len(data_list)): jerry="," j="x"+str(i) z="x"+str(i+1) jolly="'"+str(data_list[i])+"'" if(i+1==len(data_list)): jerry=" " degre_create=degre_create[:-1] else: degre_create +=" " +"("+j+")-[:AHEAD_OF]->("+z+")"+jerry degre_match +=" "+"("+j+":topic{name:"+jolly+",subject:$subjec})"+jerry degree_query=degre_match+degre_create print(degree_query) tx.run(degree_query,subjec=subject) # def jun(items): # query="UNWIND $mer_list as row MATCH(m:topic{name:"+filter_data+"}) CREATE(n:video{name:row.degree,topic:row.topic,id:row.id,img:row.img,title:row.title,des:row.des,duration:row.duration,views:row.view_count})-[:VIDEO_OF]->(m)" # tx.run(query,mer_list=mer_list)
<reponame>sagarc-contrail/contrail-controller #!/usr/bin/env python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # # analytics_systest.py # # System tests for analytics # import os import sys import threading threading._DummyThread._Thread__stop = lambda x: 42 import signal import gevent from gevent import monkey monkey.patch_all() import os import unittest import testtools import fixtures import socket from utils.analytics_fixture import AnalyticsFixture from utils.generator_fixture import GeneratorFixture from utils.stats_fixture import StatsFixture from mockcassandra import mockcassandra import logging import time import pycassa from pycassa.pool import ConnectionPool from pycassa.columnfamily import ColumnFamily from opserver.sandesh.viz.constants import * from sandesh_common.vns.ttypes import Module from sandesh_common.vns.constants import ModuleNames from utils.util import find_buildroot from cassandra.cluster import Cluster logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') builddir = find_buildroot(os.getcwd()) class AnalyticsTest(testtools.TestCase, fixtures.TestWithFixtures): @classmethod def setUpClass(cls): if AnalyticsTest._check_skip_test() is True: return if (os.getenv('LD_LIBRARY_PATH', '').find('build/lib') < 0): if (os.getenv('DYLD_LIBRARY_PATH', '').find('build/lib') < 0): assert(False) cls.cassandra_port = AnalyticsTest.get_free_port() mockcassandra.start_cassandra(cls.cassandra_port) @classmethod def tearDownClass(cls): if AnalyticsTest._check_skip_test() is True: return mockcassandra.stop_cassandra(cls.cassandra_port) pass def _update_analytics_start_time(self, start_time): cluster = Cluster(['127.0.0.1'], port=int(self.__class__.cassandra_port)) session = cluster.connect(COLLECTOR_KEYSPACE_CQL) query = "INSERT INTO {0} (key, \"{1}\") VALUES ('{2}', {3})".format( SYSTEM_OBJECT_TABLE, SYSTEM_OBJECT_START_TIME, SYSTEM_OBJECT_ANALYTICS, start_time) try: session.execute(query) except Exception as e: logging.error("INSERT INTO %s: Key %s Column %s Value %d " "FAILED: %s" % (SYSTEM_OBJECT_TABLE, SYSTEM_OBJECT_ANALYTICS, SYSTEM_OBJECT_START_TIME, start_time, str(e))) assert False else: cluster.shutdown() # end _update_analytics_start_time <EMAIL>('Skipping cassandra test with vizd') def test_01_startup(self): ''' This test starts redis,vizd,opserver and qed It uses the test class' cassandra instance Then it checks that the collector UVE (via redis) and syslog (via cassandra) can be accessed from opserver. ''' logging.info("%%% test_01_startup %%%") if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() return True <EMAIL>('Query query engine logs to test QE') def test_02_message_table_query(self): ''' This test starts redis,vizd,opserver and qed It uses the test class' cassandra instance Then it checks that the collector UVE (via redis) and syslog (via cassandra) can be accessed from opserver. ''' logging.info("%%% test_02_message_table_query %%%") if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() assert vizd_obj.verify_message_table_moduleid() assert vizd_obj.verify_message_table_select_uint_type() assert vizd_obj.verify_message_table_messagetype() assert vizd_obj.verify_message_table_where_or() assert vizd_obj.verify_message_table_where_and() assert vizd_obj.verify_message_table_where_prefix() assert vizd_obj.verify_message_table_filter() assert vizd_obj.verify_message_table_filter2() assert vizd_obj.verify_message_table_sort() assert vizd_obj.verify_message_table_limit() return True # end test_02_message_table_query <EMAIL>('Send/query flow stats to test QE') def test_03_flow_query(self): ''' This test starts redis,vizd,opserver and qed It uses the test class' cassandra instance Then it sends flow stats to the collector and checks if flow stats can be accessed from QE. ''' logging.info("%%% test_03_flow_query %%%") if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() # set the start time in analytics db 1 hour earlier than # the current time. For flow series test, we need to create # flow samples older than the current time. start_time = UTCTimestampUsec() - 3600 * 1000 * 1000 self._update_analytics_start_time(start_time) collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture("contrail-vrouter-agent", collectors, logging, vizd_obj.get_opserver_port(), start_time)) assert generator_obj.verify_on_setup() generator_obj.generate_flow_samples() generator_obj1 = self.useFixture( GeneratorFixture("contrail-vrouter-agent", collectors, logging, vizd_obj.get_opserver_port(), start_time, hostname=socket.gethostname() + "dup")) assert generator_obj1.verify_on_setup() generator_obj1.generate_flow_samples() generator_object = [generator_obj, generator_obj1] for obj in generator_object: assert vizd_obj.verify_flow_samples(obj) assert vizd_obj.verify_flow_table(generator_obj) assert vizd_obj.verify_flow_series_aggregation_binning(generator_object) return True # end test_03_flow_query <EMAIL>('InterVN stats using StatsOracle') def test_04_intervn_query(self): ''' This test starts redis,vizd,opserver and qed It uses the test class' cassandra instance Then it sends intervn stats to the collector and checks if intervn stats can be accessed from QE. ''' logging.info("%%% test_04_intervn_query %%%") if AnalyticsTest._check_skip_test() is True: return True # set the start time in analytics db 1 hour earlier than # the current time. For flow series test, we need to create # flow samples older than the current time. start_time = UTCTimestampUsec() - 3600 * 1000 * 1000 self._update_analytics_start_time(start_time) vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture("contrail-vrouter-agent", collectors, logging, vizd_obj.get_opserver_port(), start_time)) assert generator_obj.verify_on_setup() logging.info("Starting intervn gen " + str(UTCTimestampUsec())) generator_obj.generate_intervn() logging.info("Ending intervn gen " + str(UTCTimestampUsec())) assert vizd_obj.verify_intervn_all(generator_obj) assert vizd_obj.verify_intervn_sum(generator_obj) return True # end test_04_intervn_query <EMAIL>('Fieldname queries') def test_05_fieldname_query(self): ''' This test starts redis,vizd,opserver and qed It uses the test class' cassandra instance It then queries the stats table for messagetypes and objecttypes ''' logging.info("%%% test_05_fieldname_query %%%") start_time = UTCTimestampUsec() - 3600 * 1000 * 1000 self._update_analytics_start_time(start_time) vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture("VRouterAgent", collectors, logging, vizd_obj.get_opserver_port())) assert generator_obj.verify_on_setup() # Sends 2 different vn uves in 1 sec spacing generator_obj.generate_intervn() assert vizd_obj.verify_fieldname_messagetype() assert vizd_obj.verify_fieldname_table() return True # end test_05_fieldname_query <EMAIL>('verify send-tracebuffer') def test_06_send_tracebuffer(self): ''' This test verifies /analytics/send-tracebuffer/ REST API. Opserver publishes the request to send trace buffer to all the redis-uve instances. Collector forwards the request to the appropriate generator(s). Generator sends the tracebuffer to the Collector which then dumps the trace messages in the analytics db. Verify that the trace messages are written in the analytics db. ''' logging.info('%%% test_06_send_tracebuffer %%%') if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port, collector_ha_test=True)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() # Make sure the contrail-collector is connected to the redis-uve before # sending the trace buffer request assert vizd_obj.verify_collector_redis_uve_connection( vizd_obj.collectors[0]) # Send trace buffer request for only the first collector vizd_obj.opserver.send_tracebuffer_request( vizd_obj.collectors[0].hostname, ModuleNames[Module.COLLECTOR], '0', 'UveTrace') assert vizd_obj.verify_tracebuffer_in_analytics_db( vizd_obj.collectors[0].hostname, ModuleNames[Module.COLLECTOR], 'UveTrace') # There should be no trace buffer from the second collector assert not vizd_obj.verify_tracebuffer_in_analytics_db( vizd_obj.collectors[1].hostname, ModuleNames[Module.COLLECTOR], 'UveTrace') # Make sure the contrail-collector is connected to the redis-uve before # sending the trace buffer request assert vizd_obj.verify_collector_redis_uve_connection( vizd_obj.collectors[1]) # Send trace buffer request for all collectors vizd_obj.opserver.send_tracebuffer_request( '*', ModuleNames[Module.COLLECTOR], '0', 'UveTrace') assert vizd_obj.verify_tracebuffer_in_analytics_db( vizd_obj.collectors[1].hostname, ModuleNames[Module.COLLECTOR], 'UveTrace') #end test_06_send_tracebuffer @unittest.skip('verify source/module list') def test_07_table_source_module_list(self): ''' This test verifies /analytics/table/<table>/column-values/Source and /analytics/table/<table>/column-values/ModuleId ''' logging.info('%%% test_07_table_source_module_list %%%') if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port, collector_ha_test=True)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() source = socket.gethostname() exp_genlist = [ source+':Analytics:contrail-collector:0', source+':Analytics:contrail-analytics-api:0', source+':Analytics:contrail-query-engine:0', source+'dup:Analytics:contrail-collector:0' ] assert vizd_obj.verify_generator_list(vizd_obj.collectors, exp_genlist) exp_src_list = [col.hostname for col in vizd_obj.collectors] exp_mod_list = ['contrail-collector', 'contrail-analytics-api', 'contrail-query-engine'] assert vizd_obj.verify_table_source_module_list(exp_src_list, exp_mod_list) # stop the second redis_uve instance and verify the src/module list vizd_obj.redis_uves[1].stop() exp_src_list = [vizd_obj.collectors[0].hostname] exp_mod_list = [gen.split(':')[2] \ for gen in vizd_obj.get_generator_list(vizd_obj.collectors[0])] assert vizd_obj.verify_table_source_module_list(exp_src_list, exp_mod_list) #end test_07_table_source_module_list <EMAIL>(' where queries with different conditions') def test_08_where_clause_query(self): ''' This test is used to check the working of integer fields in the where query ''' logging.info("%%% test_08_where_clause_query %%%") if AnalyticsTest._check_skip_test() is True: return True start_time = UTCTimestampUsec() - 3600 * 1000 * 1000 self._update_analytics_start_time(start_time) vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_where_query() #Query the flowseriestable with different where options assert vizd_obj.verify_collector_obj_count() collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture("contrail-vrouter-agent", collectors, logging, vizd_obj.get_opserver_port(), start_time)) assert generator_obj.verify_on_setup() generator_obj.generate_flow_samples() assert vizd_obj.verify_where_query_prefix(generator_obj) return True #end test_08_where_clause_query <EMAIL>('verify ObjectTable query') def test_09_verify_object_table_query(self): ''' This test verifies the Object Table query. ''' logging.info('%%% test_09_verify_object_table_query %%%') vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture('contrail-control', collectors, logging, None, node_type='Control')) assert generator_obj.verify_on_setup() msg_types = generator_obj.send_all_sandesh_types_object_logs( socket.gethostname()) assert vizd_obj.verify_object_table_sandesh_types('ObjectBgpRouter', socket.gethostname(), msg_types) # Check if ObjectId's can be fetched properly for ObjectTable queries vm_generator_obj = self.useFixture( GeneratorFixture("contrail-vrouter-agent", collectors, logging, vizd_obj.get_opserver_port())) assert vm_generator_obj.verify_on_setup() assert vizd_obj.verify_object_table_objectid_values('ObjectBgpRouter', [socket.gethostname()]) vm1_name = 'vm1' vm2_name = 'vm2' vm_generator_obj.send_vm_uve(vm_id=vm1_name, num_vm_ifs=2, msg_count=2) vm_generator_obj.send_vm_uve(vm_id=vm2_name, num_vm_ifs=2, msg_count=2) assert vizd_obj.verify_object_table_objectid_values('ObjectVMTable', [vm1_name, vm2_name]) # end test_09_verify_object_table_query <EMAIL>('verify ObjectValueTable query') def test_10_verify_object_value_table_query(self): ''' This test verifies the ObjectValueTable query. ''' logging.info('%%% test_10_verify_object_value_table_query %%%') if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() assert vizd_obj.verify_object_value_table_query( table='ObjectCollectorInfo', exp_object_values=[vizd_obj.collectors[0].hostname]) # verify that the object table query works for object id containing # XML control characters. collectors = [vizd_obj.get_collector()] generator_obj = self.useFixture( GeneratorFixture('contrail-vrouter-agent', collectors, logging, vizd_obj.get_opserver_port())) assert generator_obj.verify_on_setup() generator_obj.send_vm_uve(vm_id='vm11&>', num_vm_ifs=2, msg_count=1) assert vizd_obj.verify_object_value_table_query(table='ObjectVMTable', exp_object_values=['vm11&>']) # end test_10_verify_object_table_query <EMAIL>('verify syslog query') def test_11_verify_syslog_table_query(self): ''' This test verifies the Syslog query. ''' import logging.handlers logging.info('%%% test_11_verify_syslog_table_query %%%') if AnalyticsTest._check_skip_test() is True: return True vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port, syslog_port = True)) assert vizd_obj.verify_on_setup() syslogger = logging.getLogger("SYSLOGER") lh = logging.handlers.SysLogHandler(address=('127.0.0.1', vizd_obj.collectors[0].get_syslog_port())) lh.setFormatter(logging.Formatter('%(asctime)s %(name)s:%(message)s', datefmt='%b %d %H:%M:%S')) lh.setLevel(logging.INFO) syslogger.addHandler(lh) line = 'pizza pasta babaghanoush' syslogger.critical(line) assert vizd_obj.verify_keyword_query(line, ['pasta', 'pizza']) assert vizd_obj.verify_keyword_query(line, ['babaghanoush']) # SYSTEMLOG assert vizd_obj.verify_keyword_query(line, ['PROGRESS', 'QueryExec']) # bad charecter (loose?) line = 'football ' + chr(201) + chr(203) + chr(70) + ' and baseball' syslogger.critical(line) assert vizd_obj.verify_keyword_query(line, ['football', 'baseball']) # end test_11_verify_syslog_table_query <EMAIL>('verify message non ascii') def test_12_verify_message_non_ascii(self): ''' This test verifies message sent with non ascii character does not crash vizd. ''' logging.info('%%% test_12_verify_message_non_ascii %%%') analytics = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert analytics.verify_on_setup() collectors = [analytics.get_collector()] generator_obj = self.useFixture( GeneratorFixture('contrail-vrouter-agent-12', collectors, logging, None, node_type='Compute')) assert generator_obj.verify_on_setup() generator_obj.send_vrouterinfo(socket.gethostname(), b_info = True, deleted = False, non_ascii=True) # Verify vizd is still running assert analytics.verify_collector_gen(analytics.collectors[0]) # end test_12_verify_message_non_ascii <EMAIL>('verify sandesh ssl') def test_13_verify_sandesh_ssl(self): ''' This test enables sandesh ssl on contrail-collector and all the analytics generators in the AnalyticsFixture and verifies that the secure sandesh connection is established between the Collector and all the Generators. ''' logging.info('%%% test_13_verify_sandesh_ssl %%%') sandesh_cfg = { 'sandesh_keyfile': builddir+'/opserver/test/data/ssl/server-privkey.pem', 'sandesh_certfile': builddir+'/opserver/test/data/ssl/server.pem', 'sandesh_ca_cert': builddir+'/opserver/test/data/ssl/ca-cert.pem', 'sandesh_ssl_enable': 'True' } vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port, sandesh_config=sandesh_cfg)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() source = socket.gethostname() exp_genlist = [ source+':Analytics:contrail-collector:0', source+':Analytics:contrail-analytics-api:0', source+':Analytics:contrail-query-engine:0' ] assert vizd_obj.verify_generator_list(vizd_obj.collectors, exp_genlist) # start a python generator without enabling sandesh ssl # and verify that it is not connected to the Collector. test_gen1 = self.useFixture( GeneratorFixture("contrail-test-generator1", vizd_obj.get_collectors(), logging, vizd_obj.get_opserver_port())) assert not test_gen1.verify_on_setup() # start a python generator with sandesh_ssl_enable = True # and verify that it is connected to the Collector. test_gen2 = self.useFixture( GeneratorFixture("contrail-test-generator2", vizd_obj.get_collectors(), logging, vizd_obj.get_opserver_port(), sandesh_config=sandesh_cfg)) assert test_gen2.verify_on_setup() # stop QE and verify the generator list vizd_obj.query_engine.stop() exp_genlist = [ source+':Analytics:contrail-collector:0', source+':Analytics:contrail-analytics-api:0', source+':Test:contrail-test-generator2:0' ] assert vizd_obj.verify_generator_list(vizd_obj.collectors, exp_genlist) # Start QE with sandesh_ssl_enable = False and verify that the # QE is not connected to the Collector vizd_obj.query_engine.set_sandesh_config(None) vizd_obj.query_engine.start() assert not vizd_obj.verify_generator_collector_connection( vizd_obj.query_engine.http_port) assert vizd_obj.verify_generator_list(vizd_obj.collectors, exp_genlist) # Restart Collector with sandesh_ssl_enable = False and verify the # generator list in the Collector. vizd_obj.collectors[0].stop() vizd_obj.collectors[0].set_sandesh_config(None) vizd_obj.collectors[0].start() assert not vizd_obj.verify_generator_collector_connection( test_gen2._http_port) assert not vizd_obj.verify_generator_collector_connection( vizd_obj.opserver.http_port) exp_genlist = [ source+':Analytics:contrail-collector:0', source+':Analytics:contrail-query-engine:0', source+':Test:contrail-test-generator1:0' ] assert vizd_obj.verify_generator_list(vizd_obj.collectors, exp_genlist) # end test_13_verify_sandesh_ssl <EMAIL>('verify test_14_verify_qe_stats_collection query') def test_14_verify_qe_stats_collection(self): ''' This test checks if the QE is able to collect the stats related to DB reads correctly ''' logging.info('%%% test_14_verify_qe_stats_collection %%%') analytics = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port)) assert analytics.verify_on_setup() # make stat table entries also collectors = [analytics.get_collector()] generator_obj = self.useFixture( StatsFixture("VRouterAgent", collectors, logging, analytics.get_opserver_port())) assert generator_obj.verify_on_setup() logging.info("Starting stat gen " + str(UTCTimestampUsec())) generator_obj.send_test_stat("t010","lxxx","samp1",1,1); generator_obj.send_test_stat("t010","lyyy","samp1",2,2); assert generator_obj.verify_test_stat("StatTable.StatTestState.st","-2m", select_fields = [ "UUID", "st.s1", "st.i1", "st.d1" ], where_clause = 'name|st.s1=t010|samp1', num = 2, check_rows = [{ "st.s1":"samp1", "st.i1":2, "st.d1":2}, { "st.s1":"samp1", "st.i1":1, "st.d1":1}]); # Get the current read stats for MessageTable old_reads = analytics.get_db_read_stats_from_qe(analytics.query_engine, 'MessageTable') # read some data from message table and issue thequery again assert analytics.verify_message_table_moduleid() new_reads = analytics.get_db_read_stats_from_qe(analytics.query_engine, 'MessageTable') assert(old_reads < new_reads) # Get the current read stats for stats table old_reads = analytics.get_db_read_stats_from_qe(analytics.query_engine, 'StatTestState:st',True) assert (old_reads > 0) assert generator_obj.verify_test_stat("StatTable.StatTestState.st","-2m", select_fields = [ "UUID", "st.s1", "st.i1", "st.d1" ], where_clause = 'name|st.s1=t010|samp1', num = 2, check_rows = [{ "st.s1":"samp1", "st.i1":2, "st.d1":2}, { "st.s1":"samp1", "st.i1":1, "st.d1":1}]); new_reads = analytics.get_db_read_stats_from_qe(analytics.query_engine, 'StatTestState:st',True) assert(new_reads > old_reads) # end test_14_verify_qe_stats_collection <EMAIL>('verify introspect ssl') def test_15_verify_introspect_ssl(self): ''' This test enables introspect ssl and starts all the analytics generators in the AnalyticsFixture and verifies that the introspect port is accessible with https. ''' logging.info('%%% test_15_verify_introspect_ssl %%%') sandesh_cfg = { 'sandesh_keyfile': builddir+'/opserver/test/data/ssl/server-privkey.pem', 'sandesh_certfile': builddir+'/opserver/test/data/ssl/server.pem', 'sandesh_ca_cert': builddir+'/opserver/test/data/ssl/ca-cert.pem', 'introspect_ssl_enable': 'True' } vizd_obj = self.useFixture( AnalyticsFixture(logging, builddir, self.__class__.cassandra_port, sandesh_config=sandesh_cfg)) assert vizd_obj.verify_on_setup() assert vizd_obj.verify_collector_obj_count() # remove the config from vizd so that it tries to access introspect # with http, it should fail vizd_obj.set_sandesh_config(None) assert not vizd_obj.verify_collector_gen(vizd_obj.collectors[0]) # start a python generator with introspect_ssl_enable = True # and verify that its introspect page is accessible. vizd_obj.set_sandesh_config(sandesh_cfg) test_gen = self.useFixture( GeneratorFixture("contrail-test-generator", vizd_obj.get_collectors(), logging, vizd_obj.get_opserver_port(), sandesh_config=sandesh_cfg)) assert test_gen.verify_on_setup() # end test_15_verify_introspect_ssl @staticmethod def get_free_port(): cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cs.bind(("", 0)) cport = cs.getsockname()[1] cs.close() return cport @staticmethod def _check_skip_test(): if (socket.gethostname() == 'build01'): logging.info("Skipping test") return True return False def _term_handler(*_): raise IntSignal() if __name__ == '__main__': gevent.signal(signal.SIGINT,_term_handler) unittest.main(catchbreak=True)
<reponame>eengineergz/Lambda import React, { useState } from 'react'; import useDarkMode from '../hooks/useDarkMode.js'; const Navbar = () => { const [darkMode, setDarkMode] = useDarkMode(false); const toggleMode = e => { e.preventDefault(); setDarkMode(!darkMode); }; return ( <nav className="navbar" id="NavBar"> <h1>Women's Soccer Players Ranked by Number of Google Searches:</h1> <div className="dark-mode__toggle"> <div onClick={toggleMode} className={darkMode ? 'toggle toggled' : 'toggle'} /> </div> </nav> ); }; export default Navbar;
def rotate90(matrix): result = [[0,0,0], [0,0,0], [0,0,0]] N = len(matrix) for i in range(N): for j in range(N): result[i][j] = matrix[N-1-j][i] for r in result: print(r) matrix = [[1,2,3], [4,5,6], [7,8,9]] rotate90(matrix) // Output [7, 4, 1] [8, 5, 2] [9, 6, 3]
<filename>src/edu/washington/cse/instrumentation/analysis/utils/ApplicationClassInference.java package edu.washington.cse.instrumentation.analysis.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class ApplicationClassInference { public static class Results { public final Set<String> applicationClassPrefixes; public final Set<String> libraryClassPrefixes; Results(final Set<String> applicationClassPrefixes, final Set<String> libraryClassPrefixes) { this.applicationClassPrefixes = applicationClassPrefixes; this.libraryClassPrefixes = libraryClassPrefixes; } } private static class PackageTrie { private final Map<String, PackageTrie> children; public PackageTrie() { children = new HashMap<>(); } public static PackageTrie of(final List<String> comp) { final PackageTrie root = new PackageTrie(); PackageTrie currNode = root; for(final String c : comp) { final PackageTrie newNode = new PackageTrie(); currNode.children.put(c, newNode); currNode = newNode; } return root; } void update(final List<String> mergeIn) { PackageTrie currNode = this; for(int i = 0; i < mergeIn.size(); i++) { final String comp = mergeIn.get(i); if(!currNode.children.containsKey(comp)) { currNode.children.put(comp, PackageTrie.of(mergeIn.subList(i+1, mergeIn.size()))); return; } else { currNode = currNode.children.get(comp); } } } public Set<String> findPackageStrings() { return this.findSingleChains(new ArrayList<String>()); } private Set<String> findSingleChains(final List<String> accum) { if(this.children.size() == 1) { return toChainEnd(accum); } else if(this.children.size() == 0) { return Collections.singleton(accumulatorToPackage(accum)); } final Set<String> toReturn = new HashSet<>(); for(final Map.Entry<String, PackageTrie> kv : children.entrySet()) { final List<String> subAccum = new ArrayList<>(accum); subAccum.add(kv.getKey()); toReturn.addAll(kv.getValue().findSingleChains(subAccum)); } return toReturn; } private Set<String> toChainEnd(final List<String> acc) { PackageTrie it = this; while(it.children.size() == 1) { final Map.Entry<String, PackageTrie> entry = it.children.entrySet().iterator().next(); if(entry.getKey().equals("$")) { break; } acc.add(entry.getKey()); it = entry.getValue(); } return Collections.singleton(accumulatorToPackage(acc)); } private String accumulatorToPackage(final List<String> accum) { assert accum.size() > 0; final StringBuilder toReturn = new StringBuilder(accum.get(0)); for(int i = 1; i < accum.size(); i++) { toReturn.append(".").append(accum.get(i)); } return toReturn.toString(); } @Override public String toString() { return this.children.toString(); } } public static Results inferApplicationClasses(final Iterator<String> positiveExample, final Iterator<String> negativeExamples) { final PackageTrie accum = new PackageTrie(); while(positiveExample.hasNext()) { final String s = positiveExample.next(); final String[] comp = s.split("\\."); comp[comp.length - 1] = "$"; accum.update(Arrays.asList(comp)); } final Set<String> applicationPackage = accum.findPackageStrings(); while(negativeExamples.hasNext()) { final String s = negativeExamples.next(); for(final String ap : applicationPackage) { assert !s.startsWith(ap); } } return new Results(Collections.unmodifiableSet(applicationPackage), Collections.<String>emptySet()); } }
require File.expand_path('../../spec_helper', __FILE__) describe 'The -S command line option' do before :each do @path = [ENV['PATH'], fixture(__FILE__, "bin")].join(':') end platform_is_not :windows do # On VirtualBox shared directory (vboxsf) all files are world writable # and MRI shows warning when including world writable path in ENV['PATH']. # This is why we are using /success$/ matching in the following cases. it "runs launcher found in PATH, but only code after the first /\#!.*ruby.*/-ish line in target file" do result = ruby_exe(nil, options: '-S hybrid_launcher.sh', env: { 'PATH' => @path }, args: '2>&1') result.should =~ /success$/ end it "runs launcher found in PATH" do result = ruby_exe(nil, options: '-S launcher.rb', env: { 'PATH' => @path }, args: '2>&1') result.should =~ /success$/ end it "runs launcher found in PATH and sets the exit status to 1 if it fails" do result = ruby_exe(nil, options: '-S dash_s_fail', env: { 'PATH' => @path }, args: '2>&1') result.should =~ /\bdie\b/ $?.exitstatus.should == 1 end end end
$(window).bind("load", function() { class Button { constructor(element) { this.element = element; this.data_url = $(element).attr('data-url'); this.position = $(this.data_url).position(); this.left = this.position.left; this.top = $(this.data_url).offset().top; this.width = $(window).width(); } down() { // resize height var height = $(this.data_url + ' .page').height(); $('#main-2').css({'max-height': (height) + 'px', 'height':height + 'px'}); // got to var speed; if(this.width > 450) { speed = 300; } else { speed = 0; } $('html, body').animate({ scrollLeft:this.left + "px", }, 0) .animate({ scrollTop:this.top + "px" }, speed); // disable scroll $('body').addClass('offWheel'); document.ontouchmove = function(e){ return true; } $('body').css('touch-action', 'auto'); // if(this.width <= 450) { $('body').css('overflow', 'scroll'); // } } up() { // go at the wright section $('#main-2').animate({'position':'absolute','z-index':'100000000', 'left': this.left}, 0); var speed; if(this.width > 450) { speed = 300; } else { speed = 0; } $('html, body').animate({ scrollLeft:this.left + "px", }, 0) .animate({ scrollTop:this.top + "px" }, speed); // disable scroll $('body').removeClass('offWheel'); // $('body').css('overflow', 'hidden'); var width = $(window).width(); if(width <= 500) { // disable scroll on IOS document.ontouchmove = function(e){ e.preventDefault(); } // disable scroll on android $('body').css('touch-action', 'none'); if(this.width <= 450) { $('body').css('overflow', 'hidden'); } } } } $('.QuiSuisJe').hide(0); $('.down').click(function() { // enable #main 2 $('#main-2').css('display', 'flex'); // show #sub-1 up button var body_id = $('body').attr('id'); $('.QuiSuisJe').not('#sublink_' + body_id).hide(0); $('#sublink_' + body_id).show(0); // prepare #sub-1 resize if($(this).attr('data-url') == '#sub-1') { $('#span-info').addClass('who'); } // enable wright sub var data_url = $(this).attr('data-url'); $('.sub').not(data_url).css('display', 'none'); $(data_url).css('display', 'block'); // prepare resize $('#info-name').text(data_url); // go down var button = new Button(this); // close menu responsive if($('.hamburger').hasClass('responsive')) { $('.hamburger').toggleClass('responsive'); var width = $(window).width(); if(width > 780) { var navHeight = 90; } else { var navHeight = 55; } $('nav').animate({'height': navHeight + 'px'}, 0); // toggle button $('.hamburger').css('transition', '0s ease-in-out').css('margin-top', '-=10px'); $('#slice-1').css('transition', '0s ease-in-out').css('transform', 'rotate(0deg) translateY(0px)'); $('#slice-2').css('transition', '0s ease-in-out').css('transform', 'translateX(0px)').fadeIn(0); $('#slice-3').css('transition', '0s ease-in-out').css('transform', 'rotate(0deg) translateY(0px)'); } // hide buble $('nav').animate({'position':'relative', 'top':'-120px'}, 300); $('footer').animate({'position':'relative', 'bottom':'-50px'}, 300); $('.bulle-container').css('transition', '0s').animate({'opacity': '0'}, 200); $('.skill-container').animate({'opacity':'0'}, 200); $('.scroll-container').animate({'opacity':'0'}, 200); $('.allons-y-container').animate({'opacity':'0'}, 200); // slide buttons if(width > 450) { $('#go-left').animate({'left':'-100px', 'right':'auto'}, 200); $('#go-right').animate({'right':'-100px'}, 200); } else { $('#go-left').css({'transition':'0.2s', 'right':'-100px', 'left':'auto'}); $('#go-right').css({'transition':'0.2s', 'right':'-100px'}); } // section 2 and 3 content if($(this).hasClass('skill-box')) { var skill_box_id = $(this).attr('id'); switch(skill_box_id) { case "code" : var sectionTitre = "Code"; $('#section-2-subtitle-1').hide(); $('#section-2-subtitle-2').text("Trouvons l’outil le mieux adapté à vos besoins."); var paragraph_title = "Wordpress"; var paragraph_title_2 = "\« From Scratch \»"; var section_2_p1 = "Wordpress est un site clé en main, maintenable sans écrire la moindre ligne de code et par n’importe qui. <span class='strong'>Ideal si vous êtes néophyte !</span>"; var section_2_p2 = "Dans Wordpress vous customisez vous-même les pages, les couleurs, les polices, etc. et bien sûr vous créez votre propre contenu. <span class='strong'>C’est l’outil parfait pour créer son blog !</span>"; var section_2_p3 = "Wordpress est livré avec un ou plusieurs designs de qualité professionnelle. Vous choisissez celui qui vous plait et remplacez les logos, les images et les textes par les vôtres. <span class='strong'>Idéal pour créer rapidement de belles vitrines d’entreprise !</span>"; var section_2_p4 = "<span class='strong'>Mais Wordpress à une courbe d’apprentissage qui peut vous décourager si vous n’y connaissez rien.</span>"; var section_2_p5 = "Lorsque vous savez déjà vous en servir, vous découvrez <span class='strong'>qu’il n’est pas possible de modifier les thèmes en profondeur sans avoir de bonnes connaissances en code.</span>"; $('#section-2-p6').css('display', 'inline-block').html('<span class="strong">Je vous apporte mon aide pour créer un site de zéro ou apporter toutes les modifications que vous souhaitez a un thème existant.</span>'); $('#section-2-p7').css('display', 'inline-block').html('<span class="strong">Je travaille avec Divi, l’un des thèmes Wordpress les plus puissants qui permet de créer n’importe quel design en un temps record !</span>'); var section_2_p8 = "<span class='strong'>« From sratch » signifie « partir de zéro »</span>. Travailler « from scratch » c’est donc coder un site par soi-même."; var section_2_p9 = "<span class='strong'>Autant dire que pour cela, il faut être calé en code</span>. C’est pourquoi la plupart des gens choisissent d’utiliser Wordpress qui ne demande aucune connaissance particulière."; var section_2_p10 = "Mais travailler « from scratch » a plein d'avantages. <span class='strong'>D’abord il permet d’être libre dans sa manière de travailler</span>. Wordpress peut être assez contraignant et il arrive qu’on s’arrache les cheveux pour changer un petit détail. Travailler avec votre propre code, permet au contraire de toujours savoir où on en est."; var section_2_p11 = "<span class='strong'>De plus travailler « from scratch » permet de construire un site sophistiqué, avec des fonctionnalités innovantes</span>. Génial si vous voulez lancer un nouveau business digital !"; $('#section-2-p12').css('display', 'block').html('<span class="strong">Je développe vos applications en HTML, javascript et PHP, seul ou en collaboration avec vos équipes, avec ou sans framework.</span>'); $('#round-p').css('text-align', 'justify').html("Etes vous plutôt Wordpress ou « from scratch » ? Voulez-vous construire un blog, une vitrine pour votre entreprise ou créer une application innovante ? Si vous avez avez fait votre choix ou avez besoin d’un conseil, "); break; case "design" : var sectionTitre = "Design"; $('#section-2-subtitle-1').show().text("Pour créer un style à votre image"); $('#section-2-subtitle-2').text("nous avons besoin :"); var paragraph_title = "D’une maquette"; var paragraph_title_2 = "Qu’il soit \« responsive \» "; var section_2_p1 = "Rien à voir avec une maquette d’architecte ! Et pourtant ça y ressemble : de même que <span class='strong'>la maquette d’un bâtiment est un prototype à petite échelle, de même la maquette est le prototype visuel d’un site.</span>"; var section_2_p2 = "Pour la créer, le designer utilise des images et des dessins faits par ordinateurs. Il simule ainsi l’apparence de votre futur site pour vous en donner une idée aussi précise que possible. <span class='strong'>Pour vous, la maquette a donc un avantage : elle permet de définir votre identité visuelle avec précision.</span>"; var section_2_p3 = "<span class='strong'>La maquette est aussi très utile au développeur web </span>: elle lui donne une idée précise de ce qu’il va coder et lui évite d’ « improviser » son design au dernier moment. Pour vous c’est l’assurance que votre identité visuelle sera respectée."; var section_2_p4 = "<span class='strong'>Mais les services d’un designer sont souvent très chers</span> et seules les entreprises ont les moyens de se les offrir."; var section_2_p5 = "<span class='strong'>Si vous travaillez sur Wordpress, vous n’aurez sans doute pas besoin d’un designer</span>. Les thèmes sont souvent bien faits et suffisent dans la plupart des cas. "; $('#section-2-p6').css('display', 'inline-block').html('<span class="strong">Mais si vous souhaitez créer votre design ou votre thème personnalisé, vous aurez sans doute besoin d’aide.</span>'); $('#section-2-p7').css('display', 'inline-block').html('<span class="strong">Je vous accompagne dans la création de votre identité visuelle et réalise votre maquette. Je me sers d’outils puissants comme Adobe XD qui permettent d’obtenir un résultat rapide et professionnel.</span>'); var section_2_p8 = "« Responsive » veut dire « adaptable » en anglais. <span class='strong'>Un design « responsive » veut dire qu’il s’adapte à différents formats d’écrans (smartphone, tablette, etc.).</span>"; var section_2_p9 = "<span class='strong'>Autrefois, l’ordinateur était le seul moyen de consulter internet</span>. On ne prêtait alors aucune attention aux éventuels changements de taille des écrans. Ainsi lorsqu’on réduisait la taille du navigateur, le site sortait de la page et le design pouvait sauter."; var section_2_p10 = "<span class='strong'>Mais aujourd’hui les choses ont changé : le smartphone a remplacé l’ordinateur pour la consulation d’internet et les designers ont dû suivre</span>. Ils ont donc créé un design « responsive », adaptable aux différentes tailles d’écrans. Vérifiez vous-mêmes : si vous réduisez la taille de cette page, vous verrez que mon site s’adapte parfaitement."; var section_2_p11 = "On comprend qu’aujourd’hui, la première exigence des clients est d’avoir un site responsive. <span class='strong'>Pour ma part cela va tellement de soi que « site web » et « responsive » sont parfaitement synonymes !</span>"; $('#section-2-p12').css('display', 'none'); $('#round-p').css('text-align', 'justify').html("Vous souhaitez un design à votre image, qui reste beau sur les différentes tailles d’écran ? N’attendez plus :"); break; case "seo" : var sectionTitre = "SEO"; $('#section-2-subtitle-1').show().text("Ou « référencement » en français."); $('#section-2-subtitle-2').text("J’y contribue par :"); var paragraph_title = "Un code adapté"; var paragraph_title_2 = "Un contenu pertinent"; var section_2_p1 = "A quoi sert d’avoir un site web si personne ne le voit ? Cela semble tellement évident que bon nombre de gens pensent qu'être développeur web et spécialiste du référencement, c'est la même chose. <span class='strong'>Mais coder un site et booster votre position sur Google sont deux métiers très différents !</span> L’un demande de parler un langage informatique pointu et l’autre de savoir ruser avec les robots de Google. Rien à voir !"; var section_2_p2 = "Pourtant il y a certaines choses qu’un développeur comme moi peut faire :"; var section_2_p3 = "<span class='strong'>- créer un site qui charge vite</span>. Google adore les sites rapides. Ainsi plus le site est « léger » (code simple et efficace, poids des images réduit, utilisation d’un CDN, etc.), plus il a des chances d’être bien référencé !"; var section_2_p4 = "<span class='strong'>- utiliser des « balises » dédiées</span>. Une balise HTML est un petit drapeau qui indique le positionnement (haut, bas, etc.) et la nature des éléments d’une page (titre, paragraphe, citation, etc). Placer ces balises permet à Google de repérer plus facilement vos mots clés. Par ex. la balise « titre » indique à Google le mot le plus important de votre page. Elle doit donc être utilisée avec soin. Il en va de même des balises schema.org qui identifient plus précisément les éléments de votre page."; var section_2_p5 = "<span class='strong'>- utiliser Wordpress (car Google aime le code de Wordpress) et ajouter des plugins dédiés comme Yoats SEO</span>."; $('#section-2-p6').css('display', 'none'); $('#section-2-p7').css('display', 'none'); var section_2_p8 = "Si vous vous êtes déjà intéressé au web, vous avez sans doute entendu parler des fameux « mots clés ». Lorsqu’un utilisateur fait une recherche sur Google, ce dernier va analyser les mots de la recherche et trouver les pages qui les contiennent. <span class='strong'>Un mot clé est donc le moyen de dire à Google que vous êtes la meilleure réponse à la question d’un utilisateur.</span>"; var section_2_p9 = "Cela prend toute son importance lorsqu’on crée un business en ligne, car <span class='strong'>trouver les bons mots-clés c’est s’assurer que Google va nous amener les bons clients</span>, c’est-à-dire ceux qui constituent notre cible. Pour prendre un exemple grossier, si je suis opticien j’ai tout intérêt à placer « lunettes » dans une de mes pages, car il y a fort à parier que les utilisateurs qui cherchent un opticien tapent « lunette » dans Google. Dans la réalité les choses sont plus complexes évidemment. Mais cela nous donne une petite idée de l’importance des mots-clés !"; var section_2_p10 = "<span class='strong'>Mais le référencement est un métier et le meilleur moyen d’être bien placé sur Google est de faire appel à un professionnel</span>. Malheureusement ils sont souvent très chers et seules les entreprises ont les moyens de se les payer."; var section_2_p11 = "Pourtant, à mon niveau, je peux vous apporter une aide. Ancien professeur de philosophie, j’ai des facilités pour organiser, exprimer et clarifier mes idées. Pendant 10 ans, j’ai corrigé et affiné mon expression écrite. <span class='strong'>Je peux vous aider à créer un contenu qui ne nuise pas à votre visibilité ou qui, dans le meilleur des cas, y soit favorable.</span>"; $('#section-2-p12').css('display', 'none'); $('#round-p').css('text-align', 'center').html("Vous souhaitez un site qui se voit sur Google ? <br>N’attendez plus :"); break; case "ecoute" : var sectionTitre = "Ecoute"; var sectionP1 = "C’est votre premier site web et vous ne savez pas encore comment vous y prendre ? Mon rôle est de vous accompagner et de répondre à toutes vos questions."; var sectionP2 = 'Ne venant pas moi-meme du monde du web, je n’ai pas l’impatience des informaticiens qui ne comprennent pas qu’on ne comprenne pas. Je suis capable de me mettre à votre place et de vous entendre.'; var sectionP3 = "Pour cela il faut que nous créions dès le départ un dialogue constructif et cordial. De mon côté, je me mets à votre disposition et suis ouvert à toutes vos remarques. Du vôtre, vous me dites tout ce que vous pensez, avec franchise et simplicité. Si, à la fin de notre travail, « site web » rime pour vous avec « sérénité », ma mission sera accomplie !"; break; case "qualite" : var sectionTitre = "Qualité"; var sectionP1 = "Par nature je ne me vends pas, je donne ce que je suis. Lorsque je fais un site web, je m’investis complètement dans la production d’un résultat impeccable. Tous mes travaux sont conçus, façonnés, ouvragés avec soin. Ce que j’aime par-dessus tout : voir la satisfaction du client." var sectionP2 = "La qualité ne repose pas seulement sur l’engagement mais aussi sur la compétence. Je maitrise les principaux langages et les dernières technologies du web. Du HTML au PHP en passant par Ajax et JQuery, mais aussi l’utilisation de frameworks ou de Wordpress, j’ai les outils pour répondre à tous vos besoins." var sectionP3 = "Vous ne connaissez rien au web et ce que je dis ne vous parle pas ? Je vous invite à découvrir mon portfolio. Je suis sûr que cela suffira pour vous convaincre." break; case "dispo" : var sectionTitre = "Disponibilité"; var sectionP1 = "Vous avez besoin de temps pour concevoir votre site web mais l’inspiration vous vient au coup par coup ? Ça tombe bien : je suis disponible pour échanger avec vous 24h/ 24 et 7j/ 7." var sectionP2 = "Quand j’étais enseignant, ce qui me frustrait était qu’on nous poussait à faire nos journées, sans plus, en attendant les vacances. Pour ma part, j’étais incapable de compter mes heures car mon travail me passionnait. C’est la même chose dans le développement web. Tout nouveau projet me stimule, me passionne. Qu’il soit petit ou grand, c’est toujours un défi à relever et je ne peux pas m’arrêter avant d’être arrivé au bout." var sectionP3 = "Ainsi que vous ayez ou non du temps à consacrer à votre projet, je serai toujours disponible pour en parler avec vous. Et pour cause : chaque fois que vous me faites une remarque vous faites avancer mon travail. Alors n’hésitez plus : contactez-moi dès maintenant et commençons à travailler ensemble !" break; } // section 2 $('#section-2-titre').text(sectionTitre); $('#paragraph-title-2-1').html(paragraph_title); $('#paragraph-title-2-2').html(paragraph_title_2); $('#section-2-p1').html(section_2_p1); $('#section-2-p2').html(section_2_p2); $('#section-2-p3').html(section_2_p3); $('#section-2-p4').html(section_2_p4); $('#section-2-p5').html(section_2_p5); $('#section-2-p8').html(section_2_p8); $('#section-2-p9').html(section_2_p9); $('#section-2-p10').html(section_2_p10); $('#section-2-p11').html(section_2_p11); // section 3 $('#section-3-titre').text(sectionTitre); $('#section-3-p1').text(sectionP1); $('#section-3-p2').text(sectionP2); $('#section-3-p3').text(sectionP3); } // go down setTimeout(function() { button.down(); var windowWidth = $(window).width(); var display; // slide buttons $('#go-left').css({'display':'none'}, 200); $('#go-right').css({'display':'none'}, 200); }, 300); // disable #main setTimeout(function() { $('#main').css('display', 'none'); $('html, body').animate({scrollTop:$('#main-2').offset().top}, 0); }, 600); return false; }); $('.up').click(function() { // enable #main-2 var windowWidth = $(window).width(); var display; if(windowWidth > 450) { display = 'flex'; $('#go-left').css({'display': 'block', 'left':'0px', 'right':'auto'}); $('#go-right').css({'display':'block', 'right':'0px'}); // if($('body').hasClass('ofWheel')) { // $('#background-0').css('top', '0px'); // } } else { display = 'block'; $('#go-left').css({'display': 'block', 'right':'5px', 'left':'auto'}); $('#go-right').css({'display':'block', 'right':'5px'}); } $('#main').css('display', display); $('html, body').animate({scrollTop:$('#main-2').offset().top}, 0); // #sub-6 active var upId = $(this).attr('id'); setTimeout(function() { if(upId == 'sublink_6') { $('.inputs').removeClass('active'); $('#input-1').addClass('active'); } }, 300); $('#info-name').text(''); // go up var button = new Button(this); button.up(); setTimeout(function() { // #sub-1 $('#span-info').removeClass('who'); // show buble $('nav').animate({'position':'relative', 'top':'0px'}, 300); $('footer').animate({'position':'relative', 'bottom':'0px'}, 300); $('.bulle-container').animate({'opacity': '1'}, 200); $('.skill-container').animate({'opacity':'1'}, 200); $('.scroll-container').animate({'opacity':'1'}, 200); $('.allons-y-container').animate({'opacity':'1'}, 200); $('.slide-mobile').show(200); // close menu responsive var width = $(window).width(); if(width > 780) { $('nav').animate({'height':'90px'}, 0); } // disable #main 2 $('.sub').css('display', 'block'); $('#main-2').animate({'position':'absolute','z-index':'1', 'left': '0px'}, 0).animate({'position':'relative'}, 0).css('display', 'none'); }, 300); return false; }); });
def lexcmp(s1, s2): # Find leftmost nonequal pair. i = 0 while i < len(s1) and i < len(s2): outcome = cmp(s1[i], s2[i]) if outcome: return outcome i += 1 # All equal, until at least one sequence was exhausted. return cmp(len(s1), len(s2))
<gh_stars>0 //const { sql, poolPromise } = require("../database/db"); const {poolPromise } = require("../database/db"); const fs = require("fs"); //const mustacheExpress = require("mustache-express"); var rawdata = fs.readFileSync("./query/queries.json"); var queries = JSON.parse(rawdata); let query = ""; let enkelSide= false; let viseAllQueryResultat = false; class MainController { async produkter(req, res) { try { console.log("req.url = " + req.url + "\n"); switch (req.url) { case "/api/produkter/alle": enkelSide= false; viseAllQueryResultat = true; console.log("/api/produkter/alle - valid request"); query = queries.produkterAlle; break; case "/api/produkter/alle-aktive": enkelSide= false; viseAllQueryResultat = true; console.log("/api/produkter/alle-aktive - valid request"); query = queries.produkterAlleAktive; break; case "/api/produkter/alle-aktive-med-nav-avtale": enkelSide= false; viseAllQueryResultat= true; console.log("/api/produkter/alle-aktive-med-nav-avtale - valid request"); query = queries.produkterAlleAktiveMedNAVAvtale; break; case "/api/produkter/alle-aktive-med-nav-avtale-techdata": enkelSide= false; viseAllQueryResultat = false; console.log("/api/produkter/alle-aktive-techdata - valid request"); query = queries.produkterAlleAktiveNAVAVtaleTechData; break; case "/api/produkter/test": enkelSide= false; viseAllQueryResultat = true; console.log("/api/produkter/test - valid request"); query = queries.produktTest; break; case `/api/produkter/${req.params.id}`: let id = ""; enkelSide= true; viseAllQueryResultat = true; console.log("/api/produkter/:id - valid request"); id = req.params.id; console.log("id after =" + JSON.stringify(id)); query = queries.produktX.replace("hmsartnr", id); break; default: console.log("/api/produkter/...not valid request"); } //pool.close(); const pool = await poolPromise; const result = await pool.request().query(query); console.log(query); console.log("Enkel side: ", enkelSide); console.log("Vise All Query Resultat: ", viseAllQueryResultat); if (!enkelSide && viseAllQueryResultat) { res.json(result.recordset); } else if (!enkelSide && !viseAllQueryResultat) { res.json(result.recordset) } else if (enkelSide && viseAllQueryResultat) { res.json(result.recordset[0]); } } catch (error) { res.status(500); res.send(error.message); } } async produktSider(req, res) { let id = req.params.id; console.log("/api/produkter/side/:id - valid request"); try { query = queries.produktX.replace("hmsartnr", id); const pool = await poolPromise; const result = await pool .request() .query(query); console.log(result.recordset[0]); const url1 = "https://www.hjelpemiddeldatabasen.no/blobs/snet/" + `${result.recordset[0].prodid}` + ".jpg"; console.log(url1); res.render("produktsider", { prodname: result.recordset[0].prodname, pshortdesc: result.recordset[0].pshortdesc, url2: url1, prodid: result.recordset[0].prodid, stockid: result.recordset[0].stockid, isocode: result.recordset[0].isocode, isotitle: result.recordset[0].isotitle, adressnamn1: result.recordset[0].adressnamn1, }); //res.json(result.parse) } catch (error) { res.status(500); res.send(error.message); } } } const controller = new MainController(); module.exports = controller;
<gh_stars>1-10 package implementation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * * @author exponential-e * 백준 21608번: 상어 초등학교 * * @see https://www.acmicpc.net/problem/21608 * */ public class Boj21608 { private static List<Seat> inputs = new ArrayList<>(); private static int[][] seats; private static int[][] favor; private static int N; private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; private static final int ROW = 0, COL = 1; private static final int CIPHER = 1_000; private static final int[] SCORE = {0, 1, 10, 100, 1_000}; private static class Seat { int src; int[] snk; public Seat(int src, int[] snk) { this.src = src; this.snk = snk; } } private static class Pair implements Comparable<Pair>{ int index; int count; public Pair(int index, int count) { this.index = index; this.count = count; } @Override public int compareTo(Pair p) { if(this.count == p.count) return this.index - p.index; return p.count - this.count; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); int loop = N * N; favor = new int[loop][loop]; while(loop-- > 0){ StringTokenizer st = new StringTokenizer(br.readLine()); int student = Integer.parseInt(st.nextToken()) - 1; int[] fav = new int[4]; for(int i = 0; i < 4; i++) { fav[i] = Integer.parseInt(st.nextToken()) - 1; favor[student][fav[i]] = 1; } inputs.add(new Seat(student, fav)); } System.out.println(positioning()); } private static int positioning() { seats = new int[N][N]; for(int i = 0; i < N; i++) { Arrays.fill(seats[i], -1); } for(Seat in: inputs) { int index = getUnique(findFavorite(in.snk)); int row = index / CIPHER; int col = index % CIPHER; seats[row][col] = in.src; } return satisfied(); } private static int satisfied() { int result = 0; for(int row = 0; row < N; row++) { for(int col = 0; col < N; col++) { int target = seats[row][col]; int count = 0; for (final int[] DIRECTION: DIRECTIONS) { int nextRow = row + DIRECTION[ROW]; int nextCol = col + DIRECTION[COL]; if (outOfRange(nextRow, nextCol)) continue; count += favor[target][seats[nextRow][nextCol]]; } result += SCORE[count]; } } return result; } /** * * Find unique coordinate * * @param arr * @return */ private static int getUnique(int[][] arr) { List<Pair> candidate = new ArrayList<>(); int max = 0; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { max = Math.max(max, arr[i][j]); } } for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++ ){ if(max != arr[i][j] || seats[i][j] != -1) continue; candidate.add(new Pair(i * CIPHER + j, emptySize(i, j))); } } Collections.sort(candidate); return candidate.get(0).index; } private static int emptySize(int row, int col) { int size = 0; for(final int[] DIRECTION: DIRECTIONS) { int nextRow = row + DIRECTION[ROW]; int nextCol = col + DIRECTION[COL]; if(outOfRange(nextRow, nextCol) || seats[nextRow][nextCol] != -1) continue; size++; } return size; } /** * * Find friends * * @param fav * @return */ private static int[][] findFavorite(int[] fav) { int[][] friends = new int[N][N]; for(int f: fav) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (seats[row][col] != f) continue; for (final int[] DIRECTION : DIRECTIONS) { int nextRow = row + DIRECTION[ROW]; int nextCol = col + DIRECTION[COL]; if (outOfRange(nextRow, nextCol) || seats[nextRow][nextCol] != -1) continue; friends[nextRow][nextCol]++; } } } } return friends; } private static boolean outOfRange(int row, int col) { return row < 0 || row >= N || col < 0 || col >= N; } }
<reponame>gittysachin/iFitClients_ADMIN export class Workouts { id: string; business_owner_id: string; category_id: string; url: File; name: string; description: string; is_active: boolean; }
import React from 'react'; import ReactDOM from 'react-dom'; import app from './app'; window.debug = require("debug"); const debug = window.debug("boilerplate"); const mountNode = document.getElementById("content"); const dehydratedState = window.App; debug("Rehydrating state...", dehydratedState); app.rehydrate(dehydratedState, (err, context) => { if (err) { throw err; } debug("State has been rehydrated"); const Main = app.getComponent(); ReactDOM.render( <Main context={ context.getComponentContext() } />, mountNode, () => { debug("Root component has been mounted"); } ) })
import './index'; import { expect } from 'chai'; import { $, $$ } from 'common-sk/modules/dom'; import fetchMock from 'fetch-mock'; import { SelectSk } from 'elements-sk/select-sk/select-sk'; import { pageSets } from './test_data'; import { setUpElementUnderTest } from '../../../infra-sk/modules/test_util'; import { PagesetSelectorSk } from './pageset-selector-sk'; describe('pageset-selector-sk', () => { const factory = setUpElementUnderTest<PagesetSelectorSk>('pageset-selector-sk'); // Returns a new element with the pagesets fetch complete. const newInstance = async (init?: ((instance: PagesetSelectorSk)=> void)) => { const ele = factory(init); await new Promise((resolve) => setTimeout(resolve, 0)); return ele; }; let selector: PagesetSelectorSk; // Set at start of each test. beforeEach(() => { fetchMock.postOnce('begin:/_/page_sets/', pageSets); }); afterEach(() => { // Check all mock fetches called at least once and reset. expect(fetchMock.done()).to.be.true; fetchMock.reset(); }); const simulateUserToggle = () => { ($$('expandable-textarea-sk > button', selector) as HTMLElement).click(); }; // Simulates a user typing 'value' into the input element by setting its // value and triggering the built-in 'input' event. const simulateUserEnteringCustomPages = (value: string) => { const ele = $$('textarea', selector) as HTMLInputElement; ele.focus(); ele.value = value; ele.dispatchEvent(new Event('input', { bubbles: true, cancelable: true, })); }; it('loads selections', async () => { selector = await newInstance(undefined); expect($('select-sk div')).to.have.length(8); expect($$('.pageset-list', selector)).to.have.property('hidden', false); expect(selector).to.have.property('selected', '10k'); }); it('reflects changes to selected', async () => { selector = await newInstance(undefined); expect(selector).to.have.property('selected', '10k'); ($$('select-sk', selector) as SelectSk).selection = 3; expect(selector).to.have.property('selected', 'Mobile10k'); selector.selected = 'Dummy1k'; expect(selector).to.have.property('selected', 'Dummy1k'); // Invalid keys aren't honored. selector.selected = 'bogus key'; expect(selector).to.have.property('selected', ''); }); it('filters out hideKeys options', async () => { selector = await newInstance((ele) => { ele.hideKeys = ['Mobile100k', '100k', 'Dummy1k', 'non-existant']; }); expect($('select-sk div', selector)).to.have.length(5); // Check that options can be recovered. selector.hideKeys = []; expect($('select-sk div', selector)).to.have.length(8); }); it('hides selector when custom page form expanded', async () => { selector = await newInstance(undefined); simulateUserToggle(); expect($$('.pageset-list', selector)).to.have.property('hidden', true); }); it('clears custom pages when custom page form collapsed ', async () => { selector = await newInstance(undefined); simulateUserToggle(); simulateUserEnteringCustomPages('example.com'); expect(selector).to.have.property('customPages', 'example.com'); expect($$('.pageset-list', selector)).to.have.property('hidden', true); simulateUserToggle(); expect($$('.pageset-list', selector)).to.have.property('hidden', false); expect(selector).to.have.property('customPages', ''); }); it('disables custom page form on disable-custom-webpages', async () => { selector = await newInstance((ele) => { ele.setAttribute('disable-custom-webpages', ''); }); expect(selector.querySelectorAll('expandable-textarea-sk').length).to.equal(0); expect(selector.querySelectorAll('select-sk').length).to.equal(1); }); });
#!/bin/bash # This assumes all of the OS-level configuration has been completed and git repo has already been cloned #sudo yum-config-manager --enable epel #sudo yum update -y #sudo yum install git libpng-devel libcurl-devel gcc python-devel libjpeg-devel -y # pip install --upgrade pip==9.0.3 # alias sudo='sudo env PATH=$PATH' # pip install --upgrade setuptools==39.0.1 # pip install --upgrade virtualenv==15.2.0 # This script should be run from the repo's deployment directory # cd deployment # ./build-s3-dist.sh source-bucket-base-name # source-bucket-base-name should be the base name for the S3 bucket location where the template will source the Lambda code from. # The template will append '-[region_name]' to this bucket name. # For example: ./build-s3-dist.sh solutions # The template will then expect the source code to be located in the solutions-[region_name] bucket # Check to see if input has been provided: if [ -z "$1" ]; then echo "Please provide the base source bucket name where the lambda code will eventually reside.\nFor example: ./build-s3-dist.sh solutions" exit 1 fi # Build source echo "Starting to build distribution" echo "export deployment_dir=`pwd`" export deployment_dir=`pwd` echo "mkdir -p dist" mkdir -p dist echo "cp -f serverless-image-handler.template dist" cp -f serverless-image-handler.template dist echo "Updating code source bucket in template with $1" replace="s/%%BUCKET_NAME%%/$1/g" echo "sed -i '' -e $replace dist/serverless-image-handler.template" sed -i '' -e $replace dist/serverless-image-handler.template # SO-SIH-154 - 07/16/2018 - Build fixes # Adding variable for artifact version replace="s/%%VERSION%%/$2/g" echo "sed -i '' -e $replace dist/serverless-image-handler.template" sed -i '' -e $replace dist/serverless-image-handler.template echo "Creating UI ZIP file" cd $deployment_dir/../source/ui zip -q -r9 $deployment_dir/dist/serverless-image-handler-ui.zip * echo "Building custom resource package ZIP file" cd $deployment_dir/dist pwd echo "virtualenv --no-site-packages env" virtualenv --no-site-packages env echo "source env/bin/activate" source env/bin/activate echo "python -m pip install pip==9.0.3" python -m pip install pip==9.0.3 # SO-SIH-157 - 07/17/2018 - Pip version # Checking pip version inside virtualenv for debugging echo "which python pip virtualenv, version" which python && python --version which pip && pip --version which virtualenv && virtualenv --version # Building custom resource zip echo "pip install -q $deployment_dir/../source/image-handler-custom-resource/. --target=$deployment_dir/dist/env/lib/python2.7/site-packages/" pip install -q $deployment_dir/../source/image-handler-custom-resource/. --target=$deployment_dir/dist/env/lib/python2.7/site-packages/ cd $deployment_dir/dist/env/lib/python2.7/site-packages/ zip -r9 $deployment_dir/dist/serverless-image-handler-custom-resource.zip * cd $deployment_dir/dist zip -q -d serverless-image-handler-custom-resource.zip pip* zip -q -d serverless-image-handler-custom-resource.zip easy* rm -rf env # Building image handler zip echo "Building Image Handler package ZIP file" cd $deployment_dir/dist pwd echo "virtualenv --no-site-packages env" virtualenv --no-site-packages env echo "source env/bin/activate" source env/bin/activate echo "python -m pip install pip==9.0.3" python -m pip install pip==9.0.3 echo "which python pip virtualenv, version" which python && python --version which pip && pip --version which virtualenv && virtualenv --version cd ../.. pwd # SO-SIH-159 - 07/25/2018 - Pycurl ssl backend # Configuring compile time ssl backend # https://stackoverflow.com/questions/21096436/ssl-backend-error-when-using-openssl export PYCURL_SSL_LIBRARY=nss # to help with debugging echo "which curl && curl --version" which curl && curl --version echo "which curl-config && curl-config --version" which curl-config && curl-config --version cd $VIRTUAL_ENV pwd # SO-SIH-159 - 07/25/2018 - Curl 7.51.0 # Installing curl 7.51.0 to keep libcurl link-time and compile-time version same # Building pycurl against libcurl 7.51.0 resolves the issue echo "installing curl 7.51.0" wget https://curl.haxx.se/download/curl-7.51.0.tar.gz tar -zxvf curl-7.51.0.tar.gz cd curl-7.51.0 ./configure make make install which curl && curl --version which curl-config && curl-config --version cd $VIRTUAL_ENV cd ../../.. pwd echo "pip install source/image-handler/. --target=$VIRTUAL_ENV/lib/python2.7/site-packages/" pip install source/image-handler/. --target=$VIRTUAL_ENV/lib/python2.7/site-packages/ cd $VIRTUAL_ENV #installing optipng pngcrush gifsicle pngquant jpegtran echo "yum install optipng pngcrush gifsicle libjpeg* pngquant ImageMagick-devel -y" yum install optipng pngcrush gifsicle libjpeg* pngquant ImageMagick-devel -y mkdir $VIRTUAL_ENV/bin/lib cp -f /usr/bin/jpegtran $VIRTUAL_ENV cp -f /usr/bin/optipng $VIRTUAL_ENV cp -f /usr/bin/pngcrush $VIRTUAL_ENV cp -f /usr/bin/gifsicle $VIRTUAL_ENV cp -f /usr/bin/pngquant $VIRTUAL_ENV cp -f /usr/lib64/libimagequant.so* $VIRTUAL_ENV/bin/lib #building mozjpeg cd $VIRTUAL_ENV pwd echo 'yum install nasm autoconf automake libtool -y' yum install nasm autoconf automake libtool -y echo 'wget https://github.com/mozilla/mozjpeg/releases/download/v3.2/mozjpeg-3.2-release-source.tar.gz' wget https://github.com/mozilla/mozjpeg/releases/download/v3.2/mozjpeg-3.2-release-source.tar.gz tar -zxvf mozjpeg-3.2-release-source.tar.gz cd mozjpeg autoreconf -fiv mkdir build && cd build sh ../configure --disable-shared --enable-static make install prefix=/var/task libdir=/var/task cp -f /var/task/libjpeg.so* $VIRTUAL_ENV/bin/lib # SO-SIH-170 - 08/15/2018 - mozjpeg path # mozjpeg executable becomes cjpeg, rectifying path echo "cp -f /var/task/bin/cjpeg $VIRTUAL_ENV" cp -f /var/task/bin/cjpeg $VIRTUAL_ENV #building imgmin cd $VIRTUAL_ENV pwd echo 'git clone https://github.com/rflynn/imgmin.git' git clone https://github.com/rflynn/imgmin.git cd imgmin autoreconf -fi ./configure make make install cd $VIRTUAL_ENV rm -rf imgmin cp -f "/usr/local/bin/imgmin" $VIRTUAL_ENV cp -f /usr/lib64/libMagickWand.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libMagickCore.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libgomp.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libtiff.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libXt.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libltdl.so* $VIRTUAL_ENV/bin/lib cp -f /usr/lib64/libjbig.so* $VIRTUAL_ENV/bin/lib #packing all cd $VIRTUAL_ENV/lib/python2.7/site-packages pwd echo "zip -q -r9 $VIRTUAL_ENV/../serverless-image-handler.zip *" zip -q -r9 $VIRTUAL_ENV/../serverless-image-handler.zip * cd $VIRTUAL_ENV pwd echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip pngquant" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip pngquant echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip jpegtran" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip jpegtran echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip optipng" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip optipng echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip pngcrush" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip pngcrush echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip gifsicle" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip gifsicle echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip mozjpeg/cjpeg" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip cjpeg echo "zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip imgmin" zip -q -g $VIRTUAL_ENV/../serverless-image-handler.zip imgmin cd $VIRTUAL_ENV/bin pwd echo "zip -r -q -g $VIRTUAL_ENV/../serverless-image-handler.zip lib" zip -r -q -g $VIRTUAL_ENV/../serverless-image-handler.zip lib cd $VIRTUAL_ENV pwd cd .. zip -q -d serverless-image-handler.zip pip* zip -q -d serverless-image-handler.zip easy* echo "Clean up build material" rm -rf $VIRTUAL_ENV echo "Completed building distribution"
python setup.py sdist twine check dist/* twine upload dist/*
#!/usr/bin/env bash if [ ! -x ./build/parser ]; then echo 'ERROR: ./build/parser: not found.' echo 'ERROR: you need to run `make` first.' exit 1 fi ZIG=${ZIG:-zig} if [ $# -eq 0 ]; then FILES=(tests/*.zig) else FILES=("$@") fi echo "running ${#FILES[@]} tests..." ANY_FAILURE= for FILE in "${FILES[@]}"; do $ZIG fmt --stdin < "$FILE" > /dev/null 2>&1 zigret=$? ./build/parser < "$FILE" > /dev/null 2>&1 parserret=$? if [ "$zigret" -ne "$parserret" ]; then echo "FAIL: ${FILE}: zig: $zigret, grammar: $parserret" ANY_FAILURE=1 fi done if [ -z "$ANY_FAILURE" ]; then echo 'all tests passed' else exit 1 fi
#!/bin/sh mkdir -p tmp make bin/vm >/dev/null 2>&1 # may not be there yet after release tarball build echo '(lambda (args) (if (equal? (cadr args) "slartibartfast") 0 1))' > tmp/exit.scm $@ -o tmp/exit.fasl tmp/exit.scm bin/vm tmp/exit.fasl 2>/dev/null echo "vm error exit $? should be 126" bin/vm tmp/exit.fasl foo echo "normal nonzero exit $? should be 1" bin/vm tmp/exit.fasl slartibartfast echo "ok exit $? should be 0" rm tmp/exit.scm tmp/exit.fasl
#!/usr/bin/env bash puppet apply --modulepath=/src/apache-2.4/build/modules /src/apache-2.4/build/build.pp
<filename>assets/files/Styles.js 'use strict'; import {Dimensions, Platform} from "react-native"; import ColorsApp from '../../application/utils/ColorsApp'; var React = require('react-native'); var { StyleSheet } = React; var {height, width} = Dimensions.get('window'); export const PrimaryColor = ColorsApp.PRIMARY; export const SecondaryColor = ColorsApp.SECOND; export const TertiaryColor = ColorsApp.TERTIARY; module.exports = StyleSheet.create({ //////////////////////// GENERAL collapseheader:{ backgroundColor: '#fbfbfc', paddingVertical: 15, paddingHorizontal: 15, borderLeftWidth: 3, borderColor: PrimaryColor, justifyContent: 'center' }, collapseicon:{ fontSize: 24, color: PrimaryColor, position: 'absolute', right: 10 }, buttonstyle1:{ backgroundColor: '#fbfbfc', paddingVertical: 15, paddingHorizontal: 15, borderLeftWidth: 3, borderColor: PrimaryColor, justifyContent: 'center', marginBottom: 15 }, buttonstyle1icon:{ fontSize: 24, color: PrimaryColor, position: 'absolute', right: 10 }, buttonstyle2:{ backgroundColor: '#fbfbfc', paddingVertical: 20, paddingHorizontal: 15, justifyContent: 'center', borderLeftWidth: 3, borderColor: PrimaryColor, paddingRight: 24, marginBottom: 15 }, buttonstyle2icon:{ fontSize: 24, color: PrimaryColor, position: 'absolute', right: 10 }, socialicon:{ fontSize: 46, width: 50, height: 50, color: PrimaryColor, }, arrowbackicon:{ color: '#000', fontSize: 27, marginLeft: 30 }, arrowbackiconRight:{ color: '#000', fontSize: 27, marginRight: 30 }, whitecolor:{ color: '#ffffff', }, primarycolor:{ color: PrimaryColor, }, primarybackground:{ backgroundColor: PrimaryColor, }, headerStyle:{ backgroundColor: '#ffffff', shadowOpacity: 0, borderBottomWidth: 0, elevation: 0, }, inputhome:{ backgroundColor: '#ffffff', borderTopLeftRadius: 50, borderBottomLeftRadius: 50, fontSize: 14, paddingLeft: 20, borderWidth: 0 }, inputBgicon:{ backgroundColor: TertiaryColor, width: 52, height: ( Platform.OS === 'ios' ) ? 51 : 50, borderTopRightRadius: 50, borderBottomRightRadius: 50, marginTop: ( Platform.OS === 'ios' ) ? 3 : 1, alignItems: 'center', justifyContent: 'center' }, alert:{ borderLeftWidth: 2, borderColor: TertiaryColor, padding: 10, backgroundColor: '#f7f7f7', borderRadius: 4 }, textalert:{ color: TertiaryColor, fontSize: 14 }, tabBarUnderline:{ backgroundColor: PrimaryColor, }, buyButton:{ backgroundColor: PrimaryColor, padding: 15, paddingLeft: 20, paddingRight: 20, borderRadius: 10, alignItems: 'center', alignContent: 'center', justifyContent: 'center', }, starcolor:{ color: '#f1c40f' }, buyButton2:{ backgroundColor: PrimaryColor, padding: 10, paddingLeft: 20, paddingRight: 20, borderRadius: 10, alignItems: 'center', alignContent: 'center', justifyContent: 'center', }, titlePayment:{ margin: 5, paddingTop: 10, paddingBottom: 10, alignContent: 'center', alignItems: 'center', backgroundColor: '#efefef', borderRadius: 10 }, readmore:{ backgroundColor: '#fff', alignItems: 'center', alignContent: 'center', justifyContent: 'center', width: 50, height: 50, position: 'absolute', right: 15, borderRadius: 50, top: 30, zIndex: 99999 }, readmoreIcon:{ fontSize: 22, color: PrimaryColor }, categoryOffer:{ color: 'rgba(255,255,255,0.5)', fontSize: 12, marginBottom: 8 }, secondcolor:{ color: PrimaryColor, }, padding_general:{ padding: 20, backgroundColor: '#FFF' }, background_general:{ backgroundColor: '#FFF' }, card_general:{ width: width*0.95, height: height*0.43, borderRadius: 8 }, buttonCard:{ paddingHorizontal: 10, paddingVertical: 3, backgroundColor: PrimaryColor, borderRadius: 5, marginTop: 5 }, socialIcon:{ fontSize: 46, width: 50, height: 50, color: PrimaryColor }, gradient_general:{ position: 'absolute', padding:15, left: 0, right: 0, bottom: 0, height: '100%', alignItems: 'center', justifyContent: 'center', borderRadius: 8 }, title_general:{ color: '#FFF', fontSize: 24, fontWeight: 'bold', marginBottom: 5 }, subtitle_general:{ color: '#FFF', fontSize: 14, fontWeight: 'bold' }, touchBookmark:{ backgroundColor: PrimaryColor, width: 50, height: 50, position: 'absolute', right: 15, bottom: -25, borderRadius: 50, alignItems: 'center', justifyContent: 'center' }, touchBookmarkTran:{ backgroundColor: 'rgba(0,0,0,0.4)', width: 50, height: 50, position: 'absolute', right: 15, top: 10, borderRadius: 50, alignItems: 'center', justifyContent: 'center' }, pickerinput:{ width: width * .9, borderWidth: 1, justifyContent: 'center', height: 55, borderColor: 'rgba(0,0,0,0.2)', borderRadius: 50, marginBottom: 15 }, pickericon:{ fontSize: 22, paddingRight: 17, paddingTop: 3, color: PrimaryColor }, //////////////////////// DETAILS label_details:{ color: PrimaryColor, fontSize: 15, fontWeight: 'bold', marginBottom: 3 }, //////////////////////// QUOTES quote:{ borderLeftWidth: 5, borderColor: PrimaryColor, marginHorizontal: 20, marginVertical: 8, backgroundColor: '#fbfbfc', minHeight: 90, alignItems: 'flex-start', justifyContent: 'center', paddingHorizontal: 20, paddingVertical: 20 }, textquote:{ fontSize: 15, fontWeight: 'bold' }, copyquote:{ fontSize: 13, fontWeight: 'bold' }, //////////////////////// CATEGORIES title_categories:{ color: '#FFF', fontSize: 14, fontWeight: 'bold' }, title_categories_background:{ width: width*0.95, alignItems: 'center', padding: 15, borderBottomLeftRadius: 8, borderBottomRightRadius: 8 }, title_categories_border:{ height: 2, backgroundColor: PrimaryColor, width: 50 }, gradient_categories:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height*0.21, alignItems: 'center', justifyContent: 'flex-end', borderRadius: 8 }, background_categories:{ width: width*0.95, height: height*0.21, alignItems: 'center', justifyContent: 'flex-end', marginBottom: 10, borderRadius: 8 }, gradient_2columns:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height /4.50, width : null, alignItems: 'center', justifyContent: 'flex-end', borderRadius: 8, }, title_2columns_background:{ width: null, alignSelf: 'stretch', alignItems: 'center', borderBottomRightRadius: 8, borderBottomLeftRadius: 8, padding: 15 }, background_2columns:{ height: height /4.50, width : null, borderRadius: 8, alignItems: 'center', justifyContent: 'flex-end', }, background_exercises:{ height: height /4.50, width : null, borderRadius: 8, alignItems: 'flex-start', justifyContent: 'flex-end', }, //////////////////////// POSTS title_posts_categories:{ color: '#FFF', fontSize: 13, padding: 10, fontWeight: 'bold', paddingTop: 2 }, date_posts:{ color: 'rgba(255,255,255,0.50)', fontSize: 11, padding: 10, paddingBottom: 0, fontWeight: 'bold' }, gradient_posts_2columns:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height * 0.15, alignItems: 'flex-start', justifyContent: 'flex-end', borderRadius: 8 }, background_posts_2columns:{ width: width * 0.46, height: height * 0.15, alignItems: 'flex-start', justifyContent: 'flex-end', }, postDetail_background:{ width: width, height: height * 0.25, alignItems: 'center', justifyContent: 'center', }, postDetail_gradient:{ position: 'absolute', padding:15, left: 0, right: 0, bottom: 0, height: height * 0.10, alignItems: 'flex-start', justifyContent: 'flex-end' }, postDetail_title:{ fontSize: 20, color: '#FFFFFF', fontWeight: 'bold', lineHeight: 25, }, postDetail_tag:{ fontSize: 15, fontWeight: 'bold', color: PrimaryColor, lineHeight: 30, }, postDetail_date:{ fontSize: 12, fontWeight: '300', color: '#666', paddingRight: 14 }, postCommentButton:{ backgroundColor: PrimaryColor, borderRadius: 6, padding: 20, alignItems: 'center', justifyContent: 'center', alignContent: 'center', }, postCommentText:{ color: '#FFFFFF', fontSize: 14, fontWeight: 'bold', }, commentTitle:{ color: '#000', fontSize: 14, fontWeight: 'bold', marginBottom: 10, }, showcomments:{ width: width * 0.93, backgroundColor: '#fff', borderWidth: 1, borderColor: '#666', marginTop: 12, height: 40, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 }, borderRadius: 6, alignItems: 'center', alignContent: 'center', justifyContent: 'center', }, //////////////////////// DIETS gridDietImage:{ width: 50, height: 50, marginBottom: 15, marginTop: 20 }, gridDietText:{ color: PrimaryColor, fontSize: 14, fontWeight: 'bold' }, gridDietCol:{ alignItems: 'center', justifyContent: 'center', alignContent: 'center', height: height*0.19 }, title_diets:{ color: '#FFF', fontSize: 20, marginBottom: 15, fontWeight: 'bold' }, title_diets_categories:{ color: '#FFF', fontSize: 14, padding: 10, fontWeight: 'bold' }, category_diets:{ color: PrimaryColor, fontSize: 14, backgroundColor: 'transparent', fontWeight: 'bold', marginBottom: 5, }, subcategory_diets:{ color: '#FFF', fontSize: 15, opacity: 0.5, marginBottom: 10, }, gradient_ddiet:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height * 0.35, paddingHorizontal: 20, paddingVertical: 20, alignItems: 'flex-start', justifyContent: 'flex-end', }, gradient_diets:{ position: 'absolute', padding:15, left: 0, right: 0, bottom: 0, height: height * 0.39, alignItems: 'flex-start', justifyContent: 'flex-end' }, background_diets:{ width: width, height: height * 0.39, alignItems: 'flex-start', justifyContent: 'flex-end', padding: 15 }, gradient_diets_2columns:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height * 0.15, alignItems: 'flex-start', justifyContent: 'flex-end' }, background_diets_2columns:{ width: width * 0.46, height: height * 0.15, alignItems: 'flex-start', justifyContent: 'flex-end', }, background_diets_col:{ width: width, height: height * 0.25, alignItems: 'center', justifyContent: 'center', }, info_diets:{ backgroundColor: 'rgba(0,0,0,0.70)', alignItems: 'center', justifyContent: 'center', padding: 6, paddingBottom: 11, paddingTop: 11 }, title_diets_detail:{ fontSize: 22, fontWeight: 'normal', lineHeight: 30, }, gtitle_diets_detail:{ fontSize: 16, fontWeight: 'bold', }, description_diets_detail:{ fontSize: 14, }, col_diets: { height: 70, alignItems: 'center', justifyContent: 'center' }, icon_dietscol:{ width: 34, height: 34, marginBottom: 10 }, titlecol_diets: { fontSize: 15, marginTop: 8, }, titlecol1_diets: { fontWeight: 'bold', fontSize: 14, }, headerProfile:{ width: width, height: height * 0.12, alignItems: 'center', justifyContent: 'center', backgroundColor: PrimaryColor, marginTop: -1 }, nameProfile:{ color: '#fff', fontWeight: 'bold', fontSize: 18, marginTop: 6 }, tabs: { backgroundColor: PrimaryColor, }, activetabs: { backgroundColor: PrimaryColor, }, tabs_text: { color: 'rgba(255,255,255,0.4)', fontWeight: 'normal', fontSize: 13 }, activetabs_text: { color: '#fff', fontWeight: 'bold', fontSize: 13 }, tabs_2: { backgroundColor: '#fafafa', }, activetabs_2: { backgroundColor: '#fafafa', }, tabs_text_2: { color: 'rgba(0,0,0,0.3)', fontWeight: 'normal' }, activetabs_text_2: { color: TertiaryColor, fontWeight: 'normal' }, //////////////////////// CARDS title_card:{ color: '#FFF', fontSize: 16, marginBottom: 6, fontWeight: 'bold' }, category_card:{ marginBottom: 6, color: PrimaryColor, fontWeight: 'bold', fontSize: 14, }, category_card_2:{ color: '#FFF', opacity: 0.8, marginBottom: 3, fontSize: 14 }, subcategory_card:{ color: PrimaryColor, fontSize: 14, }, price:{ color: '#f1c40f', fontSize: 14, marginRight: 5, fontWeight: 'bold' }, oldprice:{ color: '#FFF', fontSize: 12, opacity: 0.8, textDecorationLine: 'line-through' }, detailPrice:{ fontWeight: 'bold', fontSize: 19, marginBottom: 3, }, detailOldPrice:{ fontSize: 15, color: '#888888' }, detailPrice2:{ fontWeight: 'bold', fontSize: 19, color: PrimaryColor }, totalprice:{ fontSize: 13, marginBottom: 3, color: '#fff' }, savePrice:{ marginBottom: 5, marginTop: 5, backgroundColor: '#ddedd1', alignSelf: 'flex-start', padding: 5, paddingLeft: 7, paddingRight: 7, borderRadius: 5 }, saveTextPrice:{ fontSize: 15, color: '#367806', }, saveHomePrice:{ marginBottom: 5, marginTop: 5, backgroundColor: '#ddedd1', alignSelf: 'flex-start', padding: 5, paddingLeft: 7, paddingRight: 7, borderRadius: 5 }, saveTextHomePrice:{ fontSize: 13, color: '#367806', }, gradient_card:{ position: 'absolute', padding:15, left: 0, right: 0, bottom: 0, height: height * 0.23, alignItems: 'flex-start', justifyContent: 'flex-end', borderRadius: 8 }, background_card:{ width: width*0.95, height: height * 0.23, alignItems: 'flex-start', justifyContent: 'flex-end', padding: 15, marginBottom: 10 }, //////////////////////// WORKOUT DETAILS title_workout:{ color: '#FFF', fontSize: 18, marginBottom: 5, fontWeight: 'bold', paddingTop: 40 }, category_workout:{ color: PrimaryColor, fontSize: 16, fontWeight: 'bold' }, gradient_workout:{ position: 'absolute', left: 0, right: 0, bottom: 0, height: height * 0.35, alignItems: 'center', justifyContent: 'center' }, background_workout:{ width: width, height: height * 0.35, alignItems: 'center', justifyContent: 'center', }, col_workout: { height: 70, alignItems: 'center', justifyContent: 'center' }, titlecol_workout: { fontWeight: 'bold', fontSize: 16, color: '#fff', marginBottom: 3 }, icon_workout:{ fontSize: 22, color: PrimaryColor, position: 'absolute', right: 15 }, textButton_workout:{ color: '#000', fontSize: 15, fontWeight: 'bold', }, button_workout:{ backgroundColor: '#fbfbfc', justifyContent: "center", alignItems: 'flex-start', height: 50, paddingHorizontal: 20, elevation: 0, shadowOpacity: 0, marginVertical: 8, marginHorizontal: 15, borderLeftWidth: 2, borderColor: PrimaryColor, }, //////////////////////// EXERCISE footer_exercise:{ backgroundColor: '#fff', borderColor: '#fff', marginTop: 10, marginBottom: 5, elevation: 0, shadowOpacity: 0, }, start_exercise:{ backgroundColor: '#fff', borderColor: PrimaryColor, borderWidth: 1, elevation: 0, shadowOpacity: 0, borderRadius: 5, width: width * 0.9 }, textStart_exercise:{ color: PrimaryColor, fontSize: 16, fontWeight: 'bold' }, col_exercise:{ alignItems: 'center', justifyContent: 'center' }, titlecol_exercise: { fontWeight: 'bold', marginTop: 2, marginBottom: 6, fontSize: 16, }, title_exercise_background:{ width: width, alignItems: 'flex-start', padding: 15 }, subtitle_exercise:{ color: PrimaryColor, }, bannerAd:{ position: 'absolute', bottom: 25, alignItems: 'center', justifyContent: 'center', alignContent: 'center', backgroundColor: 'transparent', width: width }, bannerAdLight:{ position: 'absolute', bottom: 10, alignItems: 'center', justifyContent: 'center', alignContent: 'center', backgroundColor: 'transparent', width: width }, icon_get:{ fontSize: 14, fontWeight: 'bold', color: PrimaryColor }, icon_exercise:{ fontSize: 40, color: PrimaryColor, marginTop: 10, marginBottom: 7 }, icon_videoexercise:{ width: 50, height: 50, marginTop: 10, marginBottom: 7 }, playButton:{ backgroundColor: PrimaryColor, elevation: 0, shadowOpacity: 0 }, playCol_exercise:{ alignItems: 'center', justifyContent: 'center', margin: 15 }, //////////////////////// START socialFacebook:{ minWidth: 250, backgroundColor: '#fff', borderWidth: 1, borderColor: '#fff', borderRadius: 100, marginBottom: 11, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 } }, button_start_1:{ minWidth: 250, backgroundColor: PrimaryColor, borderWidth: 1, borderColor: PrimaryColor, borderRadius: 25, marginBottom: 11, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 } }, button_start:{ minWidth: 250, backgroundColor: 'transparent', borderWidth: 1, borderColor: '#fff', borderRadius: 25, marginBottom: 11, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 } }, button_start_text:{ fontWeight: 'bold', color: PrimaryColor, fontSize: 14 }, button_start_2:{ width: width * 0.80, marginBottom: 11, height: 53, borderRadius: 25, alignItems: 'center', alignContent: 'center', justifyContent: 'center', shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 }, }, logo_start:{ width: 200, height: 200, marginTop: 15, marginBottom: 5}, logo_login:{ width: 200, height: 200, marginTop: 15, marginBottom: 30}, button_contact:{ width: width * 0.92, backgroundColor: PrimaryColor, marginBottom: 8, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 }, borderRadius: 6, alignItems: 'center', alignContent: 'center', justifyContent: 'center', }, //////////////////////// LOGIN & SIGNUP button_auth:{ width: width * 0.80, backgroundColor: PrimaryColor, marginBottom: 8, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 }, borderRadius: 25, alignItems: 'center', alignContent: 'center', justifyContent: 'center', }, text_auth:{ backgroundColor: 'transparent', textAlign:'center', maxWidth: 300, minWidth: 300, marginTop: 5, fontSize: 13, color: '#808080', shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 } }, inputLogin:{ backgroundColor: '#FFFFFF', width: width*0.80, shadowRadius: 5, marginBottom: 10, borderColor: '#a4a4a4', color: '#a4a4a4' }, //////////////////////// HOME listitem_home:{ borderBottomWidth: 0, backgroundColor: 'transparent', }, icon_home:{ fontSize: 20, color: '#ddd' }, note_home:{ fontSize: 13, }, gridHomeImage:{ width: 50, height: 50, marginBottom: 15, marginTop: 20 }, gridHomeText:{ color: '#fff', fontSize: 14, fontWeight: 'bold', opacity: 0.6 }, gridHomeCol:{ alignItems: 'center', justifyContent: 'center', alignContent: 'center', height: height*0.19 }, //////////////////////// CALCULATOR calctitle:{ color: PrimaryColor, justifyContent: "center", alignSelf: "center", marginTop: 30, fontSize: 18, fontWeight: 'bold' }, calcsubtitle:{ color: '#999', justifyContent: "center", alignSelf: "center", marginTop: 10, fontSize: 16, }, calcinput:{ backgroundColor: '#FFFFFF', width: width*0.50, shadowRadius: 5, marginBottom: 10, borderColor: '#a4a4a4', paddingHorizontal: 15, color: '#a4a4a4' }, calcbutton: { width: width * 0.50, backgroundColor: TertiaryColor, justifyContent: "center", marginBottom: 8, height: 53, shadowOpacity: 0, shadowRadius: 0, elevation: 0, shadowOffset: { width: 0, height: 0 }, }, calcbuttonText: { alignSelf: "center", padding: 30, fontSize: 25, color: '#fff', fontWeight: "bold" }, calcresultnumber: { alignSelf: "center", color: PrimaryColor, fontSize: 55, padding: 15 }, calcresulttext: { alignSelf: "center", color: PrimaryColor, fontSize: 25, padding: 15 }, bmicol:{ alignItems: 'center', justifyContent: 'center', margin: 4, borderRadius: 4, }, bmi1col:{ alignItems: 'flex-start', justifyContent: 'center', margin: 4, borderRadius: 4, backgroundColor: '#f1f2f6', paddingLeft: 25 }, bmicoltext:{ fontWeight: 'bold', fontSize: 16 }, bmicolnumber:{ fontWeight: 'bold', fontSize: 16 }, //////////////////////// MENU container_menu: { flex: 1, backgroundColor: '#ffffff' }, item_menu:{ borderBottomWidth: 0, borderBottomColor: '#FFFFFF', marginLeft: 0, paddingRight: 20, paddingLeft: 40, marginBottom: 3, marginTop: 3 }, text_menu:{ fontSize: 14, color: TertiaryColor, fontWeight: 'bold', }, iconSidemenu:{ color: TertiaryColor, fontSize: 25 }, sideMenu:{ backgroundColor: '#ffffff', flexDirection:'column', justifyContent: 'center', alignItems: 'center', height: height * 0.29, marginTop: 25, padding:25 }, thumbnail_menu:{ marginRight: 10, maxWidth: 40 }, icon_menu:{ fontSize: 18, color: '#b5b5b5', opacity: 0.5 }, footer_menu: { padding: 25, alignItems: 'center', justifyContent: 'center', alignContent: 'center', backgroundColor: TertiaryColor }, wrapper: { paddingTop: 50, flex: 1 }, modal: { }, modal3: { height: 'auto', maxHeight: height * 0.60, width: width * 0.80, padding: 20, paddingTop: 10, paddingBottom: 10, borderRadius: 8 }, });
from collections import deque def minSteps(maze): directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] portals = {} start = end = None for y in range(len(maze)): for x in range(len(maze[0])): if maze[y][x] == 'S': start = (x, y) elif maze[y][x] == 'E': end = (x, y) elif maze[y][x].isalpha(): if maze[y][x] not in portals: portals[maze[y][x]] = [] portals[maze[y][x]].append((x, y)) bfs = deque([(start, 0)]) seen = set() while bfs: (x, y), dist = bfs.popleft() if (x, y) == end: return dist for dx, dy in directions: tx, ty = x + dx, y + dy if 0 <= tx < len(maze[0]) and 0 <= ty < len(maze) and maze[ty][tx] != '#': if (tx, ty, dist) not in seen: seen.add((tx, ty, dist)) if maze[ty][tx] == '.': bfs.append(((tx, ty), dist + 1)) if maze[ty][tx].isalpha(): p = (tx, ty) s = (p, dist + 1) bfs.append(s) return -1
<reponame>smagill/opensphere-desktop<filename>open-sphere-base/core/src/main/java/io/opensphere/core/cache/accessor/PropertyAccessor.java package io.opensphere.core.cache.accessor; import io.opensphere.core.cache.util.PropertyDescriptor; /** * A property accessor. This provides a mechanism for getting properties from * objects without the property consumer knowing what kind of object the * properties are coming from. This also avoids the memory consumption of * constructing large collections of properties to pass to the property * consumer. * * @param <S> The type of object that provides the property values. * @param <T> The type of the property values. */ public interface PropertyAccessor<S, T> { /** * Get the property value from an input object. * * @param input The input object. * @return The property value. */ T access(S input); /** * Get a description of the property that this accessor provides. * * @return The property descriptor. */ PropertyDescriptor<T> getPropertyDescriptor(); }
#!/usr/bin/env bash # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. declare -i missing_env=0 # Validate params for required_env in "TESTS" "PERSONALITY_FILE" "BASEDIR" "ARCHIVE_PATTERN_LIST" "OUTPUT_DIR_RELATIVE" \ "OUTPUT_DIR" "PROJECT" "AUTHOR_IGNORE_LIST" \ "WHITESPACE_IGNORE_LIST" "BRANCH_NAME" "TESTS_FILTER" "DEBUG" \ "USE_YETUS_PRERELEASE" "WORKSPACE" "YETUS_RELEASE"; do if [ -z "${!required_env}" ]; then echo "[ERROR] Required environment variable '${required_env}' is not set." missing_env=${missing_env}+1 fi done if [ ${missing_env} -gt 0 ]; then echo "[ERROR] Please set the required environment variables before invoking. If this error is " \ "on Jenkins, then please file a JIRA about the error." exit 1 fi YETUS_ARGS=() if [[ -n "${MULTIJDK}" ]]; then YETUS_ARGS=("--multijdktests=compile,javadoc" "${YETUS_ARGS[@]}") YETUS_ARGS=("--multijdkdirs=${MULTIJDK}" "${YETUS_ARGS[@]}") fi if [[ -n "${SET_JAVA_HOME}" ]]; then YETUS_ARGS=("--java-home=${SET_JAVA_HOME}" "${YETUS_ARGS[@]}") fi YETUS_ARGS=("--plugins=${TESTS}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--personality=${PERSONALITY_FILE}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--basedir=${BASEDIR}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--archive-list=${ARCHIVE_PATTERN_LIST}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--console-urls" "${YETUS_ARGS[@]}") # YETUS-532, repeat this twice in case the fix is to update args rather than docs YETUS_ARGS=("--build-url-patchdir=artifact/${OUTPUT_DIR_RELATIVE}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--build-url-artifacts=artifact/${OUTPUT_DIR_RELATIVE}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--docker" "${YETUS_ARGS[@]}") YETUS_ARGS=("--dockerfile=${BASEDIR}/dev-support/docker/Dockerfile" "${YETUS_ARGS[@]}") # Yetus sets BUILDMODE env variable to "full" if this arg is passed. YETUS_ARGS=("--empty-patch" "${YETUS_ARGS[@]}") YETUS_ARGS=("--html-report-file=${OUTPUT_DIR}/console-report.html" "${YETUS_ARGS[@]}") YETUS_ARGS=("--jenkins" "${YETUS_ARGS[@]}") YETUS_ARGS=("--mvn-custom-repos" "${YETUS_ARGS[@]}") YETUS_ARGS=("--patch-dir=${OUTPUT_DIR}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--project=${PROJECT}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--resetrepo" "${YETUS_ARGS[@]}") YETUS_ARGS=("--author-ignore-list=${AUTHOR_IGNORE_LIST}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--whitespace-eol-ignore-list=${WHITESPACE_IGNORE_LIST}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--whitespace-tabs-ignore-list=${WHITESPACE_IGNORE_LIST}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--sentinel" "${YETUS_ARGS[@]}") YETUS_ARGS=("--branch=${BRANCH_NAME}" "${YETUS_ARGS[@]}") YETUS_ARGS=("--tests-filter=${TESTS_FILTER}" "${YETUS_ARGS[@]}") # Why are these not being picked up from hbase-personality? YETUS_ARGS=("--proclimit=10000" "${YETUS_ARGS[@]}") YETUS_ARGS=("--dockermemlimit=20g" "${YETUS_ARGS[@]}") if [[ -n "${EXCLUDE_TESTS_URL}" ]]; then YETUS_ARGS=("--exclude-tests-url=${EXCLUDE_TESTS_URL}" "${YETUS_ARGS[@]}") fi if [[ -n "${INCLUDE_TESTS_URL}" ]]; then YETUS_ARGS=("--include-tests-url=${INCLUDE_TESTS_URL}" "${YETUS_ARGS[@]}") fi # For testing with specific hadoop version. Activates corresponding profile in maven runs. if [[ -n "${HADOOP_PROFILE}" ]]; then YETUS_ARGS=("--hadoop-profile=${HADOOP_PROFILE}" "${YETUS_ARGS[@]}") fi if [[ true == "${DEBUG}" ]]; then YETUS_ARGS=("--debug" "${YETUS_ARGS[@]}") fi if [[ ! -d "${OUTPUT_DIR}" ]]; then echo "[ERROR] the specified output directory must already exist: '${OUTPUT_DIR}'" exit 1 fi if [[ true != "${USE_YETUS_PRERELEASE}" ]]; then YETUS_ARGS=("--shelldocs=${WORKSPACE}/yetus-${YETUS_RELEASE}/bin/shelldocs" "${YETUS_ARGS[@]}") TESTPATCHBIN="${WORKSPACE}/yetus-${YETUS_RELEASE}/bin/test-patch" else YETUS_ARGS=("--shelldocs=${WORKSPACE}/yetus-git/shelldocs/shelldocs.py" "${YETUS_ARGS[@]}") TESTPATCHBIN="${WORKSPACE}/yetus-git/precommit/test-patch.sh" fi echo "Launching yetus with command line:" echo "${TESTPATCHBIN} ${YETUS_ARGS[*]}" /usr/bin/env bash "${TESTPATCHBIN}" "${YETUS_ARGS[@]}"
MININIX_PKG_HOMEPAGE=http://tinyscheme.sourceforge.net/home.html MININIX_PKG_DESCRIPTION="Very small scheme implementation" MININIX_PKG_VERSION=1.41 MININIX_PKG_REVISION=1 MININIX_PKG_SRCURL=http://downloads.sourceforge.net/project/tinyscheme/tinyscheme/tinyscheme-1.41/tinyscheme-1.41.tar.gz MININIX_PKG_SHA256=eac0103494c755192b9e8f10454d9f98f2bbd4d352e046f7b253439a3f991999 MININIX_PKG_BUILD_IN_SRC=yes mininix_step_pre_configure () { AR+=" crs" LD=$CC } mininix_step_post_make_install () { mkdir -p $MININIX_PREFIX/share/tinyscheme/ cp $MININIX_PKG_SRCDIR/init.scm $MININIX_PREFIX/share/tinyscheme/ }
<filename>src/main/java/org/slos/services/DelayService.java package org.slos.services; import org.slos.AppConfig; import org.slos.TeamRequestProcessStep; import org.slos.domain.TeamRequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import java.util.List; public class DelayService implements TeamRequestProcessStep { @Autowired AppConfig appConfig; @Value("${defaults.delaySubmission:false}") boolean delayToMaxTime; private final Logger logger = LoggerFactory.getLogger(DelayService.class); @Override public TeamRequestContext processStep(TeamRequestContext teamRequestContext) { if (!teamRequestContext.getTeamRequest().getTournamentGame()) { Boolean implementDelay = delayToMaxTime; List<String> delayAgainst = appConfig.getUseMaxTimeAgainst(); if (delayAgainst != null && delayAgainst.contains(teamRequestContext.getTeamRequest().getPlayerBottom())) { implementDelay = true; } if (implementDelay) { Long returnAt = teamRequestContext.getTeamRequestTimeout(); Long timeToDelay = returnAt - System.currentTimeMillis(); try { logger.info("Delaying for " + timeToDelay + " against: " + teamRequestContext.getTeamRequest().getPlayerBottom()); Thread.sleep(timeToDelay); } catch (Exception e) { } } } return teamRequestContext; } }
package com.atjl.common.api.resp1; import com.atjl.common.constant.RespConstant; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 对外response dto,包含附加数据 * * @author atjl * @since 1.0 */ @ApiModel("结果集对象V1") public class ResponseDataDtoV1 extends ResponseDtoV1 { // private static final long serialVersionUID = 1L; @ApiModelProperty(value = "结果集数据") private Object result = null; // public static final int UNKNOWN_ERROR = 1004; public ResponseDataDtoV1() { super(); } public ResponseDataDtoV1(int code, String msg) { this.code = code; this.msg = msg; } public ResponseDataDtoV1(Object data) { super(); this.result = data; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public static ResponseDataDtoV1 buildOk() { return new ResponseDataDtoV1(RespConstant.SUCCESS_CODE, RespConstant.SUCC_MSG); } public static ResponseDataDtoV1 buildOk(Object obj) { ResponseDataDtoV1 resp = new ResponseDataDtoV1(); resp.setResult(obj); return resp; } public static ResponseDataDtoV1 buildFail(String msg) { ResponseDataDtoV1 resp = new ResponseDataDtoV1(); resp.setSucc(RespConstant.FAIL_MSG); resp.setCode(RespConstant.UNKNOWN_ERROR_CODE); resp.setMsg(msg); return resp; } public static ResponseDataDtoV1 buildFail(int code, String msg) { ResponseDataDtoV1 resp = new ResponseDataDtoV1(); resp.setSucc(RespConstant.FAIL_MSG); resp.setCode(code); resp.setMsg(msg); return resp; } public static ResponseDataDtoV1 buildFail(int code, String msg, Object data) { ResponseDataDtoV1 resp = new ResponseDataDtoV1(); resp.setResult(data); resp.setCode(code); resp.setMsg(msg); return resp; } }
<gh_stars>10-100 package io.opensphere.mantle.plugin.selection; import java.util.Collection; import io.opensphere.core.geometry.PolygonGeometry; /** * The Interface SelectionCommandProcessor. */ @FunctionalInterface public interface SelectionCommandProcessor { /** * Notifies a processor that a selection command occurred. * * @param bounds the bounds * @param cmd the command. */ void selectionOccurred(Collection<? extends PolygonGeometry> bounds, SelectionCommand cmd); }
const colors = { PRIMARY: '#03a678', PRIMARY_DARKEN: '#0d7557', SECONDARY: '#ce2a36', WHITE: '#fff', LIGHTEST_GREY: '#dcdcdc', LIGHT_GREY: '#d3d3d3', MEDIUM_GREY: '#c0c0c0', DARK_GREY: '#808080', DARKEST_GREY: '#696969', DARKEST_GREY_2: '#393939', ORANGE_1: '#FFB55F', ORANGE_2: '#F49A30', ORANGE_3: '#F8892C', ORANGE_4: '#EC720B', ORANGE_5: '#C85F01', BLACK: '#20201e', DEFAULT_BLACK: '#000', }; const sizes = { DEFAULT: '16px', LARGE: '32px', HALF: '8px', RADIUS: '4px', FULL: '100%', }; const breakpoints = { SMALL: '768px', NORMAL: '1024px', BIG: '1280px', LARGE: '1440px', }; const fontSizes = { HUGE1: '48px', HUGE2: '36px', LARGE: '32px', BIG: '20px', NORMAL: '16px', SMALL: '14px', EXTRASMALL: '12px', TINY: '10px', }; const fontWeights = { LIGHT: '300', REGULAR: '400', MEDIUM: '500', SEMIBOLD: '600', BOLD: '700', }; export const zIndexes = { HELL: -1, GROUND: 1, SKY: 2, STRATOSPHERE: 3, MILKAWAY: 4, UNIVERSE: 5, }; const fonts = { DEFAULT: 'Montserrat', }; export { breakpoints, colors, fonts, fontSizes, fontWeights, sizes, };
#!/bin/bash #============================================================ # https://github.com/P3TERX/Actions-OpenWrt # File name: diy-part2.sh # Description: OpenWrt DIY script part 2 (After Update feeds) # Lisence: MIT # Author: P3TERX # Blog: https://p3terx.com #============================================================ # Modify default IP sed -i 's/192.168.2.1/192.168.1.11/g' package/base-files/files/bin/config_generate
<reponame>mjburling/beneficiary-fhir-data package gov.cms.bfd.pipeline.sharedutils.jobs.store; import gov.cms.bfd.pipeline.sharedutils.PipelineJob; import gov.cms.bfd.pipeline.sharedutils.PipelineJobArguments; import gov.cms.bfd.pipeline.sharedutils.PipelineJobOutcome; import gov.cms.bfd.pipeline.sharedutils.PipelineJobRecordId; import gov.cms.bfd.pipeline.sharedutils.PipelineJobType; import gov.cms.bfd.sharedutils.exceptions.BadCodeMonkeyException; import java.time.Duration; import java.time.Instant; import java.util.Optional; /** * Models the status of a {@link PipelineJob} that has been submitted for execution. This is * basically a state machine data store, that models the various states and transitions that a job * can proceed through. Jobs can be in the following states: * * <ul> * <li>Created: This is the initial state for every job. * <li>Canceled: Jobs can be cancelled before or during execution. * <li>Enqueued: Once a job has been submitted for execution. * <li>Started: Once a job has started running. * <li>Completed (Succeeded): A job that has successfully finished running, without exceptions. * <li>Completed (Failed): A job that started running but then threw an exception, rather than * completing successfully. * </ul> * * <p>Design Note: I considered coding this <em>as</em> an actual state machine, but all of the * libraries and patterns available for doing so in Java looked like they'd add more complexity than * they removed. Also: if we ever decided to scale job execution across multiple nodes, this * data/class would need to become a JPA entity, and none of the state machine patterns seemed * suited to that. For example, <a href="https://spring.io/projects/spring-statemachine">Spring * Statemachine</a> will persist all of the state machine's data as a combined serialized blob, * which is not what we need. */ public final class PipelineJobRecord<A extends PipelineJobArguments> { private final PipelineJobRecordId id; private final PipelineJobType<A> jobType; private final A jobArguments; private final Instant createdTime; private Optional<Instant> canceledTime; /** * "Why is this variable {@code volatile}," you might ask? Good question! The short answer is the * unhelpful, "because things can crash unless it is." The <em>better</em> answer is complicated: * When the VolunteerJob is bootstrapped, it's enqueued by PipelineManager's constructor, and ends * up setting this field -- on the application's main thread. Then, VolunteerJob starts running, * and goes looking for non-enqueued jobs. Unless this field is volatile, it will sometimes "find * itself" (lol), thinking that it's not enqueued, because it's reading a stale value of it. That * causes things to go boom. So: we mark this as volatile, and everything's copacetic. Isn't * concurrency fun?! * * <p>There's also be an issue with the other jobs, where they get enqueued by the VolunteerJob on * its thread and then, when they try to fire their start event on their thread, notice that * they're not enqueued and freak out about it. Marking this as {@code volatile} fixes that, too. * * <p>"Okay, so why aren't the other fields {@code volatile}, too," you might then ask? Also a * good question! It's because the start and completed events always run on the job's worker * thread and those events aren't queried on any other threads for anything important. (Worth * noting: the {@code final} are safe, just due to how they're treated in the Java Memory Model.) * * <p>"You left out cancel, though," you might follow up with. Good catch! But mostly, it just * doesn't really matter, even though it is set by a different thread, as it's not relied on for * anything important. * * <p>If <strong>any</strong> of these other fields end up landing in application logic, we may * need to mark them volatile -- depending on exactly how they're used and accessed. */ private volatile Optional<Instant> enqueuedTime; private Optional<Instant> startedTime; private Optional<Instant> completedTime; private Optional<PipelineJobOutcome> outcome; private Optional<PipelineJobFailure> failure; /** * Constructs a new {@link PipelineJobRecord} instance. * * @param jobType the value to use for {@link #getJobType()} * @param jobArguments the value to use for {@link #getJobArguments()} */ public PipelineJobRecord(PipelineJobType<A> jobType, A jobArguments) { this.id = new PipelineJobRecordId(); this.jobType = jobType; this.jobArguments = jobArguments; this.createdTime = Instant.now(); this.canceledTime = Optional.empty(); this.enqueuedTime = Optional.empty(); this.startedTime = Optional.empty(); this.completedTime = Optional.empty(); this.outcome = Optional.empty(); this.failure = Optional.empty(); } /** * @return the {@link PipelineJobRecordId} that uniquely identifies this {@link PipelineJobRecord} */ public PipelineJobRecordId getId() { return id; } /** @return the {@link PipelineJobType} that this {@link PipelineJobRecord} is for */ public PipelineJobType<A> getJobType() { return jobType; } /** * @return the {@link PipelineJobArguments} that the job should be run with, if any (<code>null * </code> if there are none) */ public A getJobArguments() { return jobArguments; } /** @return the {@link Instant} that this {@link PipelineJobRecord} was created at */ public Instant getCreatedTime() { return createdTime; } /** @return the {@link Instant} that this job was canceled at, if any */ public Optional<Instant> getCanceledTime() { return canceledTime; } /** @return <code>true</code> if the job has been canceled, <code>false</code> if it has not */ public boolean isCanceled() { return canceledTime.isPresent(); } /** @param canceledTime the value to set {@link #getCanceledTime()} to */ public void setCanceledTime(Instant canceledTime) { if (this.canceledTime.isPresent()) throw new BadCodeMonkeyException(); if (this.completedTime.isPresent()) throw new BadCodeMonkeyException(); this.canceledTime = Optional.of(canceledTime); } /** @return the {@link Instant} that this job was enqueued to an executor for execution, if any */ public Optional<Instant> getEnqueuedTime() { return enqueuedTime; } /** @param enqueuedTime the value to set {@link #getEnqueuedTime()} to */ public void setEnqueuedTime(Instant enqueuedTime) { // Validate the state transition. if (this.enqueuedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.canceledTime.isPresent()) throw new BadCodeMonkeyException(); if (this.startedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.completedTime.isPresent()) throw new BadCodeMonkeyException(); this.enqueuedTime = Optional.of(enqueuedTime); } /** @return <code>true</code> if this job has been enqueued, <code>false</code> if it has not */ public boolean isEnqueued() { return enqueuedTime.isPresent(); } /** @return the {@link Instant} that this job started running at, if any */ public Optional<Instant> getStartedTime() { return startedTime; } /** @return <code>true</code> if this job has started running, <code>false</code> if it has not */ public boolean isStarted() { return startedTime.isPresent(); } /** @param startedTime the value to set {@link #getStartedTime()} to */ public void setStartedTime(Instant startedTime) { if (!this.enqueuedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.canceledTime.isPresent()) throw new BadCodeMonkeyException(); if (this.startedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.completedTime.isPresent()) throw new BadCodeMonkeyException(); this.startedTime = Optional.of(startedTime); } /** @return the {@link Instant} that this job completed at, if any */ public Optional<Instant> getCompletedTime() { return completedTime; } /** * @return <code>true</code> if the job has completed (either successfully or with a failure), * <code>false</code> if it has not */ public boolean isCompleted() { return completedTime.isPresent(); } /** * @return a {@link Duration} representing how long the job ran for, or {@link Optional#empty()} * if it hasn't started or completed */ public Optional<Duration> getDuration() { if (isCompleted()) { return Optional.of(Duration.between(startedTime.get(), completedTime.get())); } else if (isCanceled()) { return Optional.of(Duration.between(startedTime.get(), canceledTime.get())); } else { return Optional.empty(); } } /** * @return the {@link PipelineJobOutcome} for this job if it has completed successfully, or {@link * Optional#empty()} if it is either as-yet-incomplete or if it failed (in which case, {@link * #getFailure()} will have a value) */ public Optional<PipelineJobOutcome> getOutcome() { return outcome; } /** * @return the {@link PipelineJobFailure} for this job if it has completed with a failure, or * {@link Optional#empty()} if it is either as-yet-incomplete or if it succeeded (in which * case, {@link #getOutcome()} will have a value) */ public Optional<PipelineJobFailure> getFailure() { return failure; } /** * @return <code>true</code> if {@link #getOutcome()} is present, <code>false</code> if it's not */ public boolean isCompletedSuccessfully() { return outcome.isPresent(); } /** * Marks the {@link PipelineJob} as having completed successfully. * * @param completedTime the value to use for {@link #getCompletedTime()} * @param outcome the value to use for {@link #getOutcome()} */ public void setCompleted(Instant completedTime, PipelineJobOutcome outcome) { if (!this.enqueuedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.canceledTime.isPresent()) throw new BadCodeMonkeyException(); if (!this.startedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.completedTime.isPresent()) throw new BadCodeMonkeyException(); this.completedTime = Optional.of(completedTime); this.outcome = Optional.of(outcome); } /** * Marks the {@link PipelineJob} as having completed with an exception. * * @param completedTime the value to use for {@link #getCompletedTime()} * @param failure the value to use for {@link #getFailure()} */ public void setCompleted(Instant completedTime, PipelineJobFailure failure) { if (!this.enqueuedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.canceledTime.isPresent()) throw new BadCodeMonkeyException(); if (!this.startedTime.isPresent()) throw new BadCodeMonkeyException(); if (this.completedTime.isPresent()) throw new BadCodeMonkeyException(); this.completedTime = Optional.of(completedTime); this.failure = Optional.of(failure); } /** @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PipelineJobRecord [id="); builder.append(id); builder.append(", jobType="); builder.append(jobType); builder.append(", jobArguments="); builder.append(jobArguments); builder.append(", createdTime="); builder.append(createdTime); builder.append(", canceledTime="); builder.append(canceledTime); builder.append(", enqueuedTime="); builder.append(enqueuedTime); builder.append(", startedTime="); builder.append(startedTime); builder.append(", completedTime="); builder.append(completedTime); builder.append(", outcome="); builder.append(outcome); builder.append(", failure="); builder.append(failure); builder.append("]"); return builder.toString(); } }
<filename>packages/polar/src/builtin-tasks/init.ts import { createProject } from "../internal/cli/project-creation"; import { task } from "../internal/core/config/config-env"; import { TASK_INIT } from "./task-names"; export default function (): void { task(TASK_INIT, "Initializes a new project in the given directory") .addPositionalParam<string>("projectName", "Name of project") .addOptionalPositionalParam<string>( "templateName", "Name of the template. If no template is specified, a default " + "template(counter) will be downloaded." ) .addOptionalPositionalParam<string>( "destination", "Path to the directory in which you would like to initialize the project files. " + "If destination is\n not provided, this defaults to the current directory.\n" ) .setAction(async ({ projectName, templateName, destination }: { projectName: string, templateName: string, destination: string }, _) => { await createProject(projectName, templateName, destination); }); }
<filename>react/components/RegistrationForm/mutations/register.js import gql from 'graphql-tag'; export default gql` mutation registerMutation( $first_name: String!, $last_name: String!, $email: String!, $password: String!, $password_confirmation: String!, $receive_newsletter: Boolean ) { registration(input: { first_name: $first_name, last_name: $last_name, email: $email, password: <PASSWORD>, password_confirmation: $<PASSWORD>, receive_newsletter: $receive_newsletter }) { me { id } } } `;
def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9
package io.github.concordcommunication.desktop.client.dto.websocket; import io.github.concordcommunication.desktop.client.dto.api.ChatResponse; public record ChatSent(ChatResponse chat) { }
<filename>assets/cases/dragging/scripts/components/Case_Dragging_Group.ts<gh_stars>0 import NodeUtil from "../../../../eazax-ccc/utils/NodeUtil"; import PromiseUtil from "../../../../eazax-ccc/utils/PromiseUtil"; import Case_Dragging from "../Case_Dragging"; import Case_Dragging_Item from "./Case_Dragging_Item"; const { ccclass, property } = cc._decorator; /** * 相交状态 */ enum IntersectionStatus { /** 无 */ OUT = 1, /** 相交 / 包含 */ IN, } @ccclass export default class Case_Dragging_Group extends cc.Component { @property({ type: cc.Layout, tooltip: CC_DEV && '布局组件' }) public layout: cc.Layout = null; /** 拖拽位置偏移 */ protected dragOffset: cc.Vec2 = null; /** 拖拽中 */ protected isDragging: boolean = false; /** 拖拽中 */ protected lastStatus: IntersectionStatus = IntersectionStatus.OUT; /** items */ public items: Case_Dragging_Item[] = []; /** 数量 */ public get itemCount() { return this.contentNode.childrenCount; } /** 内容节点 */ public get contentNode() { return this.layout.node; } /** 世界包围盒 */ public get rect() { return NodeUtil.getNodeSelfBoundingBoxToWorld(this.contentNode); } protected onLoad() { this.registerEvent(); } /** * 监听事件 */ protected registerEvent() { this.layout.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this); this.layout.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this); this.layout.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this); this.layout.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this); } /** * 触摸开始回调 * @param event */ public onTouchStart(event: cc.Event.EventTouch) { // 记录偏移 const node = this.contentNode, touchPosInWorld = event.getLocation(), touchPosInNode = node.getParent().convertToNodeSpaceAR(touchPosInWorld); this.dragOffset = touchPosInNode.sub(node.getPosition()); // 相交检测 this.updateIntersection(); } /** * 触摸移动回调 * @param event */ public onTouchMove(event: cc.Event.EventTouch) { if (!this.dragOffset) { return; } // 移动 const node = this.contentNode, touchPosInWorld = event.getLocation(), touchPosInNode = node.getParent().convertToNodeSpaceAR(touchPosInWorld); node.setPosition(touchPosInNode.sub(this.dragOffset)); // 拖起 if (!this.isDragging) { this.isDragging = true; this.drag(); } // 相交检测 this.updateIntersection(); } /** * 触摸取消回调 * @param event */ public onTouchCancel(event: cc.Event.EventTouch) { this.onTouchEnd(event); } /** * 触摸结束回调 * @param event */ public onTouchEnd(event: cc.Event.EventTouch) { if (!this.dragOffset) { return; } // 重置标志 this.dragOffset = null; // 放下 this.isDragging = false; this.drop(); } /** * 拖起 */ protected drag() { // 显示在最前面 this.node.setSiblingIndex(999); // 启用自动布局 this.enableLayout(true); // 放大物体 const items = this.items; for (let i = 0, l = items.length; i < l; i++) { items[i].scaleTo(1); } } /** * 放下 */ protected drop() { // 碰撞检测 if (this.hitTest()) { // 触发容器回调 Case_Dragging.container.onGroupDrop(this); // 物体嵌入容器 this.embedItems(); // 关闭节点(避免误触) this.contentNode.setPosition(0); this.contentNode.active = false; // 重置相交状态 this.lastStatus = IntersectionStatus.OUT; } else { // 启用自动布局 this.enableLayout(true); // 复位 this.reposition(); } } /** * 更新相交状态 */ protected updateIntersection() { const intersects = this.hitTest(); if (this.lastStatus === IntersectionStatus.OUT && intersects) { // 相交/包含状态 this.lastStatus = IntersectionStatus.IN; // 触发进入回调 Case_Dragging.container.onGroupDragEnter(this); } else if (this.lastStatus === IntersectionStatus.IN && !intersects) { // 无 this.lastStatus = IntersectionStatus.OUT; // 触发离开回调 Case_Dragging.container.onGroupDragLeave(this); } } /** * 检查碰撞 */ protected hitTest() { return this.rect.intersects(Case_Dragging.container.rect); } /** * 复位 */ protected async reposition() { // 缩小物体 const items = this.items; for (let i = 0, l = items.length; i < l; i++) { items[i].scaleTo(0.74); } //移动 await this.moveTo(cc.v3(0)); } /** * 将该组物体嵌入容器 */ protected embedItems() { // 禁用自动布局 this.enableLayout(false); // 容器变换 const container = Case_Dragging.container, containerContent = container.contentNode, items = this.items; const tasks = []; for (let i = 0, l = items.length; i < l; i++) { const item = items[i], node = item.node; // 计算位置 const targetPosInContainer = container.getNextSpacePos(), curPosInWorld = node.getParent().convertToWorldSpaceAR(node.getPosition()), curPosInContainer = containerContent.convertToNodeSpaceAR(curPosInWorld); // 添加到容器并复原位置 container.addOptionItem(item); item.embedToContainer(); node.setPosition(curPosInContainer); // 移动 const duration = 0.1 + (i * 0.02); tasks.push(new Promise<void>(res => { cc.tween(node) .to(duration, { position: targetPosInContainer, scale: 1 }, { easing: 'cubicOut' }) .call(res) .start(); })); } return Promise.all(tasks); } /** * 重组该组的物体 * @param triggerItem */ public regroupItems(triggerItem: Case_Dragging_Item) { const contentNode = this.contentNode, items = this.items; // 先计算好物体在分组里的位置 const itemPosInContent = this.getTargetSpacePos(items.indexOf(triggerItem) + 1); // 将分组内容节点移动到触发拖拽的物体当前位置 const triggerNode = triggerItem.node, itemPosInWorld = triggerNode.getParent().convertToWorldSpaceAR(triggerNode.getPosition()), posInContentParent = contentNode.getParent().convertToNodeSpaceAR(itemPosInWorld) as unknown as cc.Vec3; contentNode.setPosition(posInContentParent.sub(itemPosInContent)); // 禁用自动布局 this.enableLayout(false); // 启用内容节点 contentNode.active = true; // 逐个飞回来 for (let i = 0, l = items.length; i < l; i++) { const item = items[i], node = item.node; // 停止缓动 cc.Tween.stopAllByTarget(node); // 计算位置 const targetPosInGroup = this.getNextSpacePos(); // 添加到分组并复原位置 item.backToGroup(); node.setParent(contentNode); node.setPosition(targetPosInGroup); } } /** * 移动到目标位置 * @param pos */ protected moveTo(pos: cc.Vec3) { return new Promise<void>(res => { const node = this.contentNode, distance = cc.Vec2.distance(node.position, pos), duration = distance * (1 / 1500); cc.tween(node) .to(duration, { position: pos }, { easing: 'cubicOut' }) .call(res) .start(); }); } /** * 添加物体 * @param item */ public addOptionItem(item: Case_Dragging_Item) { item.group = this; item.node.setParent(this.contentNode); this.items.push(item); } /** * 清空物体 */ public clear() { this.contentNode.destroyAllChildren(); } /** * 获取目标位置的坐标 * @param count */ public getTargetSpacePos(count: number) { const layout = this.layout, { paddingLeft, spacingX } = layout, layoutWidth = layout.node.width, itemWidth = this.items[0].node.width, x = paddingLeft + (count * itemWidth) + ((count - 1) * spacingX) - (itemWidth / 2) - (layoutWidth / 2); return cc.v3(x, 0, 0); } /** * 获取下一个位置的坐标 */ public getNextSpacePos() { return this.getTargetSpacePos(this.itemCount + 1); } /** * 启用或禁用自动布局 * @param enabled */ public enableLayout(enabled: boolean) { this.layout.enabled = enabled; } /** * 强制更新布局 */ public forceUpdateLayout() { const children = this.layout.node.children; for (let i = 0; i < children.length; i++) { if (children[i].active) children[i]['_activeInHierarchy'] = true; } this.layout['_layoutDirty'] = true; this.layout.updateLayout(); } }
<reponame>marip8/mirror-test<filename>src/colorized_mesh_visual.cpp #include <colorized_mesh_display/colorized_mesh_visual.h> #include <OgreManualObject.h> #include <OgreSceneManager.h> #include <OgreSceneNode.h> #include <boost/lexical_cast.hpp> #include <pcl/conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> static uint32_t count = 0; namespace colorized_mesh_display { ColorizedMeshVisual::ColorizedMeshVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node) : scene_manager_(scene_manager) , material_name_("BaseWhiteNoLighting") { if (!parent_node) { parent_node = scene_manager_->getRootSceneNode(); } frame_node_ = parent_node->createChildSceneNode(); manual_object_ = scene_manager_->createManualObject("ColorizedMesh" + boost::lexical_cast<std::string>(count++)); } ColorizedMeshVisual::~ColorizedMeshVisual() { scene_manager_->destroyManualObject(manual_object_); scene_manager_->destroySceneNode(frame_node_); } void ColorizedMeshVisual::visualizeMesh(const pcl::PolygonMesh& mesh) { manual_object_->clear(); // Check if this mesh has color information auto color_it = std::find_if(mesh.cloud.fields.begin(), mesh.cloud.fields.end(), [](const pcl::PCLPointField &field) { return field.name == "rgb" || field.name == "rgba"; }); pcl::PointCloud<pcl::PointXYZRGBNormal> vertex_cloud; pcl::fromPCLPointCloud2(mesh.cloud, vertex_cloud); // Begin adding mesh information manual_object_->estimateVertexCount(vertex_cloud.size()); manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST); // Add the vertices for(const pcl::PointXYZRGBNormal& vertex : vertex_cloud) { // Set the position and normal of the vertex manual_object_->position(vertex.x, vertex.y, vertex.z); manual_object_->normal(vertex.normal_x, vertex.normal_y, vertex.normal_z); // Set default values for the color in case the mesh does not have color information float r = 0.5; float g = 0.5; float b = 0.5; // Use the colors from the mesh, if it has a color field if(color_it != mesh.cloud.fields.end()) { r = static_cast<float>(vertex.r) / 255.0f; g = static_cast<float>(vertex.g) / 255.0f; b = static_cast<float>(vertex.b) / 255.0f; } // Set the color manual_object_->colour(r, g, b); } // Add the triangles for(std::size_t i = 0; i < mesh.polygons.size(); ++i) { const pcl::Vertices& poly = mesh.polygons[i]; for(std::size_t j = 0; j < poly.vertices.size() - 2; ++j) { manual_object_->triangle(poly.vertices[0], poly.vertices[j + 1], poly.vertices[j + 2]); manual_object_->triangle(poly.vertices[j + 2], poly.vertices[j + 1], poly.vertices[0]); } } // Stop adding mesh information manual_object_->end(); // Attach the mesh object to the frame node frame_node_->attachObject(manual_object_); } void ColorizedMeshVisual::setFramePosition(const Ogre::Vector3& position) { frame_node_->setPosition(position); } void ColorizedMeshVisual::setFrameOrientation(const Ogre::Quaternion& orientation) { frame_node_->setOrientation(orientation); } } // namepsace colorized_mesh_display
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Buffer } from "./buffer.js"; /* * Buffer for CPU-side use */ export class PushBuffer extends Buffer { constructor(renderer, shaders, options) { const width = options.width || 1; const height = options.height || 1; const depth = options.depth || 1; const samples = width * height * depth; if (!options.samples) { options.samples = samples; } super(renderer, shaders, options); this.width = width; this.height = height; this.depth = depth; if (this.samples == null) { this.samples = samples; } this.build(options); } build(_options) { this.data = []; this.data.length = this.samples; this.filled = 0; this.pad = { x: 0, y: 0, z: 0 }; return (this.streamer = this.generate(this.data)); } dispose() { this.data = null; return super.dispose(); } getFilled() { return this.filled; } setActive(i, j, k) { let ref; return (([this.pad.x, this.pad.y, this.pad.z] = Array.from((ref = [this.width - i, this.height - j, this.depth - k]))), ref); } read() { return this.data; } copy(data) { const n = Math.min(data.length, this.samples); const d = this.data; return __range__(0, n, false).map((i) => (d[i] = data[i])); } fill() { let j, k, l, repeat; const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, skip, count, done, reset } = this.streamer; reset(); const n = this.width; const m = this.height; const padX = this.pad.x; const padY = this.pad.y; const limit = this.samples - this.pad.z * n * m; let i = (j = k = l = 0); if (padX > 0 || padY > 0) { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n - padX) { skip(padX); i = 0; if (++j === m - padY) { skip(n * padY); j = 0; k++; } } if (repeat === false) { break; } } } else { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n) { i = 0; if (++j === m) { j = 0; k++; } } if (repeat === false) { break; } } } this.filled = 1; return count(); } } function __range__(left, right, inclusive) { const range = []; const ascending = left < right; const end = !inclusive ? right : ascending ? right + 1 : right - 1; for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i); } return range; }
<filename>src/icons/legacy/Gamepad.tsx // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import GamepadSvg from '@rsuite/icon-font/lib/legacy/Gamepad'; const Gamepad = createSvgIcon({ as: GamepadSvg, ariaLabel: 'gamepad', category: 'legacy', displayName: 'Gamepad' }); export default Gamepad;
<reponame>set321go/composum package com.composum.sling.core.util; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.el.ELContext; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.servlet.ServletContext; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.PageContext; /** * Utility to evaluate expressions e.g. in tags. Include ExpressionUtil as lazy getter into tag. */ public class ExpressionUtil { private static final Logger LOG = LoggerFactory.getLogger(ExpressionUtil.class); private transient final PageContext pageContext; private transient JspApplicationContext jspAppContext; private transient ExpressionFactory expressionFactory; private transient ELContext elContext; public ExpressionUtil(PageContext pageContext) { this.pageContext = pageContext; } private JspApplicationContext getJspAppContext() { if (jspAppContext == null) { ServletContext servletContext = pageContext.getServletContext(); jspAppContext = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext); } return jspAppContext; } private ExpressionFactory getExpressionFactory() { if (expressionFactory == null) { expressionFactory = getJspAppContext().getExpressionFactory(); } return expressionFactory; } private ELContext getELContext() { if (elContext == null) { elContext = pageContext.getELContext(); } return elContext; } private ValueExpression createValueExpression(ELContext elContext, String expression, Class<?> type) { return getExpressionFactory().createValueExpression(elContext, expression, type); } /** * evaluate an EL expression value, the value can contain @{..} expression rules which are transformed to ${..} */ public <T> T eval(Object value, T defaultValue) { T result = null; if (value instanceof String) { String expression = (String) value; if (StringUtils.isNotBlank(expression)) { expression = expression.replaceAll("@\\{([^\\}]+)\\}", "\\${$1}"); Class type = defaultValue != null ? defaultValue.getClass() : String.class; if (String.class.equals(type) && !expression.contains("${") && !expression.contains("#{")) { result = (T) expression; // no change if it does not contain an actual EL expression } else { ELContext elContext = getELContext(); ValueExpression valueExpression = createValueExpression(elContext, expression, type); result = (T) valueExpression.getValue(elContext); } } } return result != null ? result : defaultValue; } }
<filename>Documentation/_quantize_helper_test_8cpp.js var _quantize_helper_test_8cpp = [ [ "BOOST_AUTO_TEST_CASE", "_quantize_helper_test_8cpp.xhtml#ac0a5ea873d314e59e2d7dfad4643e8e9", null ] ];
const { Platform, StyleSheet } = require('react-native'); const { getStylesForProperty } = require('css-to-react-native'); const Dynamic = new Map(); const Themes = new Map(); let theme; function setVars(obj) { Object.entries(obj).forEach(([key, val]) => Dynamic.set(key, val)); } function setVar(key, value) { Dynamic.set(key, value) } function setThemeVars(name, obj) { const cache = new Map(); Object.entries(obj).forEach(([key, val]) => cache.set(key, val)); Themes.set(name, cache); } function setTheme(name) { theme = name; } function getVar(name, fallbackValue) { // Find dynamic variable if (Dynamic.has(name)) { const res = Dynamic.get(name); if (res instanceof Array && res.length >= 2) { return res[0][res[1]]; } return res; } // Find theme variable if (Themes.has(theme)) { const Theme = Themes.get(theme); if (Theme.has(name)) { return Theme.get(name); } } return fallbackValue; } function mapStyles(styles) { // Cache builder for StyleSheet.create const cache = {}; // .className for (const className in styles) { cache[className] = {}; // propertyName: propertyValue; for (const propertyName in styles[className]) { const propertyValue = styles[className][propertyName]; cache[className][propertyName] = propertyValue; // Check if propertyValue is string if (typeof propertyValue === 'string') { // Check for properties that include css3 variables const isCssVariable = propertyValue.match(/var\((.*?)(,.*)?\)/); if (isCssVariable) { delete cache[className][propertyName]; // Includes default value? if (isCssVariable[2]) { Object.assign(cache[className], getStylesForProperty(propertyName, isCssVariable[2].substr(1))); } // Loop through themes and check for prop names Themes.forEach((themeVars, themeName) => { let fail = false; const themeClassName = `${className}__theme-${themeName}`; const propVarValue = propertyValue.replace(/var\((.*?)(,.*)?\)/, (str, varName, defaultValue) => { if (themeVars.has(`${varName.trim()}-${Platform.OS}`)) { return themeVars.get(`${varName.trim()}-${Platform.OS}`); } if (themeVars.has(varName.trim())) { return themeVars.get(varName.trim()); } if (defaultValue) { return defaultValue.substr(1); } fail = true; }); // Ensure theme classNames cache[themeClassName] = cache[themeClassName] || {}; // Assign new property values if (!fail) { Object.assign(cache[themeClassName], getStylesForProperty(propertyName, propVarValue)); } }); } } } } const sheet = StyleSheet.create(cache); // Dynamic styles function getDynamicStyles(className) { const res = {}; for (propertyName in styles[className]) { const propertyValue = styles[className][propertyName]; if (propertyValue && String(propertyValue).match(/var\((.*?)(,.*)?\)/)) { let fail = false; const propVarValue = propertyValue.replace(/var\((.*?)(,.*)?\)/, (str, varName, defaultValue) => { const trimVarName = varName.trim(); if (Dynamic.has(trimVarName)) { const res = Dynamic.get(varName.trim()); if (res instanceof Array && res.length >= 2) { return res[0][res[1]]; } return res; } if (defaultValue) { return defaultValue.substr(1); } fail = true; }); if (!fail) { Object.assign(res, getStylesForProperty(propertyName, propVarValue)); } } } return res; } function getClassNamesForKey(key) { return [ // Add base className sheet[key], // Add theme variables sheet[`${key}__theme-${theme}`], // Add dynamic variables getDynamicStyles(key), ].filter(n => { if (n instanceof Array) { return n.length === 0; } if (typeof n === 'object' && n.constructor === Object) { return Object.values(n).filter(item => !!item).length > 0; } return !!n; }); } // ClassNames implementation function classNames(...args) { const classes = []; for (let i = 0; i < args.length; i += 1) { const arg = args[i]; if (!arg) continue; const argType = typeof arg; if (argType === 'string' && sheet[arg]) { classes.push(getClassNamesForKey(arg)); } else if (argType === 'number') { classes.push(arg); } else if (Array.isArray(arg) && arg.length) { const inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } else if (argType === 'object') { for (const key in arg) { if ({}.hasOwnProperty.call(arg, key) && arg[key] && sheet[key]) { classes.push(getClassNamesForKey(key)); } } } } return classes; } for (const key in sheet) { classNames[key] = sheet[key]; Object.defineProperty(classNames, key, { get() { return getClassNamesForKey(key); } }); } // Added for debugging purpose classNames.__cache__ = cache; return classNames; }; module.exports = { Themes, Dynamic, setVar, getVar, setVars, setThemeVars, setTheme, mapStyles }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.testgrid.reporting.model.performance; /** * Model class representing a column header of the {@link PerformanceTable}. * * @since 1.0.0 */ public class ColumnHeader { private String name; private String label; private int rowSpan = 1; private int colSpan = 1; public int getRowSpan() { return rowSpan; } public void setRowSpan(int rowSpan) { this.rowSpan = rowSpan; } public int getColSpan() { return colSpan; } public void setColSpan(int colSpan) { this.colSpan = colSpan; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } }
/// <reference types="ses"> import { TypeError, arrayPush, create, defineProperties, getOwnPropertyDescriptors, } from './commons.js'; import { evadeHtmlCommentTest, evadeImportExpressionTest, rejectSomeDirectEvalExpressions, } from './transforms.js'; import { performEval } from './evaluate.js'; export const compartmentEvaluate = (compartmentFields, source, options) => { // Perform this check first to avoid unecessary sanitizing. // TODO Maybe relax string check and coerce instead: // https://github.com/tc39/proposal-dynamic-code-brand-checks if (typeof source !== 'string') { throw new TypeError('first argument of evaluate() must be a string'); } // Extract options, and shallow-clone transforms. const { transforms = [], sloppyGlobalsMode = false, __moduleShimLexicals__ = undefined, __evadeHtmlCommentTest__ = false, __evadeImportExpressionTest__ = false, __rejectSomeDirectEvalExpressions__ = true, // Note default on } = options; const localTransforms = [...transforms]; if (__evadeHtmlCommentTest__ === true) { arrayPush(localTransforms, evadeHtmlCommentTest); } if (__evadeImportExpressionTest__ === true) { arrayPush(localTransforms, evadeImportExpressionTest); } if (__rejectSomeDirectEvalExpressions__ === true) { arrayPush(localTransforms, rejectSomeDirectEvalExpressions); } let { globalTransforms } = compartmentFields; const { globalObject, globalLexicals, knownScopeProxies } = compartmentFields; let localObject = globalLexicals; if (__moduleShimLexicals__ !== undefined) { // When using `evaluate` for ESM modules, as should only occur from the // module-shim's module-instance.js, we do not reveal the SES-shim's // module-to-program translation, as this is not standardizable behavior. // However, the `localTransforms` will come from the `__shimTransforms__` // Compartment option in this case, which is a non-standardizable escape // hatch so programs designed specifically for the SES-shim // implementation may opt-in to use the same transforms for `evaluate` // and `import`, at the expense of being tightly coupled to SES-shim. globalTransforms = undefined; localObject = create(null, getOwnPropertyDescriptors(globalLexicals)); defineProperties( localObject, getOwnPropertyDescriptors(__moduleShimLexicals__), ); } return performEval(source, globalObject, localObject, { globalTransforms, localTransforms, sloppyGlobalsMode, knownScopeProxies, }); };
// Copyright 2019 Google LLC // // 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 e2e import ( "context" "flag" "sync" "testing" "time" "github.com/pkg/errors" "ns-open-match/internal/app/evaluator" "ns-open-match/internal/appmain/apptest" "ns-open-match/internal/config" mmfService "ns-open-match/internal/testing/mmf" "ns-open-match/pkg/pb" ) var ( testOnlyEnableMetrics = flag.Bool("test_only_metrics", true, "Enables metrics exporting for tests.") testOnlyEnableRPCLoggingFlag = flag.Bool("test_only_rpc_logging", false, "Enables RPC Logging for tests. This output is very verbose.") testOnlyLoggingLevel = flag.String("test_only_log_level", "info", "Sets the log level for tests.") ) func newOM(t *testing.T) *om { om := &om{ t: t, } t.Cleanup(func() { om.fLock.Lock() defer om.fLock.Unlock() om.running.Wait() // Set this cleanup before starting servers, so that servers will be // stopped before this runs. if om.mmf != nil && !om.mmfCalled { t.Error("MMF set but never called.") } if om.eval != nil && !om.evalCalled { t.Error("Evaluator set but never called.") } }) om.cfg, om.AdvanceTTLTime = start(t, om.evaluate, om.runMMF) om.fe = pb.NewFrontendServiceClient(apptest.GRPCClient(t, om.cfg, "api.frontend")) om.be = pb.NewBackendServiceClient(apptest.GRPCClient(t, om.cfg, "api.backend")) om.query = pb.NewQueryServiceClient(apptest.GRPCClient(t, om.cfg, "api.query")) return om } type om struct { t *testing.T cfg config.View fe pb.FrontendServiceClient be pb.BackendServiceClient query pb.QueryServiceClient // For local tests, advances the mini-redis ttl time. For in cluster tests, // just sleeps. AdvanceTTLTime func(time.Duration) running sync.WaitGroup fLock sync.Mutex mmfCalled bool evalCalled bool mmf mmfService.MatchFunction eval evaluator.Evaluator } func (om *om) SetMMF(mmf mmfService.MatchFunction) { om.fLock.Lock() defer om.fLock.Unlock() if om.mmf == nil { om.mmf = mmf return } om.t.Fatal("Matchmaking function set multiple times") } func (om *om) runMMF(ctx context.Context, profile *pb.MatchProfile, out chan<- *pb.Match) error { om.fLock.Lock() om.running.Add(1) defer om.running.Done() mmf := om.mmf om.mmfCalled = true om.fLock.Unlock() if mmf == nil { return errors.New("MMF called without being set") } return mmf(ctx, profile, out) } func (om *om) SetEvaluator(eval evaluator.Evaluator) { om.fLock.Lock() defer om.fLock.Unlock() if om.eval == nil { om.eval = eval return } om.t.Fatal("Evaluator function set multiple times") } func (om *om) evaluate(ctx context.Context, in <-chan *pb.Match, out chan<- string) error { om.fLock.Lock() om.running.Add(1) defer om.running.Done() eval := om.eval om.evalCalled = true om.fLock.Unlock() if eval == nil { return errors.New("Evaluator called without being set") } return eval(ctx, in, out) } func (om *om) Frontend() pb.FrontendServiceClient { return om.fe } func (om *om) Backend() pb.BackendServiceClient { return om.be } func (om *om) Query() pb.QueryServiceClient { return om.query } func (om *om) MMFConfigGRPC() *pb.FunctionConfig { return &pb.FunctionConfig{ Host: om.cfg.GetString("api." + apptest.ServiceName + ".hostname"), Port: int32(om.cfg.GetInt("api." + apptest.ServiceName + ".grpcport")), Type: pb.FunctionConfig_GRPC, } } func (om *om) MMFConfigHTTP() *pb.FunctionConfig { return &pb.FunctionConfig{ Host: om.cfg.GetString("api." + apptest.ServiceName + ".hostname"), Port: int32(om.cfg.GetInt("api." + apptest.ServiceName + ".httpport")), Type: pb.FunctionConfig_REST, } } // Testing constants which must match the configuration. Not parsed in test so // that parsing bugs can't hide logic bugs. const registrationInterval = time.Millisecond * 200 const proposalCollectionInterval = time.Millisecond * 200 const pendingReleaseTimeout = time.Millisecond * 200 const assignedDeleteTimeout = time.Millisecond * 200 // configFile is the "cononical" test config. It exactly matches the configmap // which is used in the real cluster tests. const configFile = ` registrationInterval: 200ms proposalCollectionInterval: 200ms pendingReleaseTimeout: 200ms assignedDeleteTimeout: 200ms queryPageSize: 10 logging: level: debug format: text rpc: false backoff: initialInterval: 100ms maxInterval: 500ms multiplier: 1.5 randFactor: 0.5 maxElapsedTime: 3000ms api: backend: hostname: "open-match-backend" grpcport: "50505" httpport: "51505" frontend: hostname: "open-match-frontend" grpcport: "50504" httpport: "51504" query: hostname: "open-match-query" grpcport: "50503" httpport: "51503" synchronizer: hostname: "open-match-synchronizer" grpcport: "50506" httpport: "51506" swaggerui: hostname: "open-match-swaggerui" httpport: "51500" scale: httpport: "51509" evaluator: hostname: "open-match-test" grpcport: "50509" httpport: "51509" test: hostname: "open-match-test" grpcport: "50509" httpport: "51509" redis: sentinelPort: 26379 sentinelMaster: om-redis-master sentinelHostname: open-match-redis sentinelUsePassword: usePassword: false passwordPath: /opt/bitnami/redis/secrets/redis-password pool: maxIdle: 200 maxActive: 0 idleTimeout: 0 healthCheckTimeout: 300ms telemetry: reportingPeriod: "1m" traceSamplingFraction: "0.01" zpages: enable: "true" jaeger: enable: "false" agentEndpoint: "" collectorEndpoint: "" prometheus: enable: "false" endpoint: "/metrics" serviceDiscovery: "true" stackdriverMetrics: enable: "false" gcpProjectId: "intentionally-invalid-value" prefix: "open_match" `
<reponame>wuximing/dsshop<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var util_1 = require("@antv/util"); var common_1 = require("../util/common"); var bbox_1 = tslib_1.__importDefault(require("../util/bbox")); /** * 图表的文字描述,一般用于生成图表的标题和副标题 */ var TextDescription = /** @class */ (function () { function TextDescription(cfg) { this.position = 'top'; this.destroyed = false; util_1.assign(this, cfg); this.init(); } TextDescription.prototype.getBBox = function () { var _this = this; if (this.shape) { // @ts-ignore var bbox = this.shape.getBBox(); if (this.index === 0) { return bbox_1.default.fromBBoxObject(bbox); } var padding_1 = this.plot.theme.description.padding; if (util_1.isArray(padding_1)) { util_1.each(padding_1, function (it, index) { if (typeof padding_1[index] === 'function') { padding_1[index] = padding_1[index](_this.plot.options.legend.position); } }); } return new bbox_1.default(bbox.maxX, bbox.minY, bbox.width, bbox.height); } return null; }; TextDescription.prototype.clear = function () { if (this.shape) { // @ts-ignore this.shape.attr('text', ''); } }; TextDescription.prototype.destroy = function () { if (this.shape) { this.shape.remove(); } this.destroyed = true; }; TextDescription.prototype.init = function () { var content = this.textWrapper(); var _a = this.getPosition(), x = _a.x, y = _a.y; this.shape = this.container.addShape('text', { attrs: util_1.mix({ x: x, y: y, text: content, }, this.style, { textAlign: this.getTextAlign(), }), }); // @ts-ignore this.shape.name = this.name; }; TextDescription.prototype.getPosition = function () { if (this.alignTo === 'left') { return { x: this.leftMargin, y: this.topMargin }; } else if (this.alignTo === 'middle') { return { x: this.leftMargin + this.wrapperWidth / 2, y: this.topMargin }; } else { return { x: this.rightMargin, y: this.topMargin }; } }; TextDescription.prototype.getTextAlign = function () { if (this.alignTo === 'left') { return 'left'; } else if (this.alignTo === 'middle') { return 'center'; } else { return 'right'; } }; /** * 当text过长时,默认换行 * 1. 注意初始text带换行符的场景 */ TextDescription.prototype.textWrapper = function () { var width = this.wrapperWidth; var style = this.style; var textContent = this.text; var tShape = this.container.addShape('text', { attrs: tslib_1.__assign({ text: '', x: 0, y: 0 }, style), }); var textArr = textContent.split('\n'); var wrappedTextArr = textArr.map(function (wrappedText) { var text = ''; var chars = wrappedText.split(''); var breakIndex = []; for (var i = 0; i < chars.length; i++) { var item = chars[i]; tShape.attr('text', (text += item)); var currentWidth = tShape.getBBox().width - 1; if (currentWidth > width) { // 如果是第一个字符就大于宽度不做任何换行处理 if (i === 0) { break; } breakIndex.push(i); text = ''; } } return common_1.breakText(chars, breakIndex); }); tShape.remove(); return wrappedTextArr.join('\n'); }; return TextDescription; }()); exports.default = TextDescription; //# sourceMappingURL=description.js.map
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: sdk/net/CNetServer.h * PURPOSE: Net server module interface * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #pragma once #include "ns_common.h" #include "bitstream.h" #include "ns_playerid.h" #include "CNetHTTPDownloadManagerInterface.h" #define MAX_CALL_REMOTE_QUEUES 100 namespace EDownloadMode { enum EDownloadModeType { NONE, ASE, CALL_REMOTE, CALL_REMOTE_LAST = CALL_REMOTE + MAX_CALL_REMOTE_QUEUES - 1, }; } using EDownloadMode::EDownloadModeType; struct SPacketStat { int iCount; int iTotalBytes; TIMEUS totalTime; }; class CBinaryFileInterface { public: virtual ~CBinaryFileInterface() {} virtual bool FOpen(const char* szFilename, const char* szMode, bool bValidate) = 0; virtual void FClose() = 0; virtual bool FEof() = 0; virtual void FFlush() = 0; virtual int FTell() = 0; virtual void FSeek(int iOffset, int iOrigin) = 0; virtual int FRead(void* pData, uint uiSize) = 0; virtual int FWrite(const void* pData, uint uiSize) = 0; }; struct SNetOptions { SNetOptions() { memset(this, 0, sizeof(*this)); } struct { bool bValid; int iPacketLoss; int iExtraPing; int iExtraPingVariance; int iKBPSLimit; } netSim; struct { bool bValid; bool bAutoFilter; } netFilter; struct { bool bValid; int iUpdateCycleDatagramsLimit; int iUpdateCycleMessagesLimit; } netOptimize; }; struct SScriptInfo { const char* szMinServerHostVer; const char* szMinServerRunVer; const char* szMinClientRunVer; }; struct SPlayerPacketUsage { NetServerPlayerID playerId; uint uiPktsPerSec; uint uiBytesPerSec; }; class CNetServer { public: enum ENetworkUsageDirection { STATS_INCOMING_TRAFFIC = 0, STATS_OUTGOING_TRAFFIC = 1 }; // szIP can be NULL if autochoosing is wanted. virtual bool StartNetwork(const char* szIP, unsigned short usServerPort, unsigned int uiAllowedPlayers, const char* szServerName) = 0; virtual void StopNetwork() = 0; virtual void DoPulse() = 0; virtual void RegisterPacketHandler(PPACKETHANDLER pfnPacketHandler) = 0; virtual bool GetNetworkStatistics(NetStatistics* pDest, const NetServerPlayerID& PlayerID) = 0; virtual const SPacketStat* GetPacketStats() = 0; virtual bool GetBandwidthStatistics(SBandwidthStatistics* pDest) = 0; virtual bool GetNetPerformanceStatistics(SNetPerformanceStatistics* pDest, bool bResetCounters) = 0; virtual void GetPingStatus(SFixedString<32>* pstrStatus) = 0; virtual bool GetSyncThreadStatistics(SSyncThreadStatistics* pDest, bool bResetCounters) = 0; virtual NetBitStreamInterface* AllocateNetServerBitStream(unsigned short usBitStreamVersion, const void* pData = nullptr, uint uiDataSize = 0, bool bCopyData = false) = 0; virtual void DeallocateNetServerBitStream(NetBitStreamInterface* bitStream) = 0; virtual bool SendPacket(unsigned char ucPacketID, const NetServerPlayerID& playerID, NetBitStreamInterface* bitStream, bool bBroadcast, NetServerPacketPriority packetPriority, NetServerPacketReliability packetReliability, ePacketOrdering packetOrdering = PACKET_ORDERING_DEFAULT) = 0; virtual void GetPlayerIP(const NetServerPlayerID& playerID, char strIP[22], unsigned short* usPort) = 0; virtual void Kick(const NetServerPlayerID& PlayerID) = 0; virtual void SetPassword(const char* szPassword) = 0; virtual void SetMaximumIncomingConnections(unsigned short numberAllowed) = 0; virtual CNetHTTPDownloadManagerInterface* GetHTTPDownloadManager(EDownloadModeType iMode) = 0; virtual void SetClientBitStreamVersion(const NetServerPlayerID& PlayerID, unsigned short usBitStreamVersion) = 0; virtual void ClearClientBitStreamVersion(const NetServerPlayerID& PlayerID) = 0; virtual void SetChecks(const char* szDisableComboACMap, const char* szDisableACMap, const char* szEnableSDMap, int iEnableClientChecks, bool bHideAC, const char* szImgMods) = 0; virtual unsigned int GetPendingPacketCount() = 0; virtual void GetNetRoute(SFixedString<32>* pstrRoute) = 0; virtual bool InitServerId(const char* szPath) = 0; virtual void ResendModPackets(const NetServerPlayerID& playerID) = 0; virtual void ResendACPackets(const NetServerPlayerID& playerID) = 0; virtual void GetClientSerialAndVersion(const NetServerPlayerID& playerID, SFixedString<32>& strSerial, SFixedString<64>& strExtra, SFixedString<32>& strVersion) = 0; virtual void SetNetOptions(const SNetOptions& options) = 0; virtual void GenerateRandomData(void* pOutData, uint uiLength) = 0; virtual bool EncryptDumpfile(const char* szClearPathFilename, const char* szEncryptedPathFilename) { return false; } virtual bool ValidateHttpCacheFileName(const char* szFilename) { return false; } virtual bool GetScriptInfo(const char* cpInBuffer, uint uiInSize, SScriptInfo* pOutInfo) { return false; } virtual bool DeobfuscateScript(const char* cpInBuffer, uint uiInSize, const char** pcpOutBuffer, uint* puiOutSize, const char* szScriptName) { return false; } virtual bool GetPlayerPacketUsageStats(uchar* packetIdList, uint uiNumPacketIds, SPlayerPacketUsage* pOutStats, uint uiTopCount) { return false; } virtual const char* GetLogOutput() { return NULL; } virtual bool IsValidSocket(const NetServerPlayerID& playerID) { assert(0); return false; } };
if num % 2 == 0: print("Even") else: print("Odd")
import numpy as np from sklearn.ensemble import RandomForestClassifier #data X = np.array([[1,2,3], [1,2,3], [4,5,6], [4,5,6]]) y = np.array([1,1,2,2]) #Create a Random Forest Classifier clf = RandomForestClassifier(max_depth=2, random_state=0) #Training the model clf.fit(X,y)
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-N/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-N/1024+0+512-shuffled-N-VB-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_remove_all_but_nouns_and_verbs_first_two_thirds_sixth --eval_function last_sixth_eval
def calculate_polynomials(numbers): return [x**2 + 3*x + 1 for x in numbers]
<filename>mpa/modules/hooks/mem_inspect_hook.py<gh_stars>0 # Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import os import torch import pandas as pd from mmcv.runner import Hook, HOOKS from .utils import plot_mem, print_report from mpa.utils.logger import get_logger logger = get_logger() @HOOKS.register_module() class MemInspectHook(Hook): def __init__(self, **kwargs): super(MemInspectHook, self).__init__() self.exp = kwargs.get('exp', 'baseline') self.print_report = kwargs.get('print_report', False) self.output_file = kwargs.get('output_file', f'gpu_mem_plot_{self.exp}.png') data_cfg = kwargs.get('data_cfg', None) if data_cfg is None: raise ValueError('cannot find data config') logger.info(f'data_cfg = {data_cfg}') self.data_args = self._parse_data_cfg(data_cfg) logger.info(f'keys in data args = {self.data_args.keys()}') # input value will be passed as positional argument to the model self.input = self.data_args.pop('input', None) if self.input is None: raise ValueError("invalid data configuration. 'input' key is the mandatory for the data configuration.") def _parse_data_cfg(self, cfg): input_args = {} if not isinstance(cfg, dict): raise ValueError('invalid configuration for the data. supported only dictionary type') for idx, (k, v) in enumerate(cfg.items()): type_ = v.get('type', None) args = v.get('args', None) if type_ is not None and args is not None: input_args[k] = getattr(torch, type_)(*args) elif isinstance(v, dict): input_args[k] = self._parse_data_cfg(v) return input_args # referenced from https://github.com/quentinf00/article-memory-log def _generate_mem_hook(self, mem, idx, hook_type, exp): def hook(self, *args): if len(mem) == 0 or mem[-1]['exp'] != exp: call_idx = 0 else: call_idx = mem[-1]['call_idx'] + 1 mem_all, mem_cached = torch.cuda.memory_allocated(), torch.cuda.memory_cached() torch.cuda.synchronize() mem.append({ 'layer_idx': idx, 'call_idx': call_idx, 'layer_type': type(self).__name__, 'exp': exp, 'hook_type': hook_type, 'mem_all': mem_all, 'mem_cached': mem_cached, }) return hook def before_run(self, runner): model = runner.model exp = 'baseline' mem_log = [] hooks = [] for idx, module in enumerate(runner.model.modules()): hooks.append(module.register_forward_pre_hook(self._generate_mem_hook(mem_log, idx, 'pre', exp))) hooks.append(module.register_forward_hook(self._generate_mem_hook(mem_log, idx, 'fwd', exp))) hooks.append(module.register_backward_hook(self._generate_mem_hook(mem_log, idx, 'bwd', exp))) try: out = model(self.input, **self.data_args) loss = out['loss'].sum() loss.backward() finally: [hook.remove() for hook in hooks] df = pd.DataFrame(mem_log) plot_mem(df, exps=[self.exp], output_file=os.path.join(runner.work_dir, self.output_file), normalize_call_idx=False) if self.print_report: print_report(df, exp=self.exp, logger=logger)
<filename>react-app/src/components/EdiumDisplay.tsx import React from "react"; import { useSelector } from "react-redux"; import { ElementDisplay } from "./ElementDisplay"; import { RootState } from "../slices"; interface EdiumDisplayProps { slot: "slot1" | "slot2"; } function EdiumDisplay(props: EdiumDisplayProps) { const loadedState = useSelector((state: RootState) => state.slot[props.slot].loadedState); const edium = useSelector((state: RootState) => state.slot[props.slot].edium); const title = `Edium n°${edium.id} : ${edium.name ? edium.name : "#"} (${edium.kind})`; let content; if (edium.id === 0) { content = <p>Nothing selected.</p>; } else if (loadedState === "no") { content = <p>Loading failed.</p>; } else if (loadedState === "loading") { content = <p>Loading Edium n°{edium.id}</p>; } else { content = ( <React.Fragment> <h2>{title}</h2> <table> <thead> <tr> <th>Element name</th> <th>Value</th> </tr> </thead> <tbody> { edium.elements.map((e) => { return ( <ElementDisplay key={e.id} name={e.name} value={e.value} /> ); }) } </tbody> </table> </React.Fragment> ); } return ( <div className="EdiumDisplay"> {content} </div> ); } export { EdiumDisplay };
<reponame>N-I-N-0/NSMBWii-Mod #include <profile.h> #include <game.h> #include <sfx.h> const char* ClawANL [] = { "test_lift", NULL }; class daClaw : public dEn_c { public: int onCreate(); int onExecute(); int onDelete(); int onDraw(); void updateModelMatrices(); void bindAnimChr_and_setUpdateRate(const char* name, int unk, float unk2, float rate); static dActor_c* build(); void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat3_StarPower(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat5_Mario(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCatD_Drill(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat8_FencePunch(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPoundYoshi(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCatA_PenguinMario(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat11_PipeCannon(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat9_RollingObject(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat1_Fireball_E_Explosion(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat2_IceBall_15_YoshiIce(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat13_Hammer(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat14_YoshiFire(ActivePhysics *apThis, ActivePhysics *apOther); int timer; bool leftorright; dStageActor_c* sidestepper; dAc_Py_c* target; mHeapAllocator_c allocator; m3d::mdl_c bodyModel; m3d::anmChr_c animationChr; nw4r::g3d::ResFile resFile; USING_STATES(daClaw); DECLARE_STATE(Appear); DECLARE_STATE(Attack); DECLARE_STATE(Disappear); }; CREATE_STATE(daClaw, Appear); CREATE_STATE(daClaw, Attack); CREATE_STATE(daClaw, Disappear); void daClaw::updateModelMatrices() { matrix.translation(pos.x, pos.y, pos.z); matrix.applyRotationYXZ(&rot.x, &rot.y, &rot.z); bodyModel.setDrawMatrix(matrix); bodyModel.setScale(&scale); bodyModel.calcWorld(false); } void daClaw::bindAnimChr_and_setUpdateRate(const char* name, int unk, float unk2, float rate) { nw4r::g3d::ResAnmChr anmChr = this->resFile.GetResAnmChr(name); this->animationChr.bind(&this->bodyModel, anmChr, unk); this->bodyModel.bindAnim(&this->animationChr, unk2); this->animationChr.setUpdateRate(rate); } dActor_c* daClaw::build() { void *buffer = AllocFromGameHeap1(sizeof(daClaw)); return new(buffer) daClaw; } const SpriteData ClawSpriteData = { ProfileId::Claw, 0, 0, 0, 0, 0x100, 0x100, 0, 0, 0, 0, 0 }; Profile ClawProfile(&daClaw::build, SpriteId::Claw, &ClawSpriteData, ProfileId::Claw, ProfileId::Claw, "Claw", ClawANL); void daClaw::playerCollision(ActivePhysics* apThis, ActivePhysics* apOther) { this->_vf220(apOther->owner); } bool daClaw::collisionCat3_StarPower(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat5_Mario(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCatD_Drill(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat8_FencePunch(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat7_GroundPound(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat7_GroundPoundYoshi(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCatA_PenguinMario(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat11_PipeCannon(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat9_RollingObject(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat1_Fireball_E_Explosion(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat2_IceBall_15_YoshiIce(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat13_Hammer(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } bool daClaw::collisionCat14_YoshiFire(ActivePhysics* apThis, ActivePhysics* apOther) { return true; } int daClaw::onCreate() { target = GetSpecificPlayerActor(0); //target is mario allocator.link(-1, GameHeaps[0], 0, 0x20); /* this->resFile.data = getResource("test_lift", "g3d/test_lift.brres"); nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("test_lift"); bodyModel.setup(mdl, &this->allocator, 0x224, 1, 0); SetupTextures_MapObj(&bodyModel, 0); nw4r::g3d::ResAnmChr anmChr = resFile.GetResAnmChr("wait"); this->chrAnimation.setup(mdl, anmChr, &this->allocator, 0); */ resFile.data = getResource("test_lift", "g3d/test_lift.brres"); nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("test_lift"); bodyModel.setup(mdl, &allocator, 0x224, 1, 0); SetupTextures_Boss(&bodyModel, 0); nw4r::g3d::ResAnmChr anmChr = this->resFile.GetResAnmChr("clawAppear"); this->animationChr.setup(mdl, anmChr, &this->allocator, 0); allocator.unlink(); ActivePhysics::Info HitMeBaby; HitMeBaby.xDistToCenter = 0.0; HitMeBaby.yDistToCenter = 0.0; HitMeBaby.xDistToEdge = 2.0; HitMeBaby.yDistToEdge = 2.0; HitMeBaby.category1 = 0x3; HitMeBaby.category2 = 0x0; HitMeBaby.bitfield1 = 0x4F; HitMeBaby.bitfield2 = 0xFFFFFFFF; HitMeBaby.unkShort1C = 0; HitMeBaby.callback = &dEn_c::collisionCallback; this->aPhysics.initWithStruct(this, &HitMeBaby); this->aPhysics.addToList(); this->scale.x = 0.4; this->scale.y = 0.4; this->scale.z = 0.4; //sidestepper = (dStageActor_c*)fBase_c::search(779); //this->pos = sidestepper->pos; this->pos.z = -1000; bindAnimChr_and_setUpdateRate("clawAppear", 1, 0.0, 1.0); doStateChange(&StateID_Appear); this->onExecute(); return true; } int daClaw::onExecute() { acState.execute(); updateModelMatrices(); bodyModel._vf1C(); if (this->animationChr.isAnimationDone()) { this->animationChr.setCurrentFrame(0.0); } return true; } int daClaw::onDelete() { return true; } int daClaw::onDraw() { bodyModel.scheduleForDrawing(); return true; } void daClaw::beginState_Appear() { timer = 0; bindAnimChr_and_setUpdateRate("clawAppear", 1, 0.0, 1.0); //this->pos.x = sidestepper->pos.x; this->pos.y = pos.y + 100.0; } void daClaw::executeState_Appear() { if (timer == 80) { doStateChange(&StateID_Attack); } timer++; } void daClaw::endState_Appear() { } void daClaw::beginState_Attack() { timer = 0; bindAnimChr_and_setUpdateRate("clawAttack", 1, 0.0, 1.0); if (target->pos.x < this->pos.x) //player is left { this->leftorright = false; //false = left } else //player is right { this->leftorright = true; //true = right } } void daClaw::executeState_Attack() { if (timer < 180) { if (leftorright) { pos.x += 2.0; } else { pos.x -= 2.0; } } else { doStateChange(&StateID_Disappear); } timer++; } void daClaw::endState_Attack() { } void daClaw::beginState_Disappear() { timer = 0; bindAnimChr_and_setUpdateRate("clawDisappear", 1, 0.0, 1.0); } void daClaw::executeState_Disappear() { if (timer == 80) { this->Delete(1); } timer++; } void daClaw::endState_Disappear() { }
import model.Client; import model.Cofetarie; import model.ProdusCofetarie; import service.ClientService; import service.CofetarieService; public class ExecutieCofetarieManagementApp { public static void main(String[] args) { CofetarieService cofetarieService = new CofetarieService(); ClientService clientService = new ClientService(); // Client Razvan = new Client(); //setters // Cofetarie Friscot = new Cofetarie(); // Friscot.adaugaClient(Razvan); // ProdusCofetarie Tiramisu = new ProdusCofetarie(); // Friscot.Razvan.adaugaProdusCofetarie(Tiramisu); // Friscot.Razvan.Tiramisu.afisarePret(); // cofetarieService.creareCofetarie(); // cofetarieService.afisareInformatiiCofetarie(); // cofetarieService.schimbareAdresaCofetarie(); // creem clienti Client clientTest1 = Client.builder() .adresa("iasi") .nume("ceva") .prenume("cristi") .varsta(29) .clientFidel(false) .build(); Client clientTest2 = Client.builder() .adresa("neamt") .nume("ifrim") .prenume("cristina") .varsta(29) .clientFidel(false) .build(); Client clientTest3 = Client.builder() .adresa("vaslui") .nume("popescu") .prenume("ramona") .varsta(29) .clientFidel(false) .build(); Client clientTest4 = Client.builder() .adresa("vaslui") .nume("fierascu") .prenume("alexandru") .varsta(29) .clientFidel(false) .build(); Client clientTest5 = Client.builder() .adresa("vaslui") .nume("fierascu") .prenume("roxana") .varsta(29) .clientFidel(false) .build(); Client clientTest6 = new Client(); clientTest6.setNume("Decebal"); clientTest6.setPrenume("Mircea"); cofetarieService.adaugaClient(clientTest1); cofetarieService.adaugaClient(clientTest2); cofetarieService.adaugaClient(clientTest3); cofetarieService.adaugaClient(clientTest4); cofetarieService.adaugaClient(clientTest5); // cofetarieService.afiseazaListaClientiCofetarie(); // cofetarieService.afiseazaNumarClientiExistenti(); // // cofetarieService.stergeClient(clientTest2); // cofetarieService.afiseazaListaClientiCofetarie(); // cofetarieService.afiseazaNumarClientiExistenti(); // // // ///primul client are pozitia 0 // //al 2lea client are pozitia 1 // //al 3lea client are pozitia 2 // cofetarieService.stergeClientPozitie(); // cofetarieService.afiseazaListaClientiCofetarie(); // cofetarieService.afiseazaNumarClientiExistenti(); // cofetarieService.stergeTotiClientiCofetarie(); // cofetarieService.afiseazaNumarClientiExistenti(); // System.out.println("===================\n==================="); // // ////////////adaugam produse cofetarie ProdusCofetarie produsCofetarie1 = new ProdusCofetarie(); produsCofetarie1.setNumeProdusCofetarie("tiramisu"); produsCofetarie1.setGramajProdusCofetarie(120); produsCofetarie1.setPretProdusCofetarie(10.99); ProdusCofetarie produsCofetarie2 = ProdusCofetarie.builder(). numeProdusCofetarie("cheesecake capsuni"). gramajProdusCofetarie(120). pretProdusCofetarie(15.99). build(); // // cofetarieService.adaugaProdusCofetarie(produsCofetarie1); // cofetarieService.adaugaProdusCofetarie(produsCofetarie2); // cofetarieService.afiseazaListaProduseCofetarie(); // cofetarieService.afiseazaNumarProduseCofetarieExistente(); // // // System.out.println("===================\n==================="); // System.out.println("PROGRAM ORAR"); // // cofetarieService.creazaProgramOrar(); // cofetarieService.afisareOrarCofetarie(); // // cofetarieService.schimbareOrar(); // cofetarieService.afisareOrarCofetarie(); clientService.adaugareProdusCofetarieInCosulDeCumparaturi(produsCofetarie1); clientService.adaugareProdusCofetarieInCosulDeCumparaturi(produsCofetarie2); clientService.afisarePretCosCumparaturi(); //clientService.calculareDiscount(); clientService.calcularePretFinalDupaDiscount(); } }
<filename>PyGLM/types/mvec/forward_declarations.h #pragma once #include "../forward_declarations.h" template<int L, typename T> static int mvec_getbuffer(mvec<L, T>* self, Py_buffer* view, int flags); void mvec_releasebuffer(PyObject* self, Py_buffer* view); template<int L> static Py_ssize_t mvec_len(PyObject* self); template<typename T> static PyObject* mvec2_sq_item(mvec<2, T> * self, Py_ssize_t index); template<typename T> static PyObject* mvec3_sq_item(mvec<3, T> * self, Py_ssize_t index); template<typename T> static PyObject* mvec4_sq_item(mvec<4, T> * self, Py_ssize_t index); template<typename T> static int mvec2_sq_ass_item(mvec<2, T> * self, Py_ssize_t index, PyObject * value); template<typename T> static int mvec3_sq_ass_item(mvec<3, T> * self, Py_ssize_t index, PyObject * value); template<typename T> static int mvec4_sq_ass_item(mvec<4, T> * self, Py_ssize_t index, PyObject * value); template<int L, typename T> static int mvec_contains(mvec<L, T> * self, PyObject * value); template<int L, typename T> static PyObject * mvec_add(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_sub(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_mul(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_mod(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_divmod(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_pow(PyObject * obj1, PyObject * obj2, PyObject * obj3); template<int L, typename T> static PyObject * mvec_neg(mvec<L, T> *obj); template<int L, typename T> static PyObject * mvec_pos(mvec<L, T> *obj); template<int L, typename T> static PyObject * mvec_abs(mvec<L, T> *obj); template<int L, typename T> static PyObject * mvec_iadd(mvec<L, T>* self, PyObject *obj); template<int L, typename T> static PyObject * mvec_isub(mvec<L, T>* self, PyObject *obj); template<int L, typename T> static PyObject * mvec_imul(mvec<L, T>* self, PyObject *obj); template<int L, typename T> static PyObject * mvec_imod(mvec<L, T>* self, PyObject *obj); template<int L, typename T> static PyObject * mvec_ipow(mvec<L, T>* self, PyObject * obj2, PyObject * obj3); template<int L, typename T> static PyObject * mvec_floordiv(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_div(PyObject *obj1, PyObject *obj2); template<int L, typename T> static PyObject * mvec_ifloordiv(mvec<L, T>* self, PyObject *obj); template<int L, typename T> static PyObject * mvec_idiv(mvec<L, T>* self, PyObject *obj); static void mvec_dealloc(PyObject* self); template<int L, typename T> static PyObject* mvec_copy(PyObject* self, PyObject*); template<int L, typename T> static PyObject* mvec_deepcopy(PyObject* self, PyObject* memo); template<typename T> static PyObject* mvec2_str(mvec<2, T>* self); template<typename T> static PyObject* mvec3_str(mvec<3, T>* self); template<typename T> static PyObject* mvec4_str(mvec<4, T>* self); template<int L, typename T> static PyObject* mvec_getattr(PyObject* obj, PyObject* name); template<int L, typename T> static int mvec_setattr(PyObject* obj, PyObject* name, PyObject* value); template<int L, typename T> static PyObject* mvec_richcompare(mvec<L, T>* self, PyObject* other, int comp_type); template<int L, typename T> static PyObject* mvec_geniter(mvec<L, T>* self); template<int L, typename T> static void mvecIter_dealloc(mvecIter<L, T> *rgstate); template<typename T> static PyObject* mvec2Iter_next(mvecIter<2, T> *rgstate); template<typename T> static PyObject* mvec3Iter_next(mvecIter<3, T> *rgstate); template<typename T> static PyObject* mvec4Iter_next(mvecIter<4, T> *rgstate); template<int L, typename T> static PyObject* mvecIter_new(PyTypeObject *type, PyObject *args, PyObject *kwargs);
<gh_stars>10-100 /* ---------------------------------------------------------------------------- Copyright (c) 2001-2002, <NAME> 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. * The name of the author 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 OWNER 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. ------------------------------------------------------------------------------*/ /* <NAME> <EMAIL> http://www.uni-karlsruhe.de/~uli2/ */ #include <stdio.h> #include <string.h> #include "extgl_wgl.h" #include "extgl.h" static HMODULE lib_gl_handle = NULL; void *extgl_GetProcAddress(const char *name) { void *t = wglGetProcAddress(name); if (t == NULL) { t = GetProcAddress(lib_gl_handle, name); if (t == NULL) { printfDebug("Could not locate symbol %s\n", name); } } return t; } bool extgl_Open(JNIEnv *env) { if (lib_gl_handle != NULL) return true; // load the dynamic libraries for OpenGL lib_gl_handle = LoadLibrary("opengl32.dll"); if (lib_gl_handle == NULL) { throwException(env, "Could not load OpenGL library"); return false; } return true; } void extgl_Close(void) { FreeLibrary(lib_gl_handle); lib_gl_handle = NULL; } /** returns true if the extension is available */ static bool WGLQueryExtension(WGLExtensions *extensions, const char *name) { const GLubyte *extension_string; if (!extensions->WGL_ARB_extensions_string) if (!extensions->WGL_EXT_extensions_string) return false; else extension_string = (GLubyte*)extensions->wglGetExtensionsStringEXT(); else extension_string = (GLubyte*)extensions->wglGetExtensionsStringARB(wglGetCurrentDC()); return extgl_QueryExtension(extension_string, name); } /*---------------------------------------------------------------------*/ static void extgl_InitWGLARBPbuffer(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglCreatePbufferARB", (void *)&extensions->wglCreatePbufferARB}, {"wglGetPbufferDCARB", (void *)&extensions->wglGetPbufferDCARB}, {"wglReleasePbufferDCARB", (void *)&extensions->wglReleasePbufferDCARB}, {"wglDestroyPbufferARB", (void *)&extensions->wglDestroyPbufferARB}, {"wglQueryPbufferARB", (void *)&extensions->wglQueryPbufferARB}}; if (extensions->WGL_ARB_pbuffer) extensions->WGL_ARB_pbuffer = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLARBPixelFormat(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglGetPixelFormatAttribivARB", (void *)&extensions->wglGetPixelFormatAttribivARB}, {"wglGetPixelFormatAttribfvARB", (void *)&extensions->wglGetPixelFormatAttribfvARB}, {"wglChoosePixelFormatARB", (void *)&extensions->wglChoosePixelFormatARB}}; if (extensions->WGL_ARB_pixel_format) extensions->WGL_ARB_pixel_format = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLARBRenderTexture(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglBindTexImageARB", (void *)&extensions->wglBindTexImageARB}, {"wglReleaseTexImageARB", (void *)&extensions->wglReleaseTexImageARB}, {"wglSetPbufferAttribARB", (void *)&extensions->wglSetPbufferAttribARB}}; if (extensions->WGL_ARB_render_texture) extensions->WGL_ARB_render_texture = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLEXTSwapControl(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglSwapIntervalEXT", (void *)&extensions->wglSwapIntervalEXT}, {"wglGetSwapIntervalEXT", (void *)&extensions->wglGetSwapIntervalEXT}}; if (extensions->WGL_EXT_swap_control) extensions->WGL_EXT_swap_control = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLARBMakeCurrentRead(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglMakeContextCurrentARB", (void *)&extensions->wglMakeContextCurrentARB}, {"wglGetCurrentReadDCARB", (void *)&extensions->wglGetCurrentReadDCARB}}; if (extensions->WGL_ARB_make_current_read) extensions->WGL_ARB_make_current_read = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLARBCreateContext(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglCreateContextAttribsARB", (void *)&extensions->wglCreateContextAttribsARB} }; if (extensions->WGL_ARB_create_context) extensions->WGL_ARB_create_context = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLNVPresentVideo(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglEnumerateVideoDevicesNV", (void *)&extensions->wglEnumerateVideoDevicesNV}, {"wglBindVideoDeviceNV", (void *)&extensions->wglBindVideoDeviceNV}, {"wglQueryCurrentContextNV", (void *)&extensions->wglQueryCurrentContextNV} }; if (extensions->WGL_NV_present_video) extensions->WGL_NV_present_video = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLNVVideoCapture(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglBindVideoCaptureDeviceNV", (void *)&extensions->wglBindVideoCaptureDeviceNV}, {"wglEnumerateVideoCaptureDevicesNV", (void *)&extensions->wglEnumerateVideoCaptureDevicesNV}, {"wglLockVideoCaptureDeviceNV", (void *)&extensions->wglLockVideoCaptureDeviceNV}, {"wglQueryVideoCaptureDeviceNV", (void *)&extensions->wglQueryVideoCaptureDeviceNV}, {"wglReleaseVideoCaptureDeviceNV", (void *)&extensions->wglReleaseVideoCaptureDeviceNV} }; if (extensions->WGL_NV_video_capture) extensions->WGL_NV_video_capture = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } /*---------------------------------------------------------------------*/ static void extgl_InitSupportedWGLExtensions(WGLExtensions *extensions) { extensions->WGL_ARB_buffer_region = WGLQueryExtension(extensions, "WGL_ARB_buffer_region"); extensions->WGL_ARB_make_current_read = WGLQueryExtension(extensions, "WGL_ARB_make_current_read"); extensions->WGL_ARB_multisample = WGLQueryExtension(extensions, "WGL_ARB_multisample"); extensions->WGL_ARB_pixel_format_float = WGLQueryExtension(extensions, "WGL_ARB_pixel_format_float"); extensions->WGL_ATI_pixel_format_float = WGLQueryExtension(extensions, "WGL_ATI_pixel_format_float"); extensions->WGL_ARB_pbuffer = WGLQueryExtension(extensions, "WGL_ARB_pbuffer"); extensions->WGL_ARB_pixel_format = WGLQueryExtension(extensions, "WGL_ARB_pixel_format"); extensions->WGL_ARB_render_texture = WGLQueryExtension(extensions, "WGL_ARB_render_texture"); extensions->WGL_EXT_swap_control = WGLQueryExtension(extensions, "WGL_EXT_swap_control"); extensions->WGL_NV_render_depth_texture = WGLQueryExtension(extensions, "WGL_NV_render_depth_texture"); extensions->WGL_NV_render_texture_rectangle = WGLQueryExtension(extensions, "WGL_NV_render_texture_rectangle"); extensions->WGL_ARB_framebuffer_sRGB = WGLQueryExtension(extensions, "WGL_ARB_framebuffer_sRGB") || WGLQueryExtension(extensions, "WGL_EXT_framebuffer_sRGB"); extensions->WGL_EXT_pixel_format_packed_float = WGLQueryExtension(extensions, "WGL_EXT_pixel_format_packed_float"); extensions->WGL_ARB_create_context = WGLQueryExtension(extensions, "WGL_ARB_create_context"); extensions->WGL_NV_multisample_coverage = WGLQueryExtension(extensions, "WGL_NV_multisample_coverage"); extensions->WGL_NV_present_video = WGLQueryExtension(extensions, "WGL_NV_present_video"); extensions->WGL_NV_video_capture = WGLQueryExtension(extensions, "WGL_NV_video_capture"); } static void extgl_InitWGLEXTExtensionsString(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglGetExtensionsStringEXT", (void *)&extensions->wglGetExtensionsStringEXT} }; extensions->WGL_EXT_extensions_string = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } static void extgl_InitWGLARBExtensionsString(WGLExtensions *extensions) { ExtFunction functions[] = { {"wglGetExtensionsStringARB", (void *)&extensions->wglGetExtensionsStringARB} }; extensions->WGL_ARB_extensions_string = extgl_InitializeFunctions(sizeof(functions)/sizeof(ExtFunction), functions); } void extgl_InitWGL(WGLExtensions *extensions) { extgl_InitWGLARBExtensionsString(extensions); extgl_InitWGLEXTExtensionsString(extensions); extgl_InitSupportedWGLExtensions(extensions); extgl_InitWGLARBMakeCurrentRead(extensions); extgl_InitWGLEXTSwapControl(extensions); extgl_InitWGLARBRenderTexture(extensions); extgl_InitWGLARBPixelFormat(extensions); extgl_InitWGLARBPbuffer(extensions); extgl_InitWGLARBCreateContext(extensions); extgl_InitWGLNVPresentVideo(extensions); extgl_InitWGLNVVideoCapture(extensions); }
<filename>custom/plugins/KerkowCustomModules/src/Resources/app/storefront/src/animal-parts/animal-parts.plugin.js import Plugin from "src/plugin-system/plugin.class"; import DomAccess from "src/helper/dom-access.helper"; import Iterator from "src/helper/iterator.helper"; import DeviceDetection from "src/helper/device-detection.helper"; export default class AnimalPartsPlugin extends Plugin { static options = { partsAreaSelector: "#parts", partsElementSelector: "path", partsJsonSelector: "#animal-parts-translations", animalTypeSelector: "data-animal-type", partsOverlaySelector: "parts-info-overlay", partsOverlayHeadlineClass: "info-headline", partsOverlayContentClass: "info-content", partsOverlayLinkClass: "info-link", partsMobileInstructorSelector: ".parts-instruction-mobile", partsInstructorSelector: ".parts-instruction", partsIsActiveClass: "is-active", hiddenClass: "d-none", }; init() { try { this._partsArea = DomAccess.querySelector( this.el, this.options.partsAreaSelector ); this._partsEls = this._partsArea.querySelectorAll( this.options.partsElementSelector ); const partsJson = DomAccess.querySelector( document, this.options.partsJsonSelector ); this._partsTranslations = JSON.parse(partsJson.innerHTML); this._animalType = this.el.getAttribute(this.options.animalTypeSelector); this._instruction = DomAccess.querySelector( document, this.options.partsInstructorSelector ); this._mobileInstruction = DomAccess.querySelector( document, this.options.partsMobileInstructorSelector ); } catch (e) { console.log(e); return; } // hide mobile instruction if is desktop device-detection if (DeviceDetection.isTouchDevice()) { this._instruction.classList.add(this.options.hiddenClass); this._mobileInstruction.classList.remove(this.options.hiddenClass); } else { this._instruction.classList.remove(this.options.hiddenClass); this._mobileInstruction.classList.add(this.options.hiddenClass); } this._registerEvents(); } /** * Register events * @private */ _registerEvents() { // register opening triggers Iterator.iterate(this._partsEls, (part) => { part.addEventListener("click", this._handlePartInfoEvent.bind(this)); }); // add click event listener to body const event = DeviceDetection.isTouchDevice() ? "touchstart" : "click"; document.body.addEventListener(event, this._onBodyClick.bind(this)); } /** * Register events * @private */ _handlePartInfoEvent() { //fade out instructions this._fadeOutEffect(this._mobileInstruction); this._fadeOutEffect(this._instruction); const id = event.target.getAttribute("id"); // Find translations const partContent = this._partsTranslations["animals"][this._animalType][ id ]; this._attachInfoOverlay(partContent, event); } /** * Register events * @private */ _attachInfoOverlay(partContent, event) { //remove existing overlays this._removeInfoOverlays(); event.target.classList.add(this.options.partsIsActiveClass); const headline = partContent["headline"]; const content = partContent["content"]; const link = partContent["link"]; const infoOverlay = document.createElement("div"); infoOverlay.classList.add(this.options.partsOverlaySelector); const headlineEl = document.createElement("p"); headlineEl.classList.add(this.options.partsOverlayHeadlineClass); headlineEl.innerHTML = headline; const contentEl = document.createElement("p"); contentEl.classList.add(this.options.partsOverlayContentClass); contentEl.innerHTML = content; const linkEl = document.createElement("p"); linkEl.classList.add(this.options.partsOverlayLinkClass); linkEl.innerHTML = link; infoOverlay.appendChild(headlineEl); infoOverlay.appendChild(contentEl); infoOverlay.appendChild(linkEl); this.el.appendChild(infoOverlay); } /** * Register events * @private */ _removeInfoOverlays() { const overlays = this.el.querySelectorAll( `.${this.options.partsOverlaySelector}` ); Iterator.iterate(this._partsEls, (part) => part.classList.remove(this.options.partsIsActiveClass) ); Iterator.iterate(overlays, (overlay) => overlay.remove()); } /** * Close/remove the search results from DOM if user * clicks outside the form or the results popover * @param {Event} e * @private */ _onBodyClick(e) { // remove infoOverlays if click outside of animal if ( e.target.nodeName != "path" && !e.target.parentNode.classList.contains( this.options.partsOverlayLinkClass ) ) { this._removeInfoOverlays(); } this.$emitter.publish("onBodyClick"); } /** * Close/remove the search results from DOM if user * clicks outside the form or the results popover * @private */ _fadeOutEffect(element) { var fadeTarget = element; var fadeEffect = setInterval(function () { if (!fadeTarget.style.opacity) { fadeTarget.style.opacity = 1; } if (fadeTarget.style.opacity > 0) { fadeTarget.style.opacity -= 0.1; } else { element.remove(); clearInterval(fadeEffect); } }, 30); } }
<reponame>stevenmiller888/deku-performance /** * Styles. */ export default { container: { position: 'fixed', width: '225px', height: '150px', 'font-size': '13px', '-webkit-font-smoothing': 'antialiased', 'box-shadow':'0 2px 10px rgba(0, 67, 115, .2)' }, table: { padding: '13px 0px' }, header: { 'font-weight': '600', 'line-height': '2px' }, row: { 'line-height': '2px' }, cell: { padding: '12px 12px 12px 24px' }, cellTime: { padding: '12px 12px 12px 24px', color: '#9C27B0' } };
<filename>Observer/Subject.cpp // // Created by wolf on 7/9/18. // #include "Subject.h" void Subject::Attach(Observer* observer) { observers_.emplace_back(observer); } // code from Mitch's in-class slide on erase-remove idiom void Subject::Detach(Observer* observer) { observers_.erase(std::remove_if(observers_.begin(), observers_.end(), [&observer](Observer const &value) { auto const result = &value == &observer; return result; }), observers_.end() ); } void Subject::Notify() { for (Observer* observer : observers_) observer->Update(); } }
#!/usr/bin/env bash #shellcheck disable=SC1091 # this is an example file to BUILD raw file system # export variable SUITE to set debootstrap suite name (default: hirsute) source plugins/envsetup source plugins/colors export OVERRIDER_COMPRESSION_TYPE export ENABLE_EXIT export FS_USER export FS_PASS frn="out/hirsute-raw" OVERRIDER_COMPRESSION_TYPE="gzip" ENABLE_EXIT=true do_debootstrap "${frn}-arm64" arm64 do_compress "${frn}-arm64" do_debootstrap "${frn}-armhf" armhf do_compress "${frn}-armhf" do_debootstrap "${frn}-amd64" amd64 do_compress "${frn}-amd64"
package commands import ( "strings" "testing" cmds "gx/ipfs/QmPHTMcFRnDfyF8mk7RXHoZXNQ3uvBHDmuLgvkG7RLwN6t/go-ipfs-cmds" ) func checkHelptextRecursive(t *testing.T, name []string, c *cmds.Command) { c.ProcessHelp() t.Run(strings.Join(name, "_"), func(t *testing.T) { if c.External { t.Skip("external") } t.Run("tagline", func(t *testing.T) { if c.Helptext.Tagline == "" { t.Error("no Tagline!") } }) t.Run("longDescription", func(t *testing.T) { t.Skip("not everywhere yet") if c.Helptext.LongDescription == "" { t.Error("no LongDescription!") } }) t.Run("shortDescription", func(t *testing.T) { t.Skip("not everywhere yet") if c.Helptext.ShortDescription == "" { t.Error("no ShortDescription!") } }) t.Run("synopsis", func(t *testing.T) { t.Skip("autogenerated in go-ipfs-cmds") if c.Helptext.Synopsis == "" { t.Error("no Synopsis!") } }) }) for subname, sub := range c.Subcommands { checkHelptextRecursive(t, append(name, subname), sub) } } func TestHelptexts(t *testing.T) { Root.ProcessHelp() checkHelptextRecursive(t, []string{"ipfs"}, Root) }
#!/bin/bash start(){ clear echo -e "\e[33m▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄ \e[31mCode: \e[37mYaman Efkar\n\e[33m▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄ \e[31mİnstagram: \e[37myamanefkarr\n\e[33m▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄ \e[31mYoutube: \e[37mYaman Efkar\n\e[33m▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄ \e[31mGitHub: \e[37myamanefkar\n\e[33m▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄ Tool Name: Wordlist-Pluas\n\n\n" rm -rf wordlist.txt cd Lib/ && rm -rf kayit.php read -p $'\e[31m[\e[32m!\e[31m]\e[37mAdı : ' adi read -p $'\e[31m[\e[32m!\e[31m]\e[37mSoyadı : ' soyad read -p $'\e[31m[\e[32m!\e[31m]\e[37mDoğum Tarihi : ' dogumtarih read -p $'\e[31m[\e[32m!\e[31m]\e[37mDoğum Yılı : ' dogumyilii read -p $'\e[31m[\e[32m!\e[31m]\e[37mLakabı : ' lakapi read -p $'\e[31m[\e[32m!\e[31m]\e[37mAnne Adı : ' annei read -p $'\e[31m[\e[32m!\e[31m]\e[37mBaba Adı : ' babai read -p $'\e[31m[\e[32m!\e[31m]\e[37mKardeş Adı : ' kardesi sleep 1 clear read -p $'\e[31m[\e[32m!\e[31m]\e[37mSevgilisinin Adı : ' sevgilii read -p $'\e[31m[\e[32m!\e[31m]\e[37mSevgilsinin Soyadı : ' sevsoyad read -p $'\e[31m[\e[32m!\e[31m]\e[37mÇıkma Tarihleri : ' sevtarih read -p $'\e[31m[\e[32m!\e[31m]\e[37mÇıkma Yılı : ' sevyil read -p $'\e[31m[\e[32m!\e[31m]\e[37mŞehir : ' sehiri sleep 1 clear read -p $'\e[31m[\e[32m!\e[31m]\e[37mPlaka : ' plaka read -p $'\e[31m[\e[32m!\e[31m]\e[37mTuttuğu Takım : ' takimi read -p $'\e[31m[\e[32m!\e[31m]\e[37mKısa Adı (gs,fb,bjk) : ' kisatakim read -p $'\e[31m[\e[32m!\e[31m]\e[37mTakımın Kuruluş Yılı : ' takimyil read -p $'\e[31m[\e[32m!\e[31m]\e[37mTelefon Numarası : ' numara read -p $'\e[31m[\e[32m!\e[31m]\e[37mAnnesinin Telefon Numarası : ' anneteli read -p $'\e[31m[\e[32m!\e[31m]\e[37mBabasının Telefon Numarası : ' babateli read -p $'\e[31m[\e[32m!\e[31m]\e[37mKardeşinin Telefon Numarası : ' kardesteli read -p $'\e[31m[\e[32m!\e[31m]\e[37mSevgilisinin Telefon Numarası : ' sevtel read -p $'\e[31m[\e[32m!\e[31m]\e[37mKurbanın Tc Kimlik Nosu : ' tcno read -p $'\e[31m[\e[32m!\e[31m]\e[37mEski Şifresi : ' eskisifrei echo " <?php \$ad = '$adi'; \$soyadad = '$soyad'; \$lakap = '$lakapi'; \$anne = '$annei'; \$baba = '$babai'; \$kardes = '$kardesi'; \$sevgili = '$sevgilii'; \$sevgilisoyad = '$sevsoyad'; \$dogumtarihi = '$dogumtarih'; \$dogumyili = '$dogumyilii'; \$cikmayili = '$sevyil'; \$cikmatarihi = '$sevtarih'; \$sehir = '$sehiri'; \$takim = '$takimi'; \$takimtarihi = '$takimyil'; \$takimkisa = '$kisatakim'; \$plaka = '$plaka'; \$eskisifre = '$eskisifrei'; \$tel = '$numara'; \$annetel = '$anneteli'; \$babatel = '$babateli'; \$kardestel = '$kardesteli'; \$sevgilitel = '$sevtel'; \$tckimlikno = '$tcno';?>" >> kayit.php php olanak-list.php php ad-list.php php anne-list.php php annetel-list.php php baba-list.php php babatel-list.php php cikmatarihi-list.php php cikmayili-list.php php dogumyili-list.php php eskisifre-list.php php kardes-list.php php kardestel-list.php php lakap-list.php php plaka-list.php php sehir-list.php php sevgili-list.php php sevgilisoyad-list.php php sevgilitel-list.php php soyad-list.php php takim-list.php php takimkisa-list.php php takimtarihi-list.php php tckimlikno-list.php php tel-list.php echo -e '\e[32mDosyanız Hazır : \e[37mwordlist.txt' } if [[ -e "Lib/ok.txt" ]]; then if [[ -e "wordlist.txt" ]]; then clear read -p $'\e[31m[\e[32m!\e[31m]\e[37mDaha önce oluşturduğunuz bir wordlist mevcut!\nYeni bir wordlist oluşturmak ister misiniz? [E,H] : ' yeni if [[ $yeni == "E" || $yeni == "e" ]]; then start elif [[ $yeni == "H" || $yeni == "h" ]]; then clear echo -e "Hayır 'ı seçtiniz.Eski Wordlist kullanılmaya devam edicek." else clear echo -e "Lütfen (E ,'Evet') (H ,'Hayır') seçeneklerinden birini seçiniz! " sleep 3 bash tst.sh fi else start fi else apt install php -y clear cd Lib/ echo "Bu Tool YamanEfkar Tarafından Kodlandı...." >> ok.txt cd .. bash tst.sh fi
#!/bin/sh IP=`ifconfig | grep inet | grep broad | cut -d " " -f10` NIFI_URL="nifi.wssim.com.br" echo "$IP $NIFI_URL" >> /etc/hosts # sed -i -e "s|^nifi.web.http.host=.*$|nifi.web.http.host=$(ifconfig | grep inet | grep broad | cut -d " " -f10)|" conf/nifi.properties sed -i -e "s|^nifi.web.https.host=.*$|nifi.web.https.host=$NIFI_URL|" conf/nifi.properties sed -i -e "s|^nifi.cluster.node.address=.*$|nifi.cluster.node.address=$(ifconfig | grep inet | grep broad | cut -d " " -f10)|" conf/nifi.properties sed -i -e "s|^nifi.remote.input.host=.*$|nifi.remote.input.host=$(ifconfig | grep inet | grep broad | cut -d " " -f10)|" conf/nifi.properties /opt/nifi/bin/nifi.sh start tailf logs/*
<filename>app/controllers/window/main.js var args = arguments[0] || {}; exports.baseController = "./window/abstract"; function test(){ var controller = Alloy.createController('window/main/child'); Alloy.Globals.openWindow(controller); }
<reponame>corganhejijun/frontal-face-trans<filename>lfw_distance_calculate.py # -*- coding: utf-8 -*- from src.FaceDistance import getDatasetDistance LFW_DATASET = "datasets/lfw" MODEL_DIR = "models/20180402-114759" RESULT_FILE_PATH = "compare/result/lfw_distance.txt" getDatasetDistance(RESULT_FILE_PATH, LFW_DATASET, MODEL_DIR)
<reponame>alemesa1991/School-Projects // GB - A trivial, not very interesting, producer consumer thread pool // - It is a 'one shot' thread pool. // - Threads are created, read the queue, exit when done. // - This requires the total amount of work to be understood by the producer and the consumer. // - GB pass workUnit size to the consumer and totalWork size to the producer. // - GB convert consumer threads to array of threads from fixed calls. // - The salient feature is uses 'threadsafe-queue.h'. // - The queue uses mutex to lock access and condition variables to wait if the queue is empty. // clang++ -std=c++11 producer_consumer.cpp -o producer_consumer -lrt // http://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/ // https://github.com/juanchopanza/cppblog/blob/master/Concurrency/Queue/producer_consumer1.cpp // // Copyright (c) 2013 <NAME> <EMAIL> // Subject to the BSD 2-Clause License // - see < http://opensource.org/licenses/BSD-2-Clause> // // #pragma once // file threadsafe-queue.h // http://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/ // // Copyright (c) 2013 <NAME> <EMAIL> // Subject to the BSD 2-Clause License // - see < http://opensource.org/licenses/BSD-2-Clause> // // GB - 2016 tidied up, converted to use move semantics #include <queue> #include <thread> #include <mutex> #include <condition_variable> template <typename T> class Queue { std::queue<T> q; std::mutex m; std::condition_variable c; public: T&& pop() { std::unique_lock<std::mutex> mlock(m); while (q.empty()) { c.wait(mlock); } auto val = std::move(q.front()); q.pop(); return std::move(val); } void pop(T&& item) { std::unique_lock<std::mutex> mlock(m); while (q.empty()) { c.wait(mlock); } item = std::move(q.front()); q.pop(); } void push(const T&& item) { std::unique_lock<std::mutex> mlock(m); q.push(std::move(item)); mlock.unlock(); c.notify_one(); } Queue() = default; virtual ~Queue() {} Queue(const Queue&) = delete; // disable copy constructor Queue(Queue&&) = delete; // disable move constructor Queue& operator= (const Queue&) = delete; // disable copy assignment Queue&& operator= (Queue&&) = delete; // disable move assignment }; // class Queue #include <thread> #include <mutex> // for screenLock #include <iostream> // #include "threadsafe-queue.h" std::mutex screenLock; void produce(Queue<unsigned>& q, unsigned totalWork) { for (unsigned i = 0; i< totalWork; i++) { {std::unique_lock<std::mutex> myTurn(screenLock); std::cout << "Pushing " << i << "\n"; } q.push(std::move(i)); } } void consume(Queue<unsigned>& q, unsigned id, unsigned workUnits) { for (unsigned i = 0; i< workUnits; i++) { auto item = q.pop(); {std::unique_lock<std::mutex> myTurn(screenLock); std::cout << "Consumer " << id << " popped " << item << "\n"; } } } int main() { Queue<unsigned> q; unsigned TOTALWORK = 15; // 10000; unsigned NUMTHREADS = 5; unsigned WORKUNITS = TOTALWORK / NUMTHREADS; // consumer threads std::unique_ptr<std::thread[]> consumers(new std::thread[NUMTHREADS]); for(unsigned t = 0; t < NUMTHREADS; t++) consumers[t] = std::thread( std::bind(&consume, std::ref(q), t+1, WORKUNITS) ); // producer thread std::thread producer( std::bind(produce, std::ref(q), TOTALWORK) ); producer.join(); for(unsigned t = 0; t < NUMTHREADS; t++) consumers[t].join(); }
import { UserService } from "../services/user_service"; import { Controller, Singleton, textResult } from "fortjs"; export class WebPushController extends Controller { service: UserService; constructor() { super(); } sendNotification(@Singleton(UserService) service) { console.log('send notification') return textResult("notification sent"); } }
<filename>banking/src/test/java/io/pickles/sample_apps/banking/steps/AccountSteps.java<gh_stars>0 package io.pickles.sample_apps.banking.steps; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import io.pickles.sample_apps.banking.domain.DomainModel; public class AccountSteps { private DomainModel model; public AccountSteps(DomainModel model) { this.model = model; } @Given("^a creditor account$") public void aCreditorAccount() throws Throwable { model.setCreditor("creditor account"); model.addLog("creditor account is available"); } @Given("^a debtor account$") public void aDebtorAccount() throws Throwable { model.setDebtor("debtor account"); model.addLog("debtor account is available"); } @Then("^the creditor account is credited with EUR (\\d+)\\.(\\d+)$") public void theCreditorAccountIsCreditedWithEUR(int arg1, int arg2) throws Throwable { model.addLog("creditor account is credited with " + model.getAmount()); } @Then("^the debtor account is debited with EUR (\\d+)\\.(\\d+)$") public void theDebtorAccountIsDebitedWithEUR(int arg1, int arg2) throws Throwable { model.addLog("debtor account is debited with " + model.getAmount()); } }
# This is a very basic/naive implementation of syncing your job schedules to be monitored # It might be better to just use this as a template to write your own syncing. namespace :cronitor do namespace :sidekiq_scheduler do desc 'Upload Sidekiq Scheduler Cron Jobs to Cronitor' # uses the Rails environment because we constantize the class to read the sidekiq_options task :sync => :environment do monitors_payload = [] # go through the scheduled jobs and find cron defined ones Sidekiq.get_schedule.each do |k, v| # make sure the job has a cron definition, we skip non cron defined jobs for now unless v["cron"].nil? # just in case an explicit job key has been set job_klass = Object.const_get(v["class"]) job_key = job_klass.sidekiq_options.fetch("cronitor_key", nil) || v["class"] # if monitoring for this job is turned off cronitor_disabled = job_klass.sidekiq_options.fetch("cronitor_disabled", false) monitors_payload << {key: job_key.to_s, schedule: v["cron"], platform: 'sidekiq', type: 'job' } unless cronitor_disabled end end Cronitor::Monitor.put(monitors: monitors_payload) end end end
<filename>CGMES_2.4.15_27JAN2020/cim4j/WindTurbineType3or4Dynamics.java package cim4j; import java.util.List; import java.util.Map; import java.util.HashMap; import cim4j.DynamicsFunctionBlock; import java.lang.ArrayIndexOutOfBoundsException; import java.lang.IllegalArgumentException; import cim4j.EnergySource; import cim4j.RemoteInputSignal; import cim4j.WindPlantDynamics; /* Parent class supporting relationships to wind turbines Type 3 and 4 and wind plant including their control models. */ public class WindTurbineType3or4Dynamics extends DynamicsFunctionBlock { private BaseClass[] WindTurbineType3or4Dynamics_class_attributes; private BaseClass[] WindTurbineType3or4Dynamics_primitive_attributes; private java.lang.String rdfid; public void setRdfid(java.lang.String id) { rdfid = id; } private abstract interface PrimitiveBuilder { public abstract BaseClass construct(java.lang.String value); }; private enum WindTurbineType3or4Dynamics_primitive_builder implements PrimitiveBuilder { LAST_ENUM() { public BaseClass construct (java.lang.String value) { return new cim4j.Integer("0"); } }; } private enum WindTurbineType3or4Dynamics_class_attributes_enum { EnergySource, RemoteInputSignal, WindPlantDynamics, LAST_ENUM; } public WindTurbineType3or4Dynamics() { WindTurbineType3or4Dynamics_primitive_attributes = new BaseClass[WindTurbineType3or4Dynamics_primitive_builder.values().length]; WindTurbineType3or4Dynamics_class_attributes = new BaseClass[WindTurbineType3or4Dynamics_class_attributes_enum.values().length]; } public void updateAttributeInArray(WindTurbineType3or4Dynamics_class_attributes_enum attrEnum, BaseClass value) { try { WindTurbineType3or4Dynamics_class_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void updateAttributeInArray(WindTurbineType3or4Dynamics_primitive_builder attrEnum, BaseClass value) { try { WindTurbineType3or4Dynamics_primitive_attributes[attrEnum.ordinal()] = value; } catch (ArrayIndexOutOfBoundsException aoobe) { System.out.println("No such attribute: " + attrEnum.name() + ": " + aoobe.getMessage()); } } public void setAttribute(java.lang.String attrName, BaseClass value) { try { WindTurbineType3or4Dynamics_class_attributes_enum attrEnum = WindTurbineType3or4Dynamics_class_attributes_enum.valueOf(attrName); updateAttributeInArray(attrEnum, value); System.out.println("Updated WindTurbineType3or4Dynamics, setting " + attrName); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } /* If the attribute is a String, it is a primitive and we will make it into a BaseClass */ public void setAttribute(java.lang.String attrName, java.lang.String value) { try { WindTurbineType3or4Dynamics_primitive_builder attrEnum = WindTurbineType3or4Dynamics_primitive_builder.valueOf(attrName); updateAttributeInArray(attrEnum, attrEnum.construct(value)); System.out.println("Updated WindTurbineType3or4Dynamics, setting " + attrName + " to: " + value); } catch (IllegalArgumentException iae) { super.setAttribute(attrName, value); } } public java.lang.String toString(boolean topClass) { java.lang.String result = ""; java.lang.String indent = ""; if (topClass) { for (WindTurbineType3or4Dynamics_primitive_builder attrEnum: WindTurbineType3or4Dynamics_primitive_builder.values()) { BaseClass bc = WindTurbineType3or4Dynamics_primitive_attributes[attrEnum.ordinal()]; if (bc != null) { result += " WindTurbineType3or4Dynamics." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } for (WindTurbineType3or4Dynamics_class_attributes_enum attrEnum: WindTurbineType3or4Dynamics_class_attributes_enum.values()) { BaseClass bc = WindTurbineType3or4Dynamics_class_attributes[attrEnum.ordinal()]; if (bc != null) { result += " WindTurbineType3or4Dynamics." + attrEnum.name() + "(" + bc.debugString() + ")" + " " + bc.toString(false) + System.lineSeparator(); } } result += super.toString(true); } else { result += "(WindTurbineType3or4Dynamics) RDFID: " + rdfid; } return result; } public final java.lang.String debugName = "WindTurbineType3or4Dynamics"; public java.lang.String debugString() { return debugName; } public void setValue(java.lang.String s) { System.out.println(debugString() + " is not sure what to do with " + s); } public BaseClass construct() { return new WindTurbineType3or4Dynamics(); } };
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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 org.jetbrains.webdemo.backend.executor; import org.jetbrains.webdemo.backend.BackendSettings; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class JavaExecutorBuilder { private String mainClass; private boolean enableAssertions = false; private boolean enableSecurityManager = false; private Path policyFile; private Integer memoryLimit = null; private List<Path> classPath = new ArrayList<>(); private List<String> arguments = new ArrayList<>(); public JavaExecutorBuilder enableAssertions() { enableAssertions = true; return this; } public JavaExecutorBuilder enableSecurityManager() { enableSecurityManager = true; return this; } public JavaExecutorBuilder setPolicyFile(Path policyFile) { this.policyFile = policyFile; return this; } public JavaExecutorBuilder setMemoryLimit(int memoryLimit) { this.memoryLimit = memoryLimit; return this; } public JavaExecutorBuilder setMainClass(String mainClass) { this.mainClass = mainClass; return this; } public JavaExecutorBuilder addToClasspath(Path path) { classPath.add(path); return this; } public JavaExecutorBuilder addToClasspath(List<Path> paths) { classPath.addAll(paths); return this; } public JavaExecutorBuilder addArgument(String argument) { arguments.add(argument); return this; } public JavaExecutor build() { List<String> arguments = new ArrayList<>(); arguments.add(BackendSettings.JAVA_EXECUTE); if (enableAssertions) { arguments.add("-ea"); } if (memoryLimit != null) { arguments.add("-Xmx" + memoryLimit + "M"); } if (enableSecurityManager) { arguments.add("-Djava.security.manager"); } if (policyFile != null) { arguments.add("-Djava.security.policy=" + policyFile.toString()); } if(!classPath.isEmpty()){ arguments.add("-classpath"); StringBuilder classPathString = new StringBuilder(); String separator = ""; for(Path classPathElement : classPath){ classPathString.append(separator); classPathString.append(classPathElement); separator = File.pathSeparator; } arguments.add(classPathString.toString()); } if (mainClass != null){ arguments.add(mainClass); } arguments.addAll(this.arguments); return new JavaExecutor(arguments.toArray(new String[arguments.size()])); } }
import React from 'react' import ReactNative from 'react-native' const {View, StyleSheet} = ReactNative import StaticContainer from './StaticContainer' export default SceneComponent = (Props) => { const {shouldUpdated, ...props} = Props return <View {...props}> <StaticContainer shouldUpdate={shouldUpdated}> {props.children} </StaticContainer> </View> }
package main import ( "constraints" "fmt" ) // ToString convert any type to string func ToString(value interface{}) string { if v, ok := value.(*string); ok { return *v } return fmt.Sprintf("%v", value) } func toString[T constraints.Ordered](value T) string { return fmt.Sprintf("%v", value) } // ToBool convert any type to boolean func ToBool(value interface{}) bool { switch value := value.(type) { case bool: return value case int: if value != 0 { return true } return false } return false } // can't work with type convert // func toBool[T constraints.Ordered](value T) bool { // switch value := value.(type) { // case bool: // return value // case int: // if value != 0 { // return true // } // return false // } // return false // } func main() { fmt.Println(ToString("abc")) fmt.Println(ToString(1234)) fmt.Println(ToString(1234.5678)) fmt.Println(toString("abc")) fmt.Println(toString(1234)) fmt.Println(toString(1234.5678)) fmt.Println(ToBool(true)) fmt.Println(ToBool(false)) fmt.Println(ToBool(1234)) fmt.Println(ToBool(0)) }
package io.opensphere.server.toolbox; /** * The Interface ServerRefreshController. */ public interface ServerRefreshController { /** * Gets the interval in minutes between refresh commands being sent. * * @return the refresh interval in minutes */ int getRefreshInterval(); /** * Checks if server refreshes are enabled. * * @return true, if refreshes are enabled */ boolean isRefreshEnabled(); /** * Restore defaults. */ void restoreDefaults(); /** * Enable/Disable server refreshes. * * @param isEnabled true to enable server refreshes, false otherwise */ void setRefreshEnabled(boolean isEnabled); /** * Set the interval in minutes between sending refresh commands. * * @param interval the new refresh interval in minutes */ void setRefreshInterval(int interval); }
sudo apt install -y libopenblas-base libomp-dev pip install faiss # wget -O faiss_cpu.tar.bz2 https://anaconda.org/pytorch/faiss-cpu/1.4.0/download/linux-64/faiss-cpu-1.4.0-py36_cuda0.0_1.tar.bz2 # tar xvjf faiss_cpu.tar.bz2 && cp -r lib/python3.6/site-packages/faiss ml_tools/faiss/faiss_cpu -R && rm lib/ -R && rm info/ -R # wget -O faiss_gpu.tar.bz2 https://anaconda.org/pytorch/faiss-gpu/1.4.0/download/linux-64/faiss-gpu-1.4.0-py36_cuda9.2.148_1.tar.bz2 # tar xvjf faiss_gpu.tar.bz2 && cp -r lib/python3.6/site-packages/faiss ml_tools/faiss/faiss_gpu -R && rm lib/ -R && rm info/ -R
<filename>enrichment-coordinator-service/src/test/java/org/oransc/enrichment/clients/AsyncRestClientTest.java /*- * ========================LICENSE_START================================= * O-RAN-SC * %% * Copyright (C) 2020 Nordix Foundation * %% * 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. * ========================LICENSE_END=================================== */ package org.oransc.enrichment.clients; import io.netty.util.internal.logging.InternalLoggerFactory; import io.netty.util.internal.logging.JdkLoggerFactory; import java.io.IOException; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.client.WebClientResponseException; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.Loggers; class AsyncRestClientTest { private static final String BASE_URL = "BaseUrl"; private static final String REQUEST_URL = "/test"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private static final String TEST_JSON = "{\"type\":\"type1\"}"; private static final int SUCCESS_CODE = 200; private static final int ERROR_CODE = 500; private static MockWebServer mockWebServer; private static AsyncRestClient clientUnderTest; @BeforeAll static void init() { // skip a lot of unnecessary logs from MockWebServer InternalLoggerFactory.setDefaultFactory(JdkLoggerFactory.INSTANCE); Loggers.useJdkLoggers(); mockWebServer = new MockWebServer(); clientUnderTest = new AsyncRestClient(mockWebServer.url(BASE_URL).toString()); } @AfterAll static void tearDown() throws IOException { mockWebServer.shutdown(); } @Test void testGetNoError() { mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) // .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) // .setBody(TEST_JSON)); Mono<String> returnedMono = clientUnderTest.get(REQUEST_URL); StepVerifier.create(returnedMono).expectNext(TEST_JSON).expectComplete().verify(); } @Test void testGetError() { mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE)); Mono<String> returnedMono = clientUnderTest.get(REQUEST_URL); StepVerifier.create(returnedMono) .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify(); } @Test void testPutNoError() { mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) // .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) // .setBody(TEST_JSON)); Mono<String> returnedMono = clientUnderTest.put(REQUEST_URL, TEST_JSON); StepVerifier.create(returnedMono).expectNext(TEST_JSON).expectComplete().verify(); } @Test void testPutError() { mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE)); Mono<String> returnedMono = clientUnderTest.put(REQUEST_URL, TEST_JSON); StepVerifier.create(returnedMono) .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify(); } @Test void testDeleteNoError() { mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE)); Mono<String> returnedMono = clientUnderTest.delete(REQUEST_URL); StepVerifier.create(returnedMono).expectNext("").expectComplete().verify(); } @Test void testDeleteError() { mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE)); Mono<String> returnedMono = clientUnderTest.delete(REQUEST_URL); StepVerifier.create(returnedMono) .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify(); } @Test void testPostNoError() { mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) // .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) // .setBody(TEST_JSON)); Mono<String> returnedMono = clientUnderTest.post(REQUEST_URL, TEST_JSON); StepVerifier.create(returnedMono).expectNext(TEST_JSON).expectComplete().verify(); } @Test void testPostError() { mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE)); Mono<String> returnedMono = clientUnderTest.post(REQUEST_URL, TEST_JSON); StepVerifier.create(returnedMono) .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify(); } @Test void testPostWithAuthHeaderNoError() { mockWebServer.enqueue(new MockResponse().setResponseCode(SUCCESS_CODE) // .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) // .setBody(TEST_JSON)); Mono<String> returnedMono = clientUnderTest.postWithAuthHeader(REQUEST_URL, TEST_JSON, USERNAME, PASSWORD); StepVerifier.create(returnedMono).expectNext(TEST_JSON).expectComplete().verify(); } @Test void testPostWithAuthHeaderError() { mockWebServer.enqueue(new MockResponse().setResponseCode(ERROR_CODE)); Mono<String> returnedMono = clientUnderTest.postWithAuthHeader(REQUEST_URL, TEST_JSON, USERNAME, PASSWORD); StepVerifier.create(returnedMono) .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify(); } }
#!/bin/bash read -p "Enter path to kafka Directory : " DIR read -p "kafka url : " URL cd ${DIR}/ echo "Removing Topics..." bin/kafka-topics.sh --delete --topic job-response-trainer --bootstrap-server ${URL}:9092 bin/kafka-topics.sh --delete --topic job-request-trainer --bootstrap-server ${URL}:9092 bin/kafka-topics.sh --delete --topic job-request-aggregator --bootstrap-server ${URL}:9092 bin/kafka-topics.sh --delete --topic job-response-aggregator --bootstrap-server ${URL}:9092
import { h } from 'hyperapp'; import Component from '../Component'; const Index = ({ state }) => ( <div className="fig-index"> {state.figures.map((figure, i) => ( <Component state={state} figure={figure} index={i} /> ))} </div> ); export default Index;
<gh_stars>1-10 package com.github.shaquu.networking.packets; import com.github.shaquu.file.TorroFile; import java.util.*; public class PacketManager { private HashMap<Long, Integer> packetParts = new HashMap<>(); private HashMap<Long, Packet[]> receivedParts = new HashMap<>(); private HashMap<TorroFile, Integer> packetFileParts = new HashMap<>(); private HashMap<TorroFile, Packet[]> receiverFileParts = new HashMap<>(); public HashMap<TorroFile, Packet[]> getReceiverFileParts() { return receiverFileParts; } public HashMap<Long, Packet[]> getReceivedParts() { return receivedParts; } public boolean add(Packet packet) { int maxPart = packet.getMaxPart(); long id = packet.getId(); if (!packetParts.containsKey(id)) { packetParts.put(id, maxPart); } if (!receivedParts.containsKey(id)) { receivedParts.put(id, new Packet[maxPart]); } receivedParts.get(id)[packet.getPart() - 1] = packet; for (Packet p : receivedParts.get(id)) { if (p == null) return false; } return true; } public boolean add(PushFilePacket packet) { int maxPart = packet.getMaxPart(); TorroFile torroFile = packet.getTorroFile(); if (!packetFileParts.containsKey(torroFile)) { packetFileParts.put(torroFile, maxPart); } if (!receiverFileParts.containsKey(torroFile)) { receiverFileParts.put(torroFile, new Packet[maxPart]); } receiverFileParts.get(torroFile)[packet.getPart() - 1] = packet; for (Packet p : receiverFileParts.get(torroFile)) { if (p == null) return false; } return true; } public Packet getPacket(Class clazz, long id) { if (receivedParts.containsKey(id)) { List<Byte> byteList = new ArrayList<>(); Arrays.stream(receivedParts.get(id)).forEach(e -> Collections.addAll(byteList, e.getData())); Byte[] data = byteList.toArray(new Byte[0]); if (clazz == RequestFileListPacket.class) { return new RequestFileListPacket(id); } else if (clazz == FileListPacket.class) { return new FileListPacket(id, 1, 1, data); } else if (clazz == PullFilePacket.class) { return new PullFilePacket(id, 1, 1, data, ((PullFilePacket) receivedParts.get(id)[0]).getTorroFile()); } else if (clazz == PushFilePacket.class) { return new PushFilePacket(id, 1, 1, data, ((PushFilePacket) receivedParts.get(id)[0]).getTorroFile()); } else if (clazz == LogOnPacket.class) { return new LogOnPacket(id); } else if (clazz == PullFilePartsPacket.class) { return new PullFilePartsPacket(id, 1, 1, data, ((PullFilePartsPacket) receivedParts.get(id)[0]).getParts()); } else { return new Packet(id, -1, -1, data); } } else return null; } public PushFilePacket getPushFilePacket(TorroFile torroFile) { if (receiverFileParts.containsKey(torroFile)) { List<Byte> byteList = new ArrayList<>(); Arrays.stream(receiverFileParts.get(torroFile)).forEach(e -> Collections.addAll(byteList, e.getData())); Byte[] data = byteList.toArray(new Byte[0]); return new PushFilePacket(receiverFileParts.get(torroFile)[0].getId(), 1, 1, data, torroFile); } else return null; } }
/* */ /*********************************************************** Copyright 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. 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 OPEN GROUP 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. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "Xlibint.h" #include <X11/Xos.h> #include "Xresource.h" #include <stdio.h> #ifndef ERRORDB #ifndef XERRORDB #define ERRORDB "/usr/lib/X11/XErrorDB" #else #define ERRORDB XERRORDB #endif #endif /* * descriptions of errors in Section 4 of Protocol doc (pp. 350-351); more * verbose descriptions are given in the error database */ static const char _XErrorList[] = /* No error */ "no error\0" /* BadRequest */ "BadRequest\0" /* BadValue */ "BadValue\0" /* BadWindow */ "BadWindow\0" /* BadPixmap */ "BadPixmap\0" /* BadAtom */ "BadAtom\0" /* BadCursor */ "BadCursor\0" /* BadFont */ "BadFont\0" /* BadMatch */ "BadMatch\0" /* BadDrawable */ "BadDrawable\0" /* BadAccess */ "BadAccess\0" /* BadAlloc */ "BadAlloc\0" /* BadColor */ "BadColor\0" /* BadGC */ "BadGC\0" /* BadIDChoice */ "BadIDChoice\0" /* BadName */ "BadName\0" /* BadLength */ "BadLength\0" /* BadImplementation */ "BadImplementation" ; /* offsets into _XErrorList */ static const unsigned char _XErrorOffsets[] = { 0, 9, 20, 29, 39, 49, 57, 67, 75, 84, 96, 106, 115, 124, 130, 142, 150, 160 }; int XGetErrorText( register Display *dpy, register int code, char *buffer, int nbytes) { char buf[150]; register _XExtension *ext; _XExtension *bext = (_XExtension *)NULL; if (nbytes == 0) return 0; if (code <= BadImplementation && code > 0) { sprintf(buf, "%d", code); (void) XGetErrorDatabaseText(dpy, "XProtoError", buf, _XErrorList + _XErrorOffsets[code], buffer, nbytes); } else buffer[0] = '\0'; /* call out to any extensions interested */ for (ext = dpy->ext_procs; ext; ext = ext->next) { if (ext->error_string) (*ext->error_string)(dpy, code, &ext->codes, buffer, nbytes); if (ext->codes.first_error && ext->codes.first_error <= code && (!bext || ext->codes.first_error > bext->codes.first_error)) bext = ext; } if (!buffer[0] && bext) { sprintf(buf, "%s.%d", bext->name, code - bext->codes.first_error); (void) XGetErrorDatabaseText(dpy, "XProtoError", buf, "", buffer, nbytes); } if (!buffer[0]) sprintf(buffer, "%d", code); return 0; } int /*ARGSUSED*/ XGetErrorDatabaseText( Display *dpy, register _Xconst char *name, register _Xconst char *type, _Xconst char *defaultp, char *buffer, int nbytes) { static XrmDatabase db = NULL; XrmString type_str; XrmValue result; char temp[BUFSIZ]; char* tptr; unsigned long tlen; if (nbytes == 0) return 0; if (!db) { /* the Xrm routines expect to be called with the global mutex unlocked. */ XrmDatabase temp_db; int do_destroy; const char *dbname; XrmInitialize(); #ifdef WIN32 dbname = getenv("XERRORDB"); if (!dbname) dbname = ERRORDB; #else dbname = ERRORDB; #endif temp_db = XrmGetFileDatabase(dbname); _XLockMutex(_Xglobal_lock); if (!db) { db = temp_db; do_destroy = 0; } else do_destroy = 1; /* we didn't need to get it after all */ _XUnlockMutex(_Xglobal_lock); if (do_destroy) XrmDestroyDatabase(temp_db); } if (db) { tlen = strlen (name) + strlen (type) + 2; if (tlen <= sizeof(temp)) tptr = temp; else tptr = Xmalloc (tlen); if (tptr) { sprintf(tptr, "%s.%s", name, type); XrmGetResource(db, tptr, "ErrorType.ErrorNumber", &type_str, &result); if (tptr != temp) Xfree (tptr); } else { result.addr = (XPointer) NULL; } } else result.addr = (XPointer)NULL; if (!result.addr) { result.addr = (XPointer) defaultp; result.size = strlen(defaultp) + 1; } (void) strncpy (buffer, (char *) result.addr, nbytes); if (result.size > nbytes) buffer[nbytes-1] = '\0'; return 0; }
import { Suite, Test, } from '../index.js'; import { assert } from 'chai'; export default [new Suite('chai - login window', [ new Test('should display login form', async function() { await (async () => {})(); return; }) .before('async before test with 100ms timeout', function(done) { // this.skip(); setTimeout(done, 100); }) .after('after test', async () => {}) .after('after test 2', async () => {}), new Suite('attempting login with wrong credentials', [ new Test('should show error message with username', function() { return { user: 'The User!' }; }), new Test('should show error message with email', function() {}), new Test('should expect this test to fail', async () => { assert.isOk('', 'I wanted to fail!'); }), new Test('user should be in scope', function() { assert.isOk(this.context.user, 'I wanted to fail!'); }), new Test('should return proper error object', async () => { assert.deepEqual({ status: 'error', message: 'system error', nested: { random: 'value' } }, { status: 'error', message: 'invalid credentials', nested: { expected: 'value' } }, 'incorrect error'); }), new Suite('using wrong password', [ new Test('should show error message', (done) => { setTimeout(() => { done(new Error('did not show error message')) }, 50); }), new Test('user should be in scope', function() { assert.isOk(this.context.user, 'user was not in scope'); }) ]), ]), new Suite('attempting login with correct credentials', [ new Test('should display user page', () => {}), new Test('should authenticate websocket connection', () => {}), new Test('user should not be in scope', function() { assert.isNotOk(this.context.user, 'user was in scope'); }) ]) .beforeEach('before each!', async () => {}) ])];
<filename>validator/src/test/resources/de/mirkosertic/ddd/validation/ValidValueObject1.java<gh_stars>1-10 import de.mirkosertic.ddd.annotation.ValueObject; import java.util.Date; @ValueObject public class ValidValueObject1 { public static enum TestType { }; private final String member1; private final Date member2; private final ValidValueObject1 member3; private final TestType testType; ValidValueObject1() { member1 = null; member2 = null; member3 = null; testType = null; } }
find site -type f -exec sed -i "s|svg.latex?|svg.latex?\\\color{white}|g" {} \; #sed -i "s|png.latex?|png.latex?\\\color{white}|g" site/index.html
<reponame>afkham-azeez/jaxrs-engine<gh_stars>1-10 /* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.mss.internal; import co.cask.http.HttpHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * DataHolder for the MSS component */ public class DataHolder { private static final Logger LOG = LoggerFactory.getLogger(DataHolder.class); private volatile Set<HttpHandler> httpServices = new HashSet<>(); private static DataHolder instance = new DataHolder(); private DataHolder() { } static DataHolder getInstance() { return instance; } void addHttpService(HttpHandler httpHandler) { httpServices.add(httpHandler); LOG.info("Added HTTP Service: " + httpHandler); } void removeHttpService(HttpHandler httpService) { httpServices.remove(httpService); } Set<HttpHandler> getHttpServices() { return Collections.unmodifiableSet(httpServices); } }
#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec {1 , 4, 8, 2, 5}; int sum = 0; for (int x : vec) { sum += x; } cout << "The average is: " << (sum / vec.size()) << endl; return 0; }
<gh_stars>0 #include <stdio.h> void evil() { printf("i am evil\n"); } void q() { // bitte modifizieren Sie nur im Bereich unterhalb dieser Zeile // Toben Sie sich hier aus! // bitte modifizieren Sie nur im Bereich oberhalb dieser Zeile printf("q is done \n"); } void harmless() { q(); } int main() { harmless(); return 0; }
<gh_stars>1-10 import React from 'react'; import './App.css'; import WordBoard from './components/WordBoard'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import 'bootstrap/dist/css/bootstrap.min.css'; import { devToolsEnhancer } from 'redux-devtools-extension'; import reducer from './reducers/BoardReducer'; export const store = (process.env.NODE_ENV === 'production') ? createStore(reducer) : createStore(reducer, devToolsEnhancer({})); function App() { return ( <div className="App"> <Provider store={store}> <WordBoard /> </Provider> </div> ); } export default App;
def find_two_sum(nums, target_sum): complements = {} for i, num in enumerate(nums): if target_sum - num in complements: return nums[complements[target_sum - num]], num else: complements[num] = i result = find_two_sum([1, 2, 3, 4, 5], 6) print(result)
#! /bin/sh SVG_SRC_FILE="Kyzenred" SVG_SRC_FILE_EXT=".svg" STYLE_TAG_REPLACE="(<style(\s|\S)*?id=\"current-color-scheme\"(\s|\S)*?<\/style>)"; STYLESHEET_FILE="../src/recolor.css" FULL_GTK2_IN_SCR_FILE="../src/$SVG_SRC_FILE-in$SVG_SRC_FILE_EXT" FULL_GTK2_OUT_SCR_FILE="../$SVG_SRC_FILE$SVG_SRC_FILE_EXT" if [ -e $STYLESHEET_FILE ]; then echo Generating standard colors... # Standart Colors STYLESHEET=$( < $STYLESHEET_FILE ./kyzenred-color-edit.sh "ForegroundNormal" "Colors:Window" "text" | ./kyzenred-color-edit.sh "BackgroundNormal" "Colors:Window" "background" | ./kyzenred-color-edit.sh "BackgroundNormal" "Colors:Selection" "highlight" | ./kyzenred-color-edit.sh "ForegroundNormal" "Colors:View" "view_text" | ./kyzenred-color-edit.sh "BackgroundNormal" "Colors:View" "view_background" | ./kyzenred-color-edit.sh "DecorationHover" "Colors:View" "view_hover" | ./kyzenred-color-edit.sh "DecorationFocus" "Colors:View" "view_focus" | ./kyzenred-color-edit.sh "ForegroundNormal" "Colors:Button" "button_text" | ./kyzenred-color-edit.sh "BackgroundNormal" "Colors:Button" "button_background" | ./kyzenred-color-edit.sh "DecorationFocus" "Colors:Button" "button_focus" | ./kyzenred-color-edit.sh "DecorationHover" "Colors:Button" "button_hover" ) echo Generating inactive colors... # Inactive Colors STYLESHEET=$(echo "$STYLESHEET" | ./kyzenred-color-edit-effects.sh "ForegroundInactive" "Colors:Window" "text_inactive" i | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Window" "background_inactive" i | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Selection" "highlight_inactive" i | ./kyzenred-color-edit-effects.sh "ForegroundInactive" "Colors:View" "view_text_inactive" i | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:View" "view_background_inactive" i | ./kyzenred-color-edit-effects.sh "DecorationHover" "Colors:View" "view_hover_inactive" i | ./kyzenred-color-edit-effects.sh "DecorationFocus" "Colors:View" "view_focus_inactive" i | ./kyzenred-color-edit-effects.sh "ForegroundInactive" "Colors:Button" "button_text_inactive" i | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Button" "button_background_inactive" i | ./kyzenred-color-edit-effects.sh "DecorationFocus" "Colors:Button" "button_focus_inactive" i | ./kyzenred-color-edit-effects.sh "DecorationHover" "Colors:Button" "button_hover_inactive" i ) echo Generating disabled colors... # disabled Colors STYLESHEET=$(echo "$STYLESHEET" | ./kyzenred-color-edit-effects.sh "ForegroundNormal" "Colors:Window" "text_disabled" d | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Window" "background_disabled" d | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Selection" "highlight_disabled" d | ./kyzenred-color-edit-effects.sh "ForegroundNormal" "Colors:View" "view_text_disabled" d | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:View" "view_background_disabled" d | ./kyzenred-color-edit-effects.sh "DecorationHover" "Colors:View" "view_hover_disabled" d | ./kyzenred-color-edit-effects.sh "DecorationFocus" "Colors:View" "view_focus_disabled" d | ./kyzenred-color-edit-effects.sh "ForegroundNormal" "Colors:Button" "button_text_disabled" d | ./kyzenred-color-edit-effects.sh "BackgroundNormal" "Colors:Button" "button_background_disabled" d | ./kyzenred-color-edit-effects.sh "DecorationFocus" "Colors:Button" "button_focus_disabled" d | ./kyzenred-color-edit-effects.sh "DecorationHover" "Colors:Button" "button_hover_disabled" d ) echo Generating mixed colors... # disabled Colors STYLESHEET=$(echo "$STYLESHEET" | ./kyzenred-color-edit-mix.sh "BackgroundNormal" "Colors:Window" "ForegroundNormal" "Colors:Window" "0.2" "inactive-tab-borders" | ./kyzenred-color-edit-mix.sh "BackgroundNormal" "Colors:Window" "ForegroundNormal" "Colors:Window" "0.25" "inactive-tab" ) echo Generating special opacities... # contrast opacities and cleaning STYLESHEET=$(echo "$STYLESHEET" | ./kyzenred-color-edit-contrast.sh i | ./kyzenred-color-edit-contrast.sh d ) echo Cleaning up... # cleanup STYLESHEET=$(echo "$STYLESHEET" | tr '\n' ' '| tr '\t' ' ' ) STYLESHEET="<style id=\"­current-color-scheme\">$STYLESHEET</style>"; echo Refreshing SVGs... cp -f $FULL_GTK2_IN_SCR_FILE $FULL_GTK2_OUT_SCR_FILE && sleep 1 echo "Inserting CSS <style> code..." sed -i "s@$STYLE_TAG_REPLACE@$STYLESHEET@" $FULL_GTK2_OUT_SCR_FILE echo SVG file generated! else >&2 echo src/recolor.css was not found. Stopped... exit 1 fi
The algorithm should first identify the parts of the webpage which are taking up the most loading time. Examples may include inefficient code, large images, complex interactions and so on. Then it should suggest optimizations for these areas so as to reduce their loading times. Some approaches you could take to optimize a webpage include: - Minifying and compressing HTML, CSS and JavaScript files, including removing redundant and/or unnecessary elements. - Creating compressed and scaled images for faster loading. - Reducing page redirects and minifying any existing redirects. - Splitting large JavaScript and CSS files into smaller components when possible. - Leveraging browser caching by setting different expiration times for different element types.
#!/bin/bash # Copyright 2014 Google Inc. All rights reserved. # # 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. # TODO(jbeda): Provide a way to override project ZONE=us-central1-b MASTER_SIZE=g1-small MINION_SIZE=g1-small NUM_MINIONS=2 # TODO(dchen1107): Filed an internal issue to create an alias # for containervm image, so that gcloud will expand this # to the latest supported image. IMAGE=container-vm-v20141016 IMAGE_PROJECT=google-containers NETWORK=e2e INSTANCE_PREFIX="e2e-test-${USER}" MASTER_NAME="${INSTANCE_PREFIX}-master" MASTER_TAG="${INSTANCE_PREFIX}-master" MINION_TAG="${INSTANCE_PREFIX}-minion" MINION_NAMES=($(eval echo ${INSTANCE_PREFIX}-minion-{1..${NUM_MINIONS}})) MINION_IP_RANGES=($(eval echo "10.245.{1..${NUM_MINIONS}}.0/24")) MINION_SCOPES=("storage-ro" "compute-rw") # Increase the sleep interval value if concerned about API rate limits. 3, in seconds, is the default. POLL_SLEEP_INTERVAL=3 PORTAL_NET="10.0.0.0/16" # When set to true, Docker Cache is enabled by default as part of the cluster bring up. ENABLE_DOCKER_REGISTRY_CACHE=true ENABLE_NODE_MONITORING=true ENABLE_NODE_LOGGING=true LOGGING_DESTINATION=elasticsearch # options: elasticsearch, gcp ENABLE_CLUSTER_MONITORING=false # Don't require https for registries in our local RFC1918 network EXTRA_DOCKER_OPTS="--insecure-registry 10.0.0.0/8"
#!/usr/bin/env bash set -e GITHUB_UPSTREAM=https://github.com/RocketSoftware/carbon-charts.git lerna run lint if [ $? -ne 0 ] then echo "Error: There were lint errors in the code, please review above and fix." exit 1 fi # Refresh code git pull upstream master if [ $? -ne 0 ] then echo "Error: Couldn't pull from upstream." echo "Try running 'git remote add upstream $GITHUB_UPSTREAM' and try again." exit 1 fi if [ $? -ne 0 ] then echo "There was an error running lerna bootstrap." exit 1 fi # if package locks updated, add them if [ ! -z "`git ls-files -m | grep package-lock.json`" ] then git add package-lock.json ./packages/*/package-lock.json git commit -m "Update package-lock.json files" fi lerna run format #exit 1 # stops push from running, good for testing