repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
maria-farooq/Avalon
avalon-io/src/main/java/org/koaksoft/avalon/input/BaseInputReader.java
package org.koaksoft.avalon.input; import java.util.Scanner; /** * base input reader * * @author mariafarooq * */ public class BaseInputReader implements InputReader { private final Scanner scanner; public BaseInputReader(Scanner scanner) { super(); this.scanner = scanner; } public String readString() { return scanner.nextLine(); } public int readInt() { return Integer.parseInt(scanner.nextLine()); } }
shaojiankui/iOS10-Runtime-Headers
PrivateFrameworks/StoreKitUI.framework/SKUIBadgeTextAttachmentLoader.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/StoreKitUI.framework/StoreKitUI */ @interface SKUIBadgeTextAttachmentLoader : NSObject <SKUIArtworkRequestDelegate> { NSMapTable * _imageRequests; SKUIResourceLoader * _resourceLoader; NSHashTable * _stringViews; } @property (readonly, copy) NSString *debugDescription; @property (readonly, copy) NSString *description; @property (readonly) unsigned long long hash; @property (readonly) Class superclass; - (void).cxx_destruct; - (void)artworkRequest:(id)arg1 didLoadImage:(id)arg2; - (void)connectStringView:(id)arg1; - (void)disconnectStringView:(id)arg1; - (id)initWithResourceLoader:(id)arg1; - (bool)loadImageForBadge:(id)arg1 layout:(id)arg2 reason:(long long)arg3; @end
praveennagaraj97/e-commerce-using-react-and-express
Community-side/src/components/Works/index.js
import KeyBoarders from "./KeyBoarders"; import Manufacturer from "./Manufacturer"; export { KeyBoarders, Manufacturer };
freibergerb/web-stories-wp
packages/story-editor/src/testUtils/renderWithTheme.js
<filename>packages/story-editor/src/testUtils/renderWithTheme.js /* * Copyright 2020 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 * * https://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. */ /** * External dependencies */ import { render, queries } from '@testing-library/react'; import { ThemeProvider } from 'styled-components'; /** * Internal dependencies */ import theme from '../theme'; import * as ariaLabelQueries from './queryByAriaLabel'; import * as autoAdvanceAfterQueries from './queryByAutoAdvanceAfter'; import * as idQueries from './queryById'; // eslint-disable-next-line react/prop-types const WithThemeProvider = ({ children }) => { return <ThemeProvider theme={theme}>{children}</ThemeProvider>; }; const renderWithTheme = (ui, options) => render(ui, { wrapper: WithThemeProvider, queries: { ...queries, ...ariaLabelQueries, ...autoAdvanceAfterQueries, ...idQueries, }, ...options, }); export default renderWithTheme;
LalaChen/SDEngine
SourceCode/src/Basic/FileSystem/FileResourceRequester.cpp
#include "LogManager.h" #include "FileSystemManager.h" #include "AssetResourceManager.h" #include "FileResourceRequester.h" ______________SD_START_BASIC_NAMESPACE_______________ SD_SINGLETON_DECLARATION_IMPL(FileResourceRequester); const std::string FileResourceRequester::sFilePathTypeStrings[FilePathType_MAX_DEFINE_VALUE] = { std::string("file:///"), std::string("asset:///") }; FileResourceRequester::FileResourceRequester() { } FileResourceRequester::~FileResourceRequester() { } bool FileResourceRequester::AskFile(const FilePathString &i_location, FileData &io_file) { bool result = false; FilePathString final_path; FilePathTypeEnum fp_type = ConvertFilePath(i_location, final_path); if (FileSystemManager::IsNull() == false) { if (fp_type == FilePathType_MAX_DEFINE_VALUE || fp_type == FilePathType_LOCAL_FILE) { result = FileSystemManager::GetRef().OpenFile(final_path, io_file); if (result == false) { if (fp_type != FilePathType_MAX_DEFINE_VALUE) { SDLOG("File[%s] isn't exist!!!", i_location.c_str()); return result; } else { SDLOGE("File[%s] isn't exist!!! Ask this file to AssetResourceManager.", i_location.c_str()); } } } else { SDLOG("filepath[%s] isn't local file.", i_location.c_str()); } } else { SDLOGW("FileSystemManager isn't launched!!! Ask this file[%s] to AssetResourceManager.", i_location.c_str()); } if (result == false) { if (AssetResourceManager::IsNull() == false) { if (fp_type == FilePathType_MAX_DEFINE_VALUE || fp_type == FilePathType_ASSET) { result = AssetResourceManager::GetRef().LoadAsset(i_location, io_file); if (result == false) { SDLOGW("File[%s] isn't exist in file system and asset!!! Please check.", i_location.c_str()); } } else { SDLOG("filepath[%s] isn't asset.", i_location.c_str()); } } else { SDLOGW("AssetResourceManager isn't launched!!! Ask File[%s] failure. Please check.", i_location.c_str()); } } return result; } FilePathTypeEnum FileResourceRequester::ConvertFilePath(const FilePathString &i_location, FilePathString &io_final_path) { for (uint32_t type = 0; type < static_cast<uint32_t>(FilePathType_MAX_DEFINE_VALUE); ++type) { size_t tag_pos = i_location.find(sFilePathTypeStrings[type]); if (tag_pos != std::string::npos) { size_t path_pos = tag_pos + sFilePathTypeStrings[type].length(); io_final_path = i_location.substr(path_pos, i_location.size() - path_pos); return static_cast<FilePathTypeEnum>(type); } } io_final_path = i_location; return FilePathType_MAX_DEFINE_VALUE; } FilePathString FileResourceRequester::CatenateFilePath(const FilePathString &i_location, const FilePathString &i_target_dir) { size_t tag_pos = i_location.find("///"); if (tag_pos != std::string::npos) { tag_pos += 3; } FilePathString final_dir = i_target_dir; FilePathString fp; if (final_dir[final_dir.size() - 1] != '/') { final_dir += "/"; } if (tag_pos != std::string::npos) { fp = i_location; fp.insert(tag_pos, final_dir); } else { fp = final_dir + i_location; } std::size_t current_dir_pos = fp.find("./"); if (current_dir_pos != std::string::npos) { fp.replace(current_dir_pos, 2, "", 0, 0); } return fp; } _______________SD_END_BASIC_NAMESPACE________________
op-ct/rubygem-simp-cli
lib/simp/cli/config/item/certificates.rb
require "resolv" require 'highline/import' require File.expand_path( '../item', File.dirname(__FILE__) ) require File.expand_path( '../utils', File.dirname(__FILE__) ) module Simp; end class Simp::Cli; end module Simp::Cli::Config class Item::Certificates < ActionItem attr_accessor :dirs def initialize super @key = 'certificates' @description = %Q{Sets up the cerificates for SIMP on apply. (apply-only; noop)} @dirs = { :keydist => '/etc/puppet/environments/simp/keydist', :fake_ca => '/etc/puppet/environments/simp/FakeCA', } @die_on_apply_fail = true end def apply # Certificate Management say_green 'Checking system certificates...' if !@silent hostname = @config_items.fetch( 'hostname' ).value if !( File.exist?("#{@dirs[:keydist]}/#{hostname}/#{hostname}.pub") && File.exist?("#{@dirs[:fake_ca]}/#{hostname}/#{hostname}.pem") ) say_green "INFO: No certificates were found for '#{hostname}, generating..." if !@silent Simp::Cli::Config::Utils.generate_certificates([hostname], @dirs[:fake_ca]) else say_yellow "WARNING: Found existing certificates for #{hostname}, not recreating" if !@silent end end end end
903136698/Secret
app/src/main/java/com/jikexueyuan/secret/net/GetComment.java
<reponame>903136698/Secret package com.jikexueyuan.secret.net; import com.jikexueyuan.secret.Config; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by MiracleWong on 2015/7/6. */ public class GetComment { public GetComment(String phone_md5, String token, String msgId, int page, int perpage, final SuccessCallback successCallback, final FailCallback failCallback){ new NetConnection(Config.SERVER_URL, HttpMethod.POST, new NetConnection.SuccessCallback() { @Override public void onSuccess(String result) { try { JSONObject jsonObject = new JSONObject(result); switch (jsonObject.getInt(Config.KEY_STATUS)) { case Config.RESULT_STATUS_SUCCESS: if (successCallback != null){ List<Comment> comments = new ArrayList<Comment>(); JSONArray commentsJsonArray =jsonObject.getJSONArray(Config.KEY_COMMENTS); JSONObject commentObj; for (int i = 0; i < commentsJsonArray.length(); i++) { commentObj = commentsJsonArray.getJSONObject(i); // 组建comments的数组 comments.add(new Comment(commentObj.getString(Config.KEY_CONTENT), commentObj.getString(Config.KEY_PHONE_MD5))); } successCallback.onSuccess(jsonObject.getString(Config.KEY_MSG_ID), jsonObject.getInt(Config.KEY_PAGE), jsonObject.getInt(Config.KEY_PERPAGE), comments); // successCallback.onSuccess("123", 1, 20, comments); } break; case Config.RESULT_STATUS_INVALID_TOKEN: if (failCallback!=null) { failCallback.onFail(Config.RESULT_STATUS_INVALID_TOKEN); } break; default: if (failCallback != null){ failCallback.onFail(Config.RESULT_STATUS_FAIL); } break; } } catch (JSONException e) { e.printStackTrace(); } } }, new NetConnection.FailCallback() { @Override public void onFail() { if (failCallback != null){ failCallback.onFail(Config.RESULT_STATUS_FAIL); } } }, Config.KEY_ACTION, Config.ACTION_GET_COMMENT,Config.KEY_TOKEN, token, Config.KEY_MSG_ID, msgId, Config.KEY_PAGE, page+"", Config.KEY_PERPAGE, perpage+"" ); } public static interface SuccessCallback{ void onSuccess(String msgId, int page, int perpage, List<Comment> comments); } public static interface FailCallback{ void onFail(int errorCode); } }
openlibraryenvironment/ncip-tools
src/main/java/org/olf/ncip/v1schema/UserNoticeSent.java
<gh_stars>0 // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.07.08 at 10:19:21 AM BST // package org.olf.ncip.v1schema; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "initiationHeader", "uniqueUserId", "dateSent", "userNoticeDetails" }) @XmlRootElement(name = "UserNoticeSent") public class UserNoticeSent { @XmlElement(name = "InitiationHeader", required = true) protected InitiationHeader initiationHeader; @XmlElement(name = "UniqueUserId", required = true) protected UniqueUserId uniqueUserId; @XmlElement(name = "DateSent", required = true) protected DateSent dateSent; @XmlElement(name = "UserNoticeDetails", required = true) protected UserNoticeDetails userNoticeDetails; /** * Gets the value of the initiationHeader property. * * @return * possible object is * {@link InitiationHeader } * */ public InitiationHeader getInitiationHeader() { return initiationHeader; } /** * Sets the value of the initiationHeader property. * * @param value * allowed object is * {@link InitiationHeader } * */ public void setInitiationHeader(InitiationHeader value) { this.initiationHeader = value; } /** * Gets the value of the uniqueUserId property. * * @return * possible object is * {@link UniqueUserId } * */ public UniqueUserId getUniqueUserId() { return uniqueUserId; } /** * Sets the value of the uniqueUserId property. * * @param value * allowed object is * {@link UniqueUserId } * */ public void setUniqueUserId(UniqueUserId value) { this.uniqueUserId = value; } /** * Gets the value of the dateSent property. * * @return * possible object is * {@link DateSent } * */ public DateSent getDateSent() { return dateSent; } /** * Sets the value of the dateSent property. * * @param value * allowed object is * {@link DateSent } * */ public void setDateSent(DateSent value) { this.dateSent = value; } /** * Gets the value of the userNoticeDetails property. * * @return * possible object is * {@link UserNoticeDetails } * */ public UserNoticeDetails getUserNoticeDetails() { return userNoticeDetails; } /** * Sets the value of the userNoticeDetails property. * * @param value * allowed object is * {@link UserNoticeDetails } * */ public void setUserNoticeDetails(UserNoticeDetails value) { this.userNoticeDetails = value; } }
coryb/gearbox
gearbox/t/core/plugins/goodbye.cc
<filename>gearbox/t/core/plugins/goodbye.cc // Copyright (c) 2012, Yahoo! Inc. All rights reserved. // Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. #include <gearbox/core/logger.h> #include "TestPlugin.h" struct Goodbye : public TestPlugin { Goodbye() { _DEBUG("Goodbye constructor"); } ~Goodbye() { _DEBUG("Goodbye destructor"); } std::string get() { return "goodbye"; } void set( std::string & data ) { data = "goodbye"; } }; // plugin interface extern "C" { void * goodbye_new(); void goodbye_delete(void *); } void * goodbye_new() { return new Goodbye(); } void goodbye_delete(void *ptr) { delete (Goodbye*)ptr; }
readysetstem/readysetstem-api
projects/hw/hw_test_accel.py
<reponame>readysetstem/readysetstem-api<filename>projects/hw/hw_test_accel.py #!/usr/bin/python3 from rstem.accel import Accel from rstem.gpio import Input, Output from rstem.button import Button import sys import time import os def near(actual, expected): return abs(actual - expected) < 0.1 NUM_SAMPLES = 5 pins = { "PASS0":10, "FAIL0":22, "PASS1":27, "FAIL1":17, "PASS2":14, "FAIL2":15, "PASS3":18, "FAIL3":23, "PASS4":24, "FAIL4":25, "PASS5":8, "FAIL5":7, "PASS6":12, "FAIL6":16, "PASS7":20, "FAIL7":21, "READY":19, "XTEST":13, "YTEST":6, "ZTEST":5, "STAT1":11, "STAT2":9, "START":26, } # # Pins are turned on by 5V with GPIO to ground. Unfortunately, the GPIOs can # only go to 3.3V to turn them off, so instead we turn them off by disabling # the pin (i.e. making an Input). we keep track of the current pin state in # pin_io. # pin_io = {} def on(pin_name): if pin_name in pin_io: pin_io[pin_name].disable() pin_io[pin_name] = Output(pins[pin_name]) pin_io[pin_name].on() def off(pin_name): if pin_name in pin_io: pin_io[pin_name].disable() pin_io[pin_name] = Input(pins[pin_name]) def all_off(): for led in pins: if led != "START": off(led) # # flasher generator # def flasher(pin_name, on_time, off_time): start = time.time() on(pin_name) while True: elapsed = time.time() - start if elapsed > off_time: on(pin_name) start = time.time() elif elapsed > on_time: off(pin_name) yield def select_i2c_device(bus, part): otherbus = 0 if bus else 1 def switch_cmd(bus, partmask): os.system("/usr/sbin/i2cset -y 1 {:s} {:s}".format(hex(0x70+bus), hex(partmask))) switch_cmd(bus, 1<<part) switch_cmd(otherbus, 0x00) def tester(xgood, ygood, zgood): start = time.time() for bus in range(2): for part in range(4): select_i2c_device(bus, part) try: a = Accel() except: yield False continue index = bus*4 + part forces = [] for sample in range(NUM_SAMPLES): elapsed = 0 while elapsed < 0.1: yield elapsed = time.time() - start start = time.time() try: forces.append(a.forces()) except: break if len(forces) < NUM_SAMPLES: yield False else: def mean(items): return sum(items)/len(items) xs, ys, zs = list(zip(*forces)) print(bus, part, xs, ys, zs) yield near(xgood, mean(xs)) and near(ygood, mean(ys)) and near(zgood, mean(zs)) def flash_until_button(led): flash = flasher(led, 0.1, 1.0) while not start_button.presses(): next(flash) time.sleep(0.01) on(led) def test_all_in_one_direction(led, xgood, ygood, zgood): flash_until_button(led) for i in range(8): off("FAIL" + str(i)) flash = flasher(led, 0.1, 0.2) test = tester(xgood, ygood, zgood) results = [] for result in test: if result != None: results.append(result) next(flash) time.sleep(0.01) on(led) for i, passed in enumerate(results): if not passed: on("FAIL" + str(i)) return results start_button = Button(pins["START"]) # # Hack! Pin 8 is used by the LED Driver SPI bus, which we don't care about # here. So we forcibly disable it. # os.system("echo 8 > /sys/class/gpio/unexport") all_off() while True: for led in ["XTEST", "YTEST", "ZTEST"]: off(led) flash_until_button("READY") all_off() xresults = test_all_in_one_direction("XTEST", 1, 0, 0) yresults = test_all_in_one_direction("YTEST", 0, 1, 0) zresults = test_all_in_one_direction("ZTEST", 0, 0, 1) for i, results in enumerate(zip(xresults, yresults, zresults)): if False in results: on("FAIL" + str(i)) off("PASS" + str(i)) else: off("FAIL" + str(i)) on("PASS" + str(i))
zhangshuai930822/BUCK
test/com/facebook/buck/cli/RootCommandTest.java
<reponame>zhangshuai930822/BUCK /* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cli; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.junit.MatcherAssert.assertThat; import com.facebook.buck.testutil.TestConsole; import java.io.IOException; import org.junit.Test; public class RootCommandTest { @Test public void testPrintsProjectRootToStdout() throws IOException, InterruptedException { TestConsole console = new TestConsole(); CommandRunnerParams commandRunnerParams = CommandRunnerParamsForTesting.builder().setConsole(console).build(); RootCommand runCommand = new RootCommand(); int exitCode = runCommand.run(commandRunnerParams); String testRoot = commandRunnerParams .getCell() .getFilesystem() .getRootPath() .normalize() .toAbsolutePath() .toString(); assertThat(console.getTextWrittenToStdOut(), containsString(testRoot)); assertThat(exitCode, equalTo(0)); } }
abhijeetbodas2001/DSA
part-01/2_18_find-peak-element.cpp
// Problem: https://leetcode.com/problems/find-peak-element/ // O(log(n)) time, O(1) extra space // Modified binary search. class Solution { public: int findPeakElement(vector<int>& nums) { int len = nums.size(); int left = 0; int right = len - 1; int mid; if (len == 1) { return 0; } while (true) { mid = (left + right) / 2; if (mid == 0) { if (left == 0 && right == 0) { assert(nums[0] > nums[1]); return 0; } else { assert(left == 0 && right == 1); return (nums[0] > nums[1]? 0 : 1); } } if (mid == len - 1) { assert(right == len - 1 && left == len - 1); assert(nums[len - 2] < nums[len - 1]); return len - 1; } // Note: Given no two consequetive elements are equal. if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) { return mid; } else if (nums[mid - 1] < nums[mid] && nums[mid] < nums[mid + 1]) { left = mid + 1; } else if (nums[mid - 1] > nums[mid] && nums[mid] > nums[mid + 1]) { right = mid - 1; } else { assert(nums[mid - 1] > nums[mid] && nums[mid] < nums[mid + 1]); // Both halves will have at least one peak. Arbitrarily select the right half. left = mid + 1; } } } };
yuchange/myDemoGather
myDemo/Android/gradle-2.12/src/plugins/org/gradle/api/internal/plugins/DefaultTemplateBasedStartScriptGenerator.java
<reponame>yuchange/myDemoGather /* * Copyright 2015 the original author or authors. * * 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.gradle.api.internal.plugins; import com.google.common.io.CharSource; import groovy.text.SimpleTemplateEngine; import groovy.text.Template; import org.gradle.api.Transformer; import org.gradle.api.UncheckedIOException; import org.gradle.api.internal.resources.CharSourceBackedTextResource; import org.gradle.api.resources.TextResource; import org.gradle.internal.io.IoUtils; import org.gradle.internal.resource.CharsetUtil; import org.gradle.jvm.application.scripts.JavaAppStartScriptGenerationDetails; import org.gradle.jvm.application.scripts.TemplateBasedScriptGenerator; import org.gradle.util.TextUtil; import java.io.*; import java.util.Map; public class DefaultTemplateBasedStartScriptGenerator implements TemplateBasedScriptGenerator { private final String lineSeparator; private final Transformer<Map<String, String>, JavaAppStartScriptGenerationDetails> bindingFactory; private TextResource template; public DefaultTemplateBasedStartScriptGenerator(String lineSeparator, Transformer<Map<String, String>, JavaAppStartScriptGenerationDetails> bindingFactory, TextResource template) { this.lineSeparator = lineSeparator; this.bindingFactory = bindingFactory; this.template = template; } public void generateScript(JavaAppStartScriptGenerationDetails details, Writer destination) { try { Map<String, String> binding = bindingFactory.transform(details); String scriptContent = generateStartScriptContentFromTemplate(binding); destination.write(scriptContent); } catch (IOException e) { throw new UncheckedIOException(e); } } public void setTemplate(TextResource template) { this.template = template; } public TextResource getTemplate() { return template; } private String generateStartScriptContentFromTemplate(final Map<String, String> binding) { return IoUtils.get(getTemplate().asReader(), new Transformer<String, Reader>() { @Override public String transform(Reader reader) { try { SimpleTemplateEngine engine = new SimpleTemplateEngine(); Template template = engine.createTemplate(reader); String output = template.make(binding).toString(); return TextUtil.convertLineSeparators(output, lineSeparator); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } protected static TextResource utf8ClassPathResource(final Class<?> clazz, final String filename) { return new CharSourceBackedTextResource(new CharSource() { @Override public Reader openStream() throws IOException { InputStream stream = clazz.getResourceAsStream(filename); if (stream == null) { throw new IllegalStateException("Could not find class path resource " + filename + " relative to " + clazz.getName()); } return new BufferedReader(new InputStreamReader(stream, CharsetUtil.UTF_8)); } }); } }
femtoio/femtousb-blink-example
blinky/common/services/gfx_mono/example1/example1.c
/** * \file * * \brief Monochrome graphic library example application * * Copyright (c) 2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ /** * \mainpage * * \section intro Introduction * This is an example application for the \ref gfx_mono. * It will output some random graphic primitives to a connected LCD screen or * framebuffer. * * \section files Main Files * - \ref conf_board.h * - \ref conf_clock.h * - \ref conf_st7565r.h or conf_ssd1306.h * - \ref conf_usart_spi.h * * \section device_info Device Info * All AVR devices can be used. * This example has been tested with the following setup: * - XMEGA-A3BU Xplained * - XMEGA-C3 Xplained * * \section dependencies Dependencies * Relevant module dependencies for this application are: * - \ref gfx_mono * * \section compinfo Compilation info * This software was written for the GNU GCC and IAR for AVR. Other compilers * may or may not work. * * \section contactinfo Contact Information * For further information, visit <a href="http://www.atmel.com/">Atmel</a>.\n */ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include <board.h> #include <sysclk.h> #include <gfx_mono.h> // Bitmap of two 8x8 pixel smileyfaces on top of each other stored in RAM uint8_t smiley_data[16] = { 0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C, 0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C }; // Bitmap of two 8x8 pixel smileyfaces on top of each other stored in FLASH PROGMEM_DECLARE(gfx_mono_color_t, flash_bitmap[16]) = { 0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C, 0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C }; int main(void){ struct gfx_mono_bitmap smiley; struct gfx_mono_bitmap smiley_flash; board_init(); sysclk_init(); /* Initialize GFX lib. Will configure the display controller and * create a framebuffer in RAM if the controller lack two-way communication */ gfx_mono_init(); // Setup bitmap struct for bitmap stored in RAM smiley.type = GFX_MONO_BITMAP_RAM; smiley.width = 8; smiley.height = 16; smiley.data.pixmap = smiley_data; // Setup bitmap for bitmap stored in FLASH smiley_flash.type = GFX_MONO_BITMAP_PROGMEM; smiley_flash.width = 8; smiley_flash.height = 16; smiley_flash.data.progmem = flash_bitmap; // Output bitmaps to display gfx_mono_put_bitmap(&smiley, 50, 0); gfx_mono_put_bitmap(&smiley_flash, 0, 0); //Draw horizontal an vertical lines with length 128 and 32 pixels gfx_mono_draw_vertical_line(1, 0, 32, GFX_PIXEL_SET); gfx_mono_draw_horizontal_line(0, 2, 128, GFX_PIXEL_SET); // Draw a line from the top-left corner to the bottom right corner gfx_mono_draw_line(0, 0, 127, 31, GFX_PIXEL_SET); // Draw a rectangle with upper left corner at x=20,y=10 - width=height=10px gfx_mono_draw_rect(20, 10, 10, 10,GFX_PIXEL_SET); // Draw a 10x10 filled rectangle at x=10,y=10 gfx_mono_draw_filled_rect(10, 10, 10, 10, GFX_PIXEL_SET); // Draw a whole circle at x=50,y=16 with radios=8 and all octants drawn gfx_mono_draw_circle(50, 16, 8, GFX_PIXEL_SET,GFX_WHOLE); // Draw a filled circle with all quadrant drawn gfx_mono_draw_filled_circle(80, 16, 10, GFX_PIXEL_SET, GFX_WHOLE); while(true) { // This while left intentionally blank to halt execution. } }
zhangjunfang/jstorm-0.9.6.3-
jstorm-client/src/main/java/backtype/storm/scheduler/SupervisorDetails.java
<reponame>zhangjunfang/jstorm-0.9.6.3- package backtype.storm.scheduler; import java.util.Collection; import java.util.HashSet; import java.util.Set; @SuppressWarnings({"unchecked","rawtypes"}) public class SupervisorDetails { String id; /** * hostname of this supervisor */ String host; Object meta; /** * meta data configured for this supervisor */ Object schedulerMeta; /** * all the ports of the supervisor */ Set<Integer> allPorts; public SupervisorDetails(String id, Object meta) { this.id = id; this.meta = meta; allPorts = new HashSet(); } public SupervisorDetails(String id, Object meta, Collection<Number> allPorts) { this.id = id; this.meta = meta; setAllPorts(allPorts); } public SupervisorDetails(String id, String host, Object schedulerMeta, Collection<Number> allPorts) { this.id = id; this.host = host; this.schedulerMeta = schedulerMeta; setAllPorts(allPorts); } private void setAllPorts(Collection<Number> allPorts) { this.allPorts = new HashSet<Integer>(); if (allPorts != null) { for (Number n : allPorts) { this.allPorts.add(n.intValue()); } } } public String getId() { return id; } public String getHost() { return host; } public Object getMeta() { return meta; } public Set<Integer> getAllPorts() { return allPorts; } public Object getSchedulerMeta() { return this.schedulerMeta; } }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-transcribestreaming/include/aws/transcribestreaming/model/MedicalAlternative.h
<reponame>perfectrecall/aws-sdk-cpp<gh_stars>1-10 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/transcribestreaming/TranscribeStreamingService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/transcribestreaming/model/MedicalItem.h> #include <aws/transcribestreaming/model/MedicalEntity.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace TranscribeStreamingService { namespace Model { /** * <p>A list of possible transcriptions for the audio.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-streaming-2017-10-26/MedicalAlternative">AWS * API Reference</a></p> */ class AWS_TRANSCRIBESTREAMINGSERVICE_API MedicalAlternative { public: MedicalAlternative(); MedicalAlternative(Aws::Utils::Json::JsonView jsonValue); MedicalAlternative& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The text that was transcribed from the audio.</p> */ inline const Aws::String& GetTranscript() const{ return m_transcript; } /** * <p>The text that was transcribed from the audio.</p> */ inline bool TranscriptHasBeenSet() const { return m_transcriptHasBeenSet; } /** * <p>The text that was transcribed from the audio.</p> */ inline void SetTranscript(const Aws::String& value) { m_transcriptHasBeenSet = true; m_transcript = value; } /** * <p>The text that was transcribed from the audio.</p> */ inline void SetTranscript(Aws::String&& value) { m_transcriptHasBeenSet = true; m_transcript = std::move(value); } /** * <p>The text that was transcribed from the audio.</p> */ inline void SetTranscript(const char* value) { m_transcriptHasBeenSet = true; m_transcript.assign(value); } /** * <p>The text that was transcribed from the audio.</p> */ inline MedicalAlternative& WithTranscript(const Aws::String& value) { SetTranscript(value); return *this;} /** * <p>The text that was transcribed from the audio.</p> */ inline MedicalAlternative& WithTranscript(Aws::String&& value) { SetTranscript(std::move(value)); return *this;} /** * <p>The text that was transcribed from the audio.</p> */ inline MedicalAlternative& WithTranscript(const char* value) { SetTranscript(value); return *this;} /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline const Aws::Vector<MedicalItem>& GetItems() const{ return m_items; } /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline bool ItemsHasBeenSet() const { return m_itemsHasBeenSet; } /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline void SetItems(const Aws::Vector<MedicalItem>& value) { m_itemsHasBeenSet = true; m_items = value; } /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline void SetItems(Aws::Vector<MedicalItem>&& value) { m_itemsHasBeenSet = true; m_items = std::move(value); } /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline MedicalAlternative& WithItems(const Aws::Vector<MedicalItem>& value) { SetItems(value); return *this;} /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline MedicalAlternative& WithItems(Aws::Vector<MedicalItem>&& value) { SetItems(std::move(value)); return *this;} /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline MedicalAlternative& AddItems(const MedicalItem& value) { m_itemsHasBeenSet = true; m_items.push_back(value); return *this; } /** * <p>A list of objects that contains words and punctuation marks that represents * one or more interpretations of the input audio.</p> */ inline MedicalAlternative& AddItems(MedicalItem&& value) { m_itemsHasBeenSet = true; m_items.push_back(std::move(value)); return *this; } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline const Aws::Vector<MedicalEntity>& GetEntities() const{ return m_entities; } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline bool EntitiesHasBeenSet() const { return m_entitiesHasBeenSet; } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline void SetEntities(const Aws::Vector<MedicalEntity>& value) { m_entitiesHasBeenSet = true; m_entities = value; } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline void SetEntities(Aws::Vector<MedicalEntity>&& value) { m_entitiesHasBeenSet = true; m_entities = std::move(value); } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline MedicalAlternative& WithEntities(const Aws::Vector<MedicalEntity>& value) { SetEntities(value); return *this;} /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline MedicalAlternative& WithEntities(Aws::Vector<MedicalEntity>&& value) { SetEntities(std::move(value)); return *this;} /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline MedicalAlternative& AddEntities(const MedicalEntity& value) { m_entitiesHasBeenSet = true; m_entities.push_back(value); return *this; } /** * <p>Contains the medical entities identified as personal health information in * the transcription output.</p> */ inline MedicalAlternative& AddEntities(MedicalEntity&& value) { m_entitiesHasBeenSet = true; m_entities.push_back(std::move(value)); return *this; } private: Aws::String m_transcript; bool m_transcriptHasBeenSet; Aws::Vector<MedicalItem> m_items; bool m_itemsHasBeenSet; Aws::Vector<MedicalEntity> m_entities; bool m_entitiesHasBeenSet; }; } // namespace Model } // namespace TranscribeStreamingService } // namespace Aws
Pholisa-Fatyela/Ovex-test-ui
lib/daemons/amqp_daemon.rb
require File.join(ENV.fetch('RAILS_ROOT'), 'config', 'environment') raise "bindings must be provided." if ARGV.size == 0 Rails.logger = logger = Logger.new STDOUT conn = Bunny.new AMQPConfig.connect conn.start ch = conn.create_channel id = $0.split(':')[2] prefetch = AMQPConfig.channel(id)[:prefetch] || 0 ch.prefetch(prefetch) if prefetch > 0 logger.info "Connected to AMQP broker (prefetch: #{prefetch > 0 ? prefetch : 'default'})" terminate = proc do # logger is forbidden in signal handling, just use puts here puts "Terminating threads .." ch.work_pool.kill puts "Stopped." end Signal.trap("INT", &terminate) Signal.trap("TERM", &terminate) workers = [] ARGV.each do |id| worker = AMQPConfig.binding_worker(id) queue = ch.queue *AMQPConfig.binding_queue(id) if args = AMQPConfig.binding_exchange(id) x = ch.send *args case args.first when 'direct' queue.bind x, routing_key: AMQPConfig.routing_key(id) when 'topic' AMQPConfig.topics(id).each do |topic| queue.bind x, routing_key: topic end else queue.bind x end end clean_start = AMQPConfig.data[:binding][id][:clean_start] queue.purge if clean_start # Enable manual acknowledge mode by setting manual_ack: true. queue.subscribe manual_ack: true do |delivery_info, metadata, payload| logger.info "Received: #{payload}" begin # Invoke Worker#process with floating number of arguments. args = [JSON.parse(payload), metadata, delivery_info] arity = worker.method(:process).arity resized_args = arity < 0 ? args : args[0...arity] worker.method(:process).call(*resized_args) # Send confirmation to RabbitMQ that message has been successfully processed. # See http://rubybunny.info/articles/queues.html ch.ack(delivery_info.delivery_tag) rescue Exception => e Kernel.print e.inspect, "\b", e.backtrace.join("\n"), "\n\n" # Ask RabbitMQ to deliver message once again later. # See http://rubybunny.info/articles/queues.html ch.nack(delivery_info.delivery_tag, false, true) end end workers << worker end %w(USR1 USR2).each do |signal| Signal.trap(signal) do puts "#{signal} received." handler = "on_#{signal.downcase}" workers.each {|w| w.send handler if w.respond_to?(handler) } end end ch.work_pool.join
datamolecule/door_mat
lib/door_mat/process/manage_email.rb
<filename>lib/door_mat/process/manage_email.rb<gh_stars>0 module DoorMat module Process class ManageEmail def self.add(email, actor, controller) return false unless email.valid? actor.with_lock do return false unless actor.can_add_email? email email.status = :not_available if DoorMat::Email.count_matching(email.address) > DoorMat::configuration.plausible_deniability_count actor.emails << email DoorMat::ActivityConfirmEmail.for(email, controller) end true end def self.set_primary(encoded_address, actor) actor.with_lock do email = actor.email_from_urlsafe_encoded(encoded_address) return false if email.blank? return true if email.primary? return false unless email.confirmed? actor.emails.primary.each do |e| e.confirmed! end email.primary! end true end end end end
threefoldtech/0-templates
tests/controller/templates_manager/general_temp/zt_client.py
<filename>tests/controller/templates_manager/general_temp/zt_client.py<gh_stars>1-10 from jumpscale import j from zerorobot.service_collection import ServiceNotFoundError from testconfig import config import random class ZT_Client: def __init__(self, parent, local=False): self.zt_template = 'github.com/threefoldtech/0-templates/zerotier_client/0.0.1' self._parent = parent self.logger = self._parent.logger if local: self.robot = self._parent.robot else: self.robot = self._parent.remote_robot self.service_name = self._parent.random_string() self._zt_service = self.robot.services.create(self.zt_template, self.service_name, {'token': config['zt']['zt_client']}) def uninstall(self): return self._zt_service.schedule_action('uninstall').wait(die=True) def token(self): return self._zt_service.schedule_action('token').wait(die=True) def delete(self): return self._zt_service.schedule_action('delete').wait(die=True)
edwardstudy/eirini
models.go
package eirini import ( "context" "fmt" "code.cloudfoundry.org/bbs/models" "code.cloudfoundry.org/eirini/models/cf" "code.cloudfoundry.org/eirini/opi" ) const ( //Environment Variable Names EnvDownloadURL = "DOWNLOAD_URL" EnvBuildpacks = "BUILDPACKS" EnvDropletUploadURL = "DROPLET_UPLOAD_URL" EnvAppID = "APP_ID" EnvStagingGUID = "STAGING_GUID" EnvCompletionCallback = "COMPLETION_CALLBACK" EnvCfUsername = "CF_USERNAME" EnvCfPassword = "<PASSWORD>" EnvAPIAddress = "API_ADDRESS" EnvEiriniAddress = "EIRINI_ADDRESS" RegisteredRoutes = "routes" CCUploaderInternalURL = "cc-uploader.service.cf.internal" CCCertsMountPath = "/etc/config/certs" CCCertsVolumeName = "cc-certs-volume" CCAPICertName = "cc-server-crt" CCAPIKeyName = "cc-server-crt-key" CCUploaderCertName = "cc-uploader-crt" CCUploaderKeyName = "cc-uploader-crt-key" CCInternalCACertName = "internal-ca-cert" ) type Config struct { Properties Properties `yaml:"opi"` } type Properties struct { KubeNamespace string `yaml:"kube_namespace"` NatsPassword string `yaml:"nats_password"` NatsIP string `yaml:"nats_ip"` CcUploaderIP string `yaml:"cc_uploader_ip"` CcInternalAPI string `yaml:"cc_internal_api"` CCCertsSecretName string `yaml:"cc_certs_secret_name"` RegistryAddress string `yaml:"registry_address"` EiriniAddress string `yaml:"eirini_address"` StagerImage string `yaml:"stager_image"` MetricsSourceAddress string `yaml:"metrics_source_address"` LoggregatorAddress string `yaml:"loggregator_address"` LoggregatorCertPath string `yaml:"loggergator_cert_path"` LoggregatorKeyPath string `yaml:"loggregator_key_path"` LoggregatorCAPath string `yaml:"loggregator_ca_path"` CCCertPath string `yaml:"cc_cert_path"` CCKeyPath string `yaml:"cc_key_path"` CCCAPath string `yaml:"cc_ca_path"` } //go:generate counterfeiter . Stager type Stager interface { Stage(string, cf.StagingRequest) error CompleteStaging(*models.TaskCallbackResponse) error } type StagerConfig struct { EiriniAddress string Image string } //go:generate counterfeiter . Extractor type Extractor interface { Extract(src, targetDir string) error } //go:generate counterfeiter . Bifrost type Bifrost interface { Transfer(ctx context.Context, request cf.DesireLRPRequest) error List(ctx context.Context) ([]*models.DesiredLRPSchedulingInfo, error) Update(ctx context.Context, update cf.UpdateDesiredLRPRequest) error Stop(ctx context.Context, identifier opi.LRPIdentifier) error GetApp(ctx context.Context, identifier opi.LRPIdentifier) *models.DesiredLRP GetInstances(ctx context.Context, identifier opi.LRPIdentifier) ([]*cf.Instance, error) } func GetInternalServiceName(appName string) string { //Prefix service as the appName could start with numerical characters, which is not allowed return fmt.Sprintf("cf-%s", appName) } func GetInternalHeadlessServiceName(appName string) string { //Prefix service as the appName could start with numerical characters, which is not allowed return fmt.Sprintf("cf-%s-headless", appName) }
v-tsun/azure-sdk-for-js
sdk/textanalytics/ai-text-analytics/recordings/node/aad_textanalyticsclient_health/recording_output_has_the_same_order_as_input.js
<reponame>v-tsun/azure-sdk-for-js let nock = require('nock'); module.exports.hash = "cca3d852367a8f22e560c9113bc0d622"; module.exports.testInfo = {"uniqueName":{},"newDate":{}} nock('https://login.microsoftonline.com:443', {"encodedQueryParams":true}) .post('/azure_tenant_id/oauth2/v2.0/token', "response_type=token&grant_type=client_credentials&client_id=azure_client_id&client_secret=azure_client_secret&scope=https%3A%2F%2Fcognitiveservices.azure.com%2F.default") .reply(200, {"token_type":"Bearer","expires_in":86399,"ext_expires_in":86399,"access_token":"access_token"}, [ 'Cache-Control', 'no-store, no-cache', 'Pragma', 'no-cache', 'Content-Type', 'application/json; charset=utf-8', 'Expires', '-1', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains', 'X-Content-Type-Options', 'nosniff', 'P3P', 'CP="DSP CUR OTPi IND OTRi ONL FIN"', 'x-ms-request-id', '88dd8585-66dc-4d0b-ac30-0199ec833b00', 'x-ms-ests-server', '2.1.11251.18 - NCUS ProdSlices', 'Set-Cookie', 'fpc=AgBSweJWyK1CkavnJvVpd5Zz_bg1AQAAAMPeSNcOAAAA; expires=Sat, 19-Dec-2020 21:46:44 GMT; path=/; secure; HttpOnly; SameSite=None', 'Set-Cookie', 'x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly', 'Set-Cookie', 'stsservicecookie=estsfd; path=/; secure; samesite=none; httponly', 'Date', 'Thu, 19 Nov 2020 21:46:44 GMT', 'Content-Length', '1331' ]); nock('https://endpoint', {"encodedQueryParams":true}) .post('/text/analytics/v3.1-preview.3/entities/health/jobs', {"documents":[{"id":"1","text":"one"},{"id":"2","text":"two"},{"id":"3","text":"three"},{"id":"4","text":"four"},{"id":"5","text":"five"}]}) .query(true) .reply(500, {"error":{"code":"InternalServerError","message":"Unable to get resource information."}}, [ 'Content-Length', '89', 'Content-Type', 'application/json', 'apim-request-id', 'a5f5962e-e22c-43f6-9d73-e54feb215132', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload', 'x-content-type-options', 'nosniff', 'Date', 'Thu, 19 Nov 2020 21:46:45 GMT' ]); nock('https://endpoint', {"encodedQueryParams":true}) .post('/text/analytics/v3.1-preview.3/entities/health/jobs', {"documents":[{"id":"1","text":"one"},{"id":"2","text":"two"},{"id":"3","text":"three"},{"id":"4","text":"four"},{"id":"5","text":"five"}]}) .query(true) .reply(500, {"error":{"code":"InternalServerError","message":"Unable to get resource information."}}, [ 'Content-Length', '89', 'Content-Type', 'application/json', 'apim-request-id', 'b9c9c3bf-6e86-4e83-912a-b36ed47c00e8', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload', 'x-content-type-options', 'nosniff', 'Date', 'Thu, 19 Nov 2020 21:46:45 GMT' ]); nock('https://endpoint', {"encodedQueryParams":true}) .post('/text/analytics/v3.1-preview.3/entities/health/jobs', {"documents":[{"id":"0","text":"random text","language":"en"},{"id":"1","text":"random text","language":"en"},{"id":"2","text":"random text","language":"en"},{"id":"3","text":"random text","language":"en"},{"id":"4","text":"random text","language":"en"},{"id":"5","text":"random text","language":"en"},{"id":"6","text":"random text","language":"en"},{"id":"7","text":"random text","language":"en"},{"id":"8","text":"random text","language":"en"},{"id":"9","text":"random text","language":"en"},{"id":"10","text":"random text","language":"en"}]}) .query(true) .reply(500, {"error":{"code":"InternalServerError","message":"Unable to get resource information."}}, [ 'Content-Length', '89', 'Content-Type', 'application/json', 'apim-request-id', '739fd5f0-ba9f-4a42-ac67-a5f35f837a0c', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload', 'x-content-type-options', 'nosniff', 'Date', 'Thu, 19 Nov 2020 21:46:48 GMT' ]); nock('https://login.microsoftonline.com:443', {"encodedQueryParams":true}) .post('/azure_tenant_id/oauth2/v2.0/token', "response_type=token&grant_type=client_credentials&client_id=azure_client_id&client_secret=azure_client_secret&scope=https%3A%2F%2Fcognitiveservices.azure.com%2F.default") .reply(200, {"token_type":"Bearer","expires_in":86399,"ext_expires_in":86399,"access_token":"access_token"}, [ 'Cache-Control', 'no-store, no-cache', 'Pragma', 'no-cache', 'Content-Type', 'application/json; charset=utf-8', 'Expires', '-1', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains', 'X-Content-Type-Options', 'nosniff', 'P3P', 'CP="DSP CUR OTPi IND OTRi ONL FIN"', 'x-ms-request-id', '16fa55cc-8891-4844-bb77-8d30a9eb3900', 'x-ms-ests-server', '2.1.11251.18 - NCUS ProdSlices', 'Set-Cookie', 'fpc=AqGrg6pRqvdOpWpTEBjN32lz_bg1AgAAAKXeSNcOAAAA; expires=Sat, 19-Dec-2020 21:46:49 GMT; path=/; secure; HttpOnly; SameSite=None', 'Set-Cookie', 'x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly', 'Set-Cookie', 'stsservicecookie=estsfd; path=/; secure; samesite=none; httponly', 'Date', 'Thu, 19 Nov 2020 21:46:49 GMT', 'Content-Length', '1331' ]);
lhj502819/Java-Family-Bucket
jdk1.8-source-analysis/test/com/source/cyclicbarrier/TestCyclcBarrier.java
package com.source.cyclicbarrier; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * TODO * * @author lihongjian * @since 2020/5/7 */ public class TestCyclcBarrier { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(2,new Action()); Thread t1 = new Thread(() -> { try { System.out.println("1"); cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } }); Thread t2 = new Thread(() -> { try { System.out.println("2"); cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } }); t1.start(); t2.start(); } } class Action implements Runnable{ @Override public void run() { System.out.println("action ...."); } }
viewdy/phantomjs
src/qt/qtwebkit/Source/WebCore/inspector/InspectorFrontendHost.cpp
<gh_stars>1-10 /* * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2008 <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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. */ #include "config.h" #if ENABLE(INSPECTOR) #include "InspectorFrontendHost.h" #include "ContextMenu.h" #include "ContextMenuItem.h" #include "ContextMenuController.h" #include "ContextMenuProvider.h" #include "DOMFileSystem.h" #include "DOMWrapperWorld.h" #include "Element.h" #include "Frame.h" #include "FrameLoader.h" #include "HitTestResult.h" #include "HTMLFrameOwnerElement.h" #include "InspectorAgent.h" #include "InspectorController.h" #include "InspectorFrontendClient.h" #include "Page.h" #include "Pasteboard.h" #include "ResourceError.h" #include "ResourceRequest.h" #include "ResourceResponse.h" #include "ScriptFunctionCall.h" #include "UserGestureIndicator.h" #include <wtf/StdLibExtras.h> namespace WebCore { #if ENABLE(CONTEXT_MENUS) class FrontendMenuProvider : public ContextMenuProvider { public: static PassRefPtr<FrontendMenuProvider> create(InspectorFrontendHost* frontendHost, ScriptObject frontendApiObject, const Vector<ContextMenuItem>& items) { return adoptRef(new FrontendMenuProvider(frontendHost, frontendApiObject, items)); } void disconnect() { m_frontendApiObject = ScriptObject(); m_frontendHost = 0; } private: FrontendMenuProvider(InspectorFrontendHost* frontendHost, ScriptObject frontendApiObject, const Vector<ContextMenuItem>& items) : m_frontendHost(frontendHost) , m_frontendApiObject(frontendApiObject) , m_items(items) { } virtual ~FrontendMenuProvider() { contextMenuCleared(); } virtual void populateContextMenu(ContextMenu* menu) { for (size_t i = 0; i < m_items.size(); ++i) menu->appendItem(m_items[i]); } virtual void contextMenuItemSelected(ContextMenuItem* item) { if (m_frontendHost) { UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture); int itemNumber = item->action() - ContextMenuItemBaseCustomTag; ScriptFunctionCall function(m_frontendApiObject, "contextMenuItemSelected"); function.appendArgument(itemNumber); function.call(); } } virtual void contextMenuCleared() { if (m_frontendHost) { ScriptFunctionCall function(m_frontendApiObject, "contextMenuCleared"); function.call(); m_frontendHost->m_menuProvider = 0; } m_items.clear(); } InspectorFrontendHost* m_frontendHost; ScriptObject m_frontendApiObject; Vector<ContextMenuItem> m_items; }; #endif InspectorFrontendHost::InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage) : m_client(client) , m_frontendPage(frontendPage) #if ENABLE(CONTEXT_MENUS) , m_menuProvider(0) #endif { } InspectorFrontendHost::~InspectorFrontendHost() { ASSERT(!m_client); } void InspectorFrontendHost::disconnectClient() { m_client = 0; #if ENABLE(CONTEXT_MENUS) if (m_menuProvider) m_menuProvider->disconnect(); #endif m_frontendPage = 0; } void InspectorFrontendHost::loaded() { if (m_client) m_client->frontendLoaded(); } void InspectorFrontendHost::requestSetDockSide(const String& side) { if (!m_client) return; if (side == "undocked") m_client->requestSetDockSide(InspectorFrontendClient::UNDOCKED); else if (side == "right") m_client->requestSetDockSide(InspectorFrontendClient::DOCKED_TO_RIGHT); else if (side == "bottom") m_client->requestSetDockSide(InspectorFrontendClient::DOCKED_TO_BOTTOM); } void InspectorFrontendHost::closeWindow() { if (m_client) { m_client->closeWindow(); disconnectClient(); // Disconnect from client. } } void InspectorFrontendHost::bringToFront() { if (m_client) m_client->bringToFront(); } void InspectorFrontendHost::setZoomFactor(float zoom) { m_frontendPage->mainFrame()->setPageAndTextZoomFactors(zoom, 1); } void InspectorFrontendHost::inspectedURLChanged(const String& newURL) { if (m_client) m_client->inspectedURLChanged(newURL); } void InspectorFrontendHost::setAttachedWindowHeight(unsigned height) { if (m_client) m_client->changeAttachedWindowHeight(height); } void InspectorFrontendHost::setAttachedWindowWidth(unsigned width) { if (m_client) m_client->changeAttachedWindowWidth(width); } void InspectorFrontendHost::setToolbarHeight(unsigned height) { if (m_client) m_client->setToolbarHeight(height); } void InspectorFrontendHost::moveWindowBy(float x, float y) const { if (m_client) m_client->moveWindowBy(x, y); } void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script) { ASSERT(m_frontendPage->inspectorController()); m_frontendPage->inspectorController()->setInjectedScriptForOrigin(origin, script); } String InspectorFrontendHost::localizedStringsURL() { return m_client ? m_client->localizedStringsURL() : ""; } void InspectorFrontendHost::copyText(const String& text) { Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace); } void InspectorFrontendHost::openInNewTab(const String& url) { if (m_client) m_client->openInNewTab(url); } bool InspectorFrontendHost::canSave() { if (m_client) return m_client->canSave(); return false; } void InspectorFrontendHost::save(const String& url, const String& content, bool forceSaveAs) { if (m_client) m_client->save(url, content, forceSaveAs); } void InspectorFrontendHost::append(const String& url, const String& content) { if (m_client) m_client->append(url, content); } void InspectorFrontendHost::close(const String&) { } void InspectorFrontendHost::sendMessageToBackend(const String& message) { if (m_client) m_client->sendMessageToBackend(message); } #if ENABLE(CONTEXT_MENUS) void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items) { if (!event) return; ASSERT(m_frontendPage); ScriptState* frontendScriptState = scriptStateFromPage(debuggerWorld(), m_frontendPage); ScriptObject frontendApiObject; if (!ScriptGlobalObject::get(frontendScriptState, "InspectorFrontendAPI", frontendApiObject)) { ASSERT_NOT_REACHED(); return; } RefPtr<FrontendMenuProvider> menuProvider = FrontendMenuProvider::create(this, frontendApiObject, items); ContextMenuController* menuController = m_frontendPage->contextMenuController(); menuController->showContextMenu(event, menuProvider); m_menuProvider = menuProvider.get(); } #endif String InspectorFrontendHost::loadResourceSynchronously(const String& url) { ResourceRequest request(url); request.setHTTPMethod("GET"); Vector<char> data; ResourceError error; ResourceResponse response; m_frontendPage->mainFrame()->loader()->loadResourceSynchronously(request, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, error, response, data); return String::fromUTF8(data.data(), data.size()); } bool InspectorFrontendHost::supportsFileSystems() { if (m_client) return m_client->supportsFileSystems(); return false; } void InspectorFrontendHost::requestFileSystems() { if (m_client) m_client->requestFileSystems(); } void InspectorFrontendHost::addFileSystem() { if (m_client) m_client->addFileSystem(); } void InspectorFrontendHost::removeFileSystem(const String& fileSystemPath) { if (m_client) m_client->removeFileSystem(fileSystemPath); } #if ENABLE(FILE_SYSTEM) PassRefPtr<DOMFileSystem> InspectorFrontendHost::isolatedFileSystem(const String& fileSystemName, const String& rootURL) { ScriptExecutionContext* context = m_frontendPage->mainFrame()->document(); return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL), AsyncFileSystem::create()); } #endif bool InspectorFrontendHost::isUnderTest() { return m_client && m_client->isUnderTest(); } bool InspectorFrontendHost::canSaveAs() { return false; } bool InspectorFrontendHost::canInspectWorkers() { return false; } } // namespace WebCore #endif // ENABLE(INSPECTOR)
livehybrid/addonfactory-ucc-generator
splunk_add_on_ucc_framework/UCC-UI-lib/style.config.js
var path = require('path'); var buildToolsDir = path.join(__dirname, 'bower_components', 'SplunkWebCore', 'build_tools'); var mergeConfigs = require(buildToolsDir + '/util/mergeConfigs'); var cssConfig = require(buildToolsDir + '/profiles/common/css.config'); module.exports = mergeConfigs(cssConfig('enterprise'), { output: { path: path.join(__dirname, 'build', 'appserver', 'static', 'css') }, entry: { bootstrap: path.join(__dirname, 'build', 'appserver', 'static', 'styles', 'bootstrap.pcss') } });
stkdman/exerciociosCod3r-JS
exercicio29.js
function intervalo10E20 (numeros) { let num = numeros let entre = 0 let fora = 0 for (i = 0 ; i < numeros.length ; i++) { if (numeros[i] >= 10 && numeros[i] <= 20){ entre++ } else { fora++ } } return [entre, fora] } console.log(intervalo10E20([5,4,9,19,14,13,12,17,22,26]))
nmercier/linux-cross-gcc
linux/lib/python2.7/dist-packages/blueman/bluez/Adapter.py
<gh_stars>1-10 from PropertiesBlueZInterface import PropertiesBlueZInterface from errors import raise_dbus_error, parse_dbus_error from Device import Device import dbus class Adapter(PropertiesBlueZInterface): @raise_dbus_error def __init__(self, obj_path=None): if self.__class__.get_interface_version()[0] < 5: interface = 'org.bluez.Adapter' else: interface = 'org.bluez.Adapter1' proxy = dbus.SystemBus().get_object('org.bluez', '/', follow_name_owner_changes=True) self.manager_interface = dbus.Interface(proxy, 'org.freedesktop.DBus.ObjectManager') super(Adapter, self).__init__(interface, obj_path) @raise_dbus_error def find_device(self, address): devices = self.list_devices() for device in devices: if device.get_properties()['Address'] == address: return device @raise_dbus_error def list_devices(self): if self.__class__.get_interface_version()[0] < 5: devices = self.get_interface().ListDevices() return [Device(device) for device in devices] else: objects = self.manager_interface.GetManagedObjects() devices = [] for path, interfaces in objects.items(): if 'org.bluez.Device1' in interfaces: devices.append(path) return [Device(device) for device in devices] @raise_dbus_error def create_paired_device(self, address, agent_path, capability, error_handler=None, reply_handler=None, timeout=120): # BlueZ 4 only! def reply_handler_wrapper(obj_path): if not callable(reply_handler): return reply_handler(Device(obj_path)) def error_handler_wrapper(exception): exception = parse_dbus_error(exception) if not callable(error_handler): raise exception error_handler(exception) if reply_handler is None and error_handler is None: obj_path = self.get_interface().CreatePairedDevice(address, agent_path, capability) return Device(obj_path) else: self.get_interface().CreatePairedDevice(address, agent_path, capability, reply_handler=reply_handler_wrapper, error_handler=error_handler_wrapper, timeout=timeout) @raise_dbus_error def create_device(self, address, reply_handler=None, error_handler=None): # BlueZ 4 only! def reply_handler_wrapper(path): if not callable(reply_handler): return reply_handler(Device(path)) def error_handler_wrapper(exception): exception = parse_dbus_error(exception) if not callable(error_handler): raise exception error_handler(exception) if reply_handler is None and error_handler is None: obj_path = self.get_interface().CreateDevice(address) return Device(obj_path) else: self.get_interface().CreateDevice( address, reply_handler=reply_handler_wrapper, error_handler=error_handler_wrapper ) return None @raise_dbus_error def handle_signal(self, handler, signal, **kwargs): if signal in ['DeviceCreated', 'DeviceRemoved', 'DeviceFound']: if self.__class__.get_interface_version()[0] < 5: self._handle_signal(handler, signal, self.get_interface_name(), self.get_object_path(), **kwargs) else: if signal == 'DeviceFound': return def wrapper(object_path, interfaces): if 'org.bluez.Device1' in interfaces: handler(object_path) self._handler_wrappers[handler] = wrapper signal = { 'DeviceCreated': 'InterfacesAdded', 'DeviceRemoved': 'InterfacesRemoved' }[signal] self._handle_signal(wrapper, signal, 'org.freedesktop.DBus.ObjectManager', '/', **kwargs) else: super(Adapter, self).handle_signal(handler, signal, **kwargs) @raise_dbus_error def unhandle_signal(self, handler, signal, **kwargs): if signal in ['DeviceCreated', 'DeviceRemoved', 'DeviceFound']: if self.__class__.get_interface_version()[0] < 5: self._unhandle_signal(handler, signal, self.get_interface_name(), self.get_object_path(), **kwargs) else: if signal == 'DeviceFound': return signal = { 'DeviceCreated': 'InterfacesAdded', 'DeviceRemoved': 'InterfacesRemoved' }[signal] self._unhandle_signal(self._handler_wrappers[handler], signal, self.get_interface_name(), self.get_object_path(), **kwargs) else: super(Adapter, self).unhandle_signal(handler, signal, **kwargs) @raise_dbus_error def start_discovery(self): self.get_interface().StartDiscovery() @raise_dbus_error def stop_discovery(self): self.get_interface().StopDiscovery() @raise_dbus_error def remove_device(self, device): self.get_interface().RemoveDevice(device.get_object_path()) @raise_dbus_error def register_agent(self, agent, capability=''): # BlueZ 4 only! self.get_interface().RegisterAgent(agent.get_object_path(), capability) @raise_dbus_error def unregister_agent(self, agent): # BlueZ 4 only! self.get_interface().UnregisterAgent(agent.get_object_path())
so3500/problem-solving
src/main/java/programmers/CodingB.java
/* * 1부터 n까지 번호가 붙어있는 n명의 사람이 영어 끝말잇기를 하고 있습니다. 영어 끝말잇기는 다음과 같은 규칙으로 진행됩니다. 1번부터 번호 순서대로 한 사람씩 차례대로 단어를 말합니다. 마지막 사람이 단어를 말한 다음에는 다시 1번부터 시작합니다. 앞사람이 말한 단어의 마지막 문자로 시작하는 단어를 말해야 합니다. 이전에 등장했던 단어는 사용할 수 없습니다. 한 글자인 단어는 인정되지 않습니다. 다음은 3명이 끝말잇기를 하는 상황을 나타냅니다. tank → kick → know → wheel → land → dream → mother → robot → tank 위 끝말잇기는 다음과 같이 진행됩니다. 1번 사람이 자신의 첫 번째 차례에 tank를 말합니다. 2번 사람이 자신의 첫 번째 차례에 kick을 말합니다. 3번 사람이 자신의 첫 번째 차례에 know를 말합니다. 1번 사람이 자신의 두 번째 차례에 wheel을 말합니다. (계속 진행) 끝말잇기를 계속 진행해 나가다 보면, 3번 사람이 자신의 세 번째 차례에 말한 tank 라는 단어는 이전에 등장했던 단어이므로 탈락하게 됩니다. 사람의 수 n과 사람들이 순서대로 말한 단어 words 가 매개변수로 주어질 때, 가장 먼저 탈락하는 사람의 번호와 그 사람이 자신의 몇 번째 차례에 탈락하는지를 구해서 return 하도록 solution 함수를 완성해주세요. 제한 사항 끝말잇기에 참여하는 사람의 수 n은 2 이상 10 이하의 자연수입니다. words는 끝말잇기에 사용한 단어들이 순서대로 들어있는 배열이며, 길이는 n 이상 100 이하입니다. 단어의 길이는 2 이상 50 이하입니다. 모든 단어는 알파벳 소문자로만 이루어져 있습니다. 끝말잇기에 사용되는 단어의 뜻(의미)은 신경 쓰지 않으셔도 됩니다. 정답은 [ 번호, 차례 ] 형태로 return 해주세요. 만약 주어진 단어들로 탈락자가 생기지 않는다면, [0, 0]을 return 해주세요. 입출력 예 n words result 3 [tank, kick, know, wheel, land, dream, mother, robot, tank] [3,3] 5 [hello, observe, effect, take, either, recognize, encourage, ensure, establish, hang, gather, refer, reference, estimate, executive] [0,0] 2 [hello, one, even, never, now, world, draw] [1,3] 입출력 예 설명 입출력 예 #1 3명의 사람이 끝말잇기에 참여하고 있습니다. 1번 사람 : tank, wheel, mother 2번 사람 : kick, land, robot 3번 사람 : know, dream, tank 와 같은 순서로 말을 하게 되며, 3번 사람이 자신의 세 번째 차례에 말한 tank라는 단어가 1번 사람이 자신의 첫 번째 차례에 말한 tank와 같으므로 3번 사람이 자신의 세 번째 차례로 말을 할 때 처음 탈락자가 나오게 됩니다. 입출력 예 #2 5명의 사람이 끝말잇기에 참여하고 있습니다. 1번 사람 : hello, recognize, gather 2번 사람 : observe, encourage, refer 3번 사람 : effect, ensure, reference 4번 사람 : take, establish, estimate 5번 사람 : either, hang, executive 와 같은 순서로 말을 하게 되며, 이 경우는 주어진 단어로만으로는 탈락자가 발생하지 않습니다. 따라서 [0, 0]을 return하면 됩니다. 입출력 예 #3 2명의 사람이 끝말잇기에 참여하고 있습니다. 1번 사람 : hello, even, now, draw 2번 사람 : one, never, world 와 같은 순서로 말을 하게 되며, 1번 사람이 자신의 세 번째 차례에 'r'로 시작하는 단어 대신, n으로 시작하는 now를 말했기 때문에 이때 처음 탈락자가 나오게 됩니다. * * */ package programmers; import java.util.HashSet; public class CodingB { public static void main(String[] args) { // TODO Auto-generated method stub String[] input = {"hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"}; String[] input2 = {"tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"}; String[] input3 = {"hello", "one", "even", "never", "now", "world", "draw"}; solution(5, input); solution(3, input2); solution(2, input3); } public static int[] solution(int n, String[] words) { int[] answer = {0, 0}; int people, cnt, idx; String before, next; HashSet<String> set = new HashSet<>(); set.add(words[0]); before = words[0]; people = 1; cnt = 1; for (idx = 1; idx < words.length; idx++) { next = words[idx]; people++; if (set.contains(next) || before.charAt(before.length() - 1) != next.charAt(0)) { answer[0] = people; answer[1] = cnt; break; } if (people == n) { people = 0; cnt++; } set.add(next); before = next; } return answer; } }
WolffunGame/go-sdk
pkg/decision/evaluator/matchers/semver_test.go
/**************************************************************************** * Copyright 2020-2021, Optimizely, Inc. and contributors * * * * 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 matchers import ( "testing" "github.com/stretchr/testify/assert" "github.com/WolffunGame/experiment/pkg/entities" ) func TestValidAttributes(t *testing.T) { scenarios := []struct { matchType string version string expected bool }{ {matchType: "semver_eq", version: "2", expected: false}, {matchType: "semver_eq", version: "2.0.0", expected: true}, {matchType: "semver_eq", version: "2.9", expected: false}, {matchType: "semver_eq", version: "1.9", expected: false}, {matchType: "semver_ge", version: "2.0.0", expected: true}, {matchType: "semver_ge", version: "2.9", expected: true}, {matchType: "semver_ge", version: "1.9", expected: false}, {matchType: "semver_gt", version: "2.0.0", expected: false}, {matchType: "semver_gt", version: "2.9", expected: true}, {matchType: "semver_gt", version: "1.9", expected: false}, {matchType: "semver_le", version: "2.0.0", expected: true}, {matchType: "semver_le", version: "2.9", expected: false}, {matchType: "semver_le", version: "1.9", expected: true}, {matchType: "semver_lt", version: "2.0.0", expected: false}, {matchType: "semver_lt", version: "2.9", expected: false}, {matchType: "semver_lt", version: "1.9", expected: true}, } for _, scenario := range scenarios { condition := entities.Condition{ Match: scenario.matchType, Value: "2.0", Name: "version", } user := entities.UserContext{ Attributes: map[string]interface{}{ "version": scenario.version, }, } messageAndArgs := []interface{}{"matchType: %s, condition: %s, attribute: %s", scenario.matchType, condition.Value, scenario.version} matcher, ok := Get(scenario.matchType) assert.True(t, ok, messageAndArgs...) actual, err := matcher(condition, user, nil) assert.NoError(t, err, messageAndArgs...) assert.Equal(t, scenario.expected, actual, messageAndArgs...) } } func TestValidAttributesReleaseToBeta(t *testing.T) { scenarios := []struct { matchType string version string expected bool }{ {matchType: "semver_eq", version: "2.1.2-release", expected: false}, {matchType: "semver_eq", version: "2.1.2", expected: false}, {matchType: "semver_eq", version: "2.1.2-beta", expected: true}, {matchType: "semver_ge", version: "2.1.2-release", expected: true}, {matchType: "semver_ge", version: "2.1.2", expected: false}, {matchType: "semver_ge", version: "2.1.2-beta", expected: true}, {matchType: "semver_gt", version: "2.1.2-release", expected: true}, {matchType: "semver_gt", version: "2.1.2", expected: false}, {matchType: "semver_gt", version: "2.1.2-beta", expected: false}, {matchType: "semver_le", version: "2.1.2-release", expected: false}, {matchType: "semver_le", version: "2.1.2", expected: true}, {matchType: "semver_le", version: "2.1.2-beta", expected: true}, {matchType: "semver_lt", version: "2.1.2-release", expected: false}, {matchType: "semver_lt", version: "2.1.2", expected: true}, {matchType: "semver_lt", version: "2.1.2-beta", expected: false}, } for _, scenario := range scenarios { condition := entities.Condition{ Match: scenario.matchType, Value: "2.1.2-beta", Name: "version", } user := entities.UserContext{ Attributes: map[string]interface{}{ "version": scenario.version, }, } messageAndArgs := []interface{}{"matchType: %s, condition: %s, attribute: %s", scenario.matchType, condition.Value, scenario.version} matcher, ok := Get(scenario.matchType) assert.True(t, ok, messageAndArgs...) actual, err := matcher(condition, user, nil) assert.NoError(t, err, messageAndArgs...) assert.Equal(t, scenario.expected, actual, messageAndArgs...) } } func TestValidAttributesBetaToRelease(t *testing.T) { scenarios := []struct { matchType string version string expected bool }{ {matchType: "semver_eq", version: "2.1.2-beta", expected: false}, {matchType: "semver_eq", version: "2.1.2", expected: false}, {matchType: "semver_eq", version: "2.1.2-release", expected: true}, {matchType: "semver_ge", version: "2.1.2-beta", expected: false}, {matchType: "semver_ge", version: "2.1.2", expected: false}, {matchType: "semver_ge", version: "2.1.2-release", expected: true}, {matchType: "semver_gt", version: "2.1.2-beta", expected: false}, {matchType: "semver_gt", version: "2.1.2", expected: false}, {matchType: "semver_gt", version: "2.1.2-release", expected: false}, {matchType: "semver_le", version: "2.1.2-beta", expected: true}, {matchType: "semver_le", version: "2.1.2", expected: true}, {matchType: "semver_le", version: "2.1.2-release", expected: true}, {matchType: "semver_lt", version: "2.1.2-beta", expected: true}, {matchType: "semver_lt", version: "2.1.2", expected: true}, {matchType: "semver_lt", version: "2.1.2-release", expected: false}, } for _, scenario := range scenarios { condition := entities.Condition{ Match: scenario.matchType, Value: "2.1.2-release", Name: "version", } user := entities.UserContext{ Attributes: map[string]interface{}{ "version": scenario.version, }, } messageAndArgs := []interface{}{"matchType: %s, condition: %s, attribute: %s", scenario.matchType, condition.Value, scenario.version} matcher, ok := Get(scenario.matchType) assert.True(t, ok, messageAndArgs...) actual, err := matcher(condition, user, nil) assert.NoError(t, err, messageAndArgs...) assert.Equal(t, scenario.expected, actual, messageAndArgs...) } } func TestTargetBetaAndBetaComplex(t *testing.T) { testValues := []string{"2.1.3-beta+1", "2.1.3+build-1.2.3"} scenarios := []struct { matchType string version string expected bool }{ {matchType: "semver_eq", version: "2.1.3-beta+1.2.3", expected: false}, {matchType: "semver_eq", version: "2.1.3+build-1", expected: false}, {matchType: "semver_ge", version: "2.1.3-beta+1.2.3", expected: true}, {matchType: "semver_ge", version: "2.1.3+build-1", expected: false}, {matchType: "semver_gt", version: "2.1.3-beta+1.2.3", expected: true}, {matchType: "semver_gt", version: "2.1.3+build-1", expected: false}, {matchType: "semver_le", version: "2.1.3-beta+1.2.3", expected: false}, {matchType: "semver_le", version: "2.1.3+build-1", expected: true}, {matchType: "semver_lt", version: "2.1.3-beta+1.2.3", expected: false}, {matchType: "semver_lt", version: "2.1.3+build-1", expected: true}, } for index, scenario := range scenarios { condition := entities.Condition{ Match: scenario.matchType, Value: testValues[index%len(testValues)], Name: "version", } user := entities.UserContext{ Attributes: map[string]interface{}{ "version": scenario.version, }, } messageAndArgs := []interface{}{"matchType: %s, condition: %s, attribute: %s", scenario.matchType, condition.Value, scenario.version} matcher, ok := Get(scenario.matchType) assert.True(t, ok, messageAndArgs...) actual, err := matcher(condition, user, nil) assert.NoError(t, err, messageAndArgs...) assert.Equal(t, scenario.expected, actual, messageAndArgs...) } } func TestDifferentAttributeAgainstBuildAndPrerelease(t *testing.T) { testValues := []string{"3.7.0", "3.7.0", "3.7.0-prerelease", "3.7.0-prerelease+build"} scenarios := []struct { matchType string version string expected bool }{ {matchType: "semver_eq", version: "3.7.0+build", expected: true}, {matchType: "semver_eq", version: "3.7.0-prerelease", expected: false}, {matchType: "semver_eq", version: "3.7.0+build", expected: false}, {matchType: "semver_eq", version: "3.7.0-prerelease-prelrease+rc", expected: false}, {matchType: "semver_ge", version: "3.7.0+build", expected: true}, {matchType: "semver_ge", version: "3.7.0-prerelease", expected: false}, {matchType: "semver_ge", version: "3.7.0+build", expected: true}, {matchType: "semver_ge", version: "3.7.0-prerelease-prelrease+rc", expected: true}, {matchType: "semver_gt", version: "3.7.0+build", expected: false}, {matchType: "semver_gt", version: "3.7.0-prerelease", expected: false}, {matchType: "semver_gt", version: "3.7.0+build", expected: true}, {matchType: "semver_gt", version: "3.7.0-prerelease-prelrease+rc", expected: true}, {matchType: "semver_le", version: "3.7.0+build", expected: true}, {matchType: "semver_le", version: "3.7.0-prerelease", expected: true}, {matchType: "semver_le", version: "3.7.0+build", expected: false}, {matchType: "semver_le", version: "3.7.0-prerelease-prelrease+rc", expected: false}, {matchType: "semver_lt", version: "3.7.0+build", expected: false}, {matchType: "semver_lt", version: "3.7.0-prerelease", expected: true}, {matchType: "semver_lt", version: "3.7.0+build", expected: false}, {matchType: "semver_lt", version: "3.7.0-prerelease-prelrease+rc", expected: false}, } for index, scenario := range scenarios { condition := entities.Condition{ Match: scenario.matchType, Value: testValues[index%len(testValues)], Name: "version", } user := entities.UserContext{ Attributes: map[string]interface{}{ "version": scenario.version, }, } messageAndArgs := []interface{}{"matchType: %s, condition: %s, attribute: %s", scenario.matchType, condition.Value, scenario.version} matcher, ok := Get(scenario.matchType) assert.True(t, ok, messageAndArgs...) actual, err := matcher(condition, user, nil) assert.NoError(t, err, messageAndArgs...) assert.Equal(t, scenario.expected, actual, messageAndArgs...) } } func TestInvalidAttributes(t *testing.T) { condition := entities.Condition{ Match: "semver_eq", Value: "2.0", Name: "version", } matchTypes := []string{ "semver_eq", "semver_ge", "semver_gt", "semver_le", "semver_lt", } invalidAttributes := []interface{}{ true, 37, nil, "-", ".", "..", "+", "+test", " ", "2 .3. 0", "2.", ".2.2", "3.7.2.2", "3.x", ",", "+build-prerelese", } for _, matchType := range matchTypes { matcher, ok := Get(matchType) assert.True(t, ok) for _, attribute := range invalidAttributes { user := entities.UserContext{ Attributes: map[string]interface{}{ "version": attribute, }, } _, err := matcher(condition, user, nil) assert.Error(t, err, "matchType: %s, value: %v", matchType, attribute) } } } func TestInvalidConditions(t *testing.T) { conditions := []entities.Condition{{ Match: "semver_eq", Value: "", Name: "version", }, { Match: "semver_eq", Value: nil, Name: "version", }, } for _, condition := range conditions { matcher, ok := Get("semver_eq") assert.True(t, ok) user := entities.UserContext{ Attributes: map[string]interface{}{ "version": "12.2.3", }, } _, err := matcher(condition, user, nil) assert.Error(t, err, "matchType: semver_eq, value: 12.2.3") } }
andbi/evrete
evrete-dsl-java/src/main/java/org/evrete/dsl/ClassMethod.java
<filename>evrete-dsl-java/src/main/java/org/evrete/dsl/ClassMethod.java package org.evrete.dsl; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.function.Function; class ClassMethod { final boolean staticMethod; private final MethodHandle handle; final Object[] args; ClassMethod(MethodHandles.Lookup lookup, Method method) { this.staticMethod = Modifier.isStatic(method.getModifiers()); try { this.handle = lookup.unreflect(method); } catch (IllegalAccessException e) { throw new MalformedResourceException("Rule method access exception", e); } this.args = new Object[handle.type().parameterCount()]; } private ClassMethod(boolean staticMethod, MethodHandle handle) { this.staticMethod = staticMethod; this.handle = handle; this.args = new Object[handle.type().parameterCount()]; } ClassMethod(ClassMethod method, Object instance) { this.staticMethod = method.staticMethod; this.handle = staticMethod ? method.handle : method.handle.bindTo(instance); this.args = new Object[this.handle.type().parameterCount()]; } ClassMethod(ClassMethod other) { this.staticMethod = other.staticMethod; this.handle = other.handle; this.args = other.args.clone(); } static ClassMethod lookup(MethodHandles.Lookup lookup, String name, MethodType methodType) { MethodHandle handle; boolean staticMethod; Class<?> javaClass = lookup.lookupClass(); try { handle = lookup.findStatic(javaClass, name, methodType); staticMethod = true; } catch (NoSuchMethodException | IllegalAccessException e1) { try { handle = lookup.findVirtual(javaClass, name, methodType); staticMethod = false; } catch (NoSuchMethodException | IllegalAccessException e2) { throw new MalformedResourceException("Unable to find/access method '" + name + "' in " + javaClass + " of type " + methodType); } } return new ClassMethod(staticMethod, handle); } @SuppressWarnings("unchecked") final <T> T call() { try { return (T) handle.invokeWithArguments(args); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } final <V, R> Function<V, R> asFunction() { assert args.length == 1; return new Function<V, R>() { @Override public R apply(V v) { args[0] = v; return call(); } @Override public String toString() { return handle.toString(); } }; } }
lollito/fm
src/main/java/com/lollito/fm/config/security/JwtUtil.java
package com.lollito.fm.config.security; import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.lollito.fm.model.User; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JwtUtil { @Value("${security.jwt.header}") private String header; @Value("${security.jwt.prefix}") private String prefix; @Value("${security.jwt.expiration}") private Integer expiration; @Value("${security.jwt.secret}") private String secret; public Claims parseToken(String token) { return Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } public String generateToken(User user) { Long now = System.currentTimeMillis(); Claims claims = Jwts.claims() // TODO check id/username .setSubject(user.getId().toString()) .setIssuedAt( new Date (now) ) .setExpiration( new Date( now + expiration * 1000) ); claims.put("userId", user.getId() ); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public Integer getExpiration() { return expiration; } public void setExpiration(Integer expiration) { this.expiration = expiration; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } }
allansrc/fuchsia
src/firmware/gigaboot/include/stdio.h
<reponame>allansrc/fuchsia<gh_stars>100-1000 // Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_FIRMWARE_GIGABOOT_INCLUDE_STDIO_H_ #define SRC_FIRMWARE_GIGABOOT_INCLUDE_STDIO_H_ #ifndef NULL #define NULL ((void*)0) #endif #include <printf.h> #include <stddef.h> #include <stdint.h> int puts16(char16_t* str); #endif // SRC_FIRMWARE_GIGABOOT_INCLUDE_STDIO_H_
wonderzdh/zydis
include/Zydis/CommonTypes.h
<filename>include/Zydis/CommonTypes.h /*************************************************************************************************** Zyan Disassembler Library (Zydis) Original Author : <NAME>, <NAME> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ***************************************************************************************************/ /** * @file * @brief Includes and defines some default datatypes. */ #ifndef ZYDIS_COMMONTYPES_H #define ZYDIS_COMMONTYPES_H #include "Zydis/Defines.h" /* ============================================================================================== */ /* Integer types */ /* ============================================================================================== */ #if !defined(ZYDIS_NO_LIBC) // If is LibC present, we use stdint types. # include <stdint.h> # include <stddef.h> typedef uint8_t ZydisU8; typedef uint16_t ZydisU16; typedef uint32_t ZydisU32; typedef uint64_t ZydisU64; typedef int8_t ZydisI8; typedef int16_t ZydisI16; typedef int32_t ZydisI32; typedef int64_t ZydisI64; typedef size_t ZydisUSize; typedef ptrdiff_t ZydisISize; typedef uintptr_t ZydisUPointer; typedef intptr_t ZydisIPointer; #else // No LibC, use compiler built-in types / macros. # if defined(ZYDIS_MSVC) typedef unsigned __int8 ZydisU8; typedef unsigned __int16 ZydisU16; typedef unsigned __int32 ZydisU32; typedef unsigned __int64 ZydisU64; typedef signed __int8 ZydisI8; typedef signed __int16 ZydisI16; typedef signed __int32 ZydisI32; typedef signed __int64 ZydisI64; # if _WIN64 typedef ZydisU64 ZydisUSize; typedef ZydisI64 ZydisISize; typedef ZydisU64 ZydisUPointer; typedef ZydisI64 ZydisIPointer; # else typedef ZydisU32 ZydisUSize; typedef ZydisI32 ZydisISize; typedef ZydisU32 ZydisUPointer; typedef ZydisI32 ZydisIPointer; # endif # elif defined(ZYDIS_GNUC) typedef __UINT8_TYPE__ ZydisU8; typedef __UINT16_TYPE__ ZydisU16; typedef __UINT32_TYPE__ ZydisU32; typedef __UINT64_TYPE__ ZydisU64; typedef __INT8_TYPE__ ZydisI8; typedef __INT16_TYPE__ ZydisI16; typedef __INT32_TYPE__ ZydisI32; typedef __INT64_TYPE__ ZydisI64; typedef __SIZE_TYPE__ ZydisUSize; typedef __PTRDIFF_TYPE__ ZydisISize; typedef __UINTPTR_TYPE__ ZydisUPointer; typedef __INTPTR_TYPE__ ZydisIPointer; # else # error "Unsupported compiler for no-libc mode." # endif #endif // Verify size assumptions. ZYDIS_STATIC_ASSERT(sizeof(ZydisU8 ) == 1 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisU16 ) == 2 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisU32 ) == 4 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisU64 ) == 8 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisI8 ) == 1 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisI16 ) == 2 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisI32 ) == 4 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisI64 ) == 8 ); ZYDIS_STATIC_ASSERT(sizeof(ZydisUSize ) == sizeof(void*)); // TODO: This one is incorrect! ZYDIS_STATIC_ASSERT(sizeof(ZydisISize ) == sizeof(void*)); // TODO: This one is incorrect! ZYDIS_STATIC_ASSERT(sizeof(ZydisUPointer) == sizeof(void*)); ZYDIS_STATIC_ASSERT(sizeof(ZydisIPointer) == sizeof(void*)); // Verify signedness assumptions (relies on size checks above). ZYDIS_STATIC_ASSERT((ZydisI8 )-1 >> 1 < (ZydisI8 )((ZydisU8 )-1 >> 1)); ZYDIS_STATIC_ASSERT((ZydisI16)-1 >> 1 < (ZydisI16)((ZydisU16)-1 >> 1)); ZYDIS_STATIC_ASSERT((ZydisI32)-1 >> 1 < (ZydisI32)((ZydisU32)-1 >> 1)); ZYDIS_STATIC_ASSERT((ZydisI64)-1 >> 1 < (ZydisI64)((ZydisU64)-1 >> 1)); /* ============================================================================================== */ /* NULL */ /* ============================================================================================== */ #define ZYDIS_NULL ((void*)0) /* ============================================================================================== */ /* Boolean */ /* ============================================================================================== */ #define ZYDIS_FALSE 0 #define ZYDIS_TRUE 1 /** * @briefs Defines the @c ZydisBool datatype. */ typedef ZydisU8 ZydisBool; /* ============================================================================================== */ #endif /* ZYDIS_COMMONTYPES_H */
hipstersmoothie/parse-commit-message
src/main.js
<filename>src/main.js import { tryCatch, isObject } from './utils'; import { parseCommit, stringifyCommit, checkCommit } from './commit'; /** * Receives and parses a single or multiple commit message(s) in form of string, * object, array of strings, array of objects or mixed. * * @example * import { parse } from 'parse-commit-message'; * * const commits = [ * 'fix(ci): tweaks for @circleci config', * 'chore: bar qux' * ]; * const result = parse(commits); * console.log(result); * // => [{ * // header: { type: 'fix', scope: 'ci', subject: 'tweaks for @circleci config' }, * // body: null, * // footer: null, * // }, { * // header: { type: 'chore', scope: null, subject: 'bar qux' }, * // body: null, * // footer: null, * // }] * * // Or pass `flat = true` to return a single object * // when results contain only one item. * const commitMessage = `feat: awesome yeah * * Awesome body! * resolves #123 * * Signed-off-by: <NAME> <<EMAIL>>`; * * const res = parse(commitMessage, true); * * console.log(res); * // => { * // header: { type: 'feat', scope: null, subject: 'awesome yeah' }, * // body: 'Awesome body!\nresolves #123', * // footer: 'Signed-off-by: <NAME> <<EMAIL>>', * // } * * @name .parse * @param {string|object|array} commits a value to be parsed into an object like `Commit` type * @param {boolean} [flat] if the returned result length is 1, then returns the first item * @returns {Array<Commit>} if `flat: true`, returns a `Commit` * @public */ export function parse(commits, flat = false) { const result = [] .concat(commits) .filter(Boolean) .reduce((acc, val) => { if (typeof val === 'string') { return acc.concat(parseCommit(val)); } if (isObject(val)) { return acc.concat(val); } return acc.concat(parse(val)); }, []); return flat === true && result.length === 1 ? result[0] : result; } /** * Receives a `Commit` object, validates it using `validate`, * builds a "commit" message string and returns it. * * This method does checking and validation too, * so if you pass a string, it will be parsed and validated, * and after that turned again to string. * * @example * import { parse, stringify } from 'parse-commit-message'; * * const commitMessage = `feat: awesome yeah * * Awesome body! * resolves #123 * * Signed-off-by: <NAME> <<EMAIL>>`; * * const flat = true; * const res = parse(commitMessage, flat); * * const str = stringify(res, flat); * console.log(str); * console.log(str === commitMessage); * * @name .stringify * @param {string|object|array} commits a `Commit` object, or anything that can be passed to `check` * @param {boolean} [flat] if the returned result length is 1, then returns the first item * @returns {Array<string>} an array of commit strings like `'fix(foo): bar baz'`, * if `flat: true`, returns a `string` * @public */ export function stringify(commits, flat = false) { const result = [] .concat(commits) .filter(Boolean) .reduce( (acc, val) => acc.concat(check(val).map((x) => stringifyCommit(x))), [], ); return flat === true && result.length === 1 ? result[0] : result; } /** * Validates a single or multiple commit message(s) in form of string, * object, array of strings, array of objects or mixed. * You may want to pass `ret` to return an object instead of throwing. * * @example * import { validate } from 'parse-commit-message'; * * console.log(validate('foo bar qux')); // false * console.log(validate('foo: bar qux')); // true * console.log(validate('fix(ci): bar qux')); // true * * console.log(validate(['a bc cqux', 'foo bar qux'])); // false * * console.log(validate({ qux: 1 })); // false * console.log(validate({ header: { type: 'fix' } })); // false * console.log(validate({ header: { type: 'fix', subject: 'ok' } })); // true * * const commitObject = { * header: { type: 'test', subject: 'updating tests' }, * foo: 'bar', * isBreaking: false, * body: 'oh ah', * }; * console.log(validate(commitObject)); // true * * const result = validate('foo bar qux', true); * console.log(result.error); * // => Error: expect \`commit\` to follow: * // <type>[optional scope]: <description> * // * // [optional body] * // * // [optional footer] * * const res = validate('fix(ci): okey barry', true); * console.log(result.value); * // => [{ * // header: { type: 'fix', scope: 'ci', subject: 'okey barry' }, * // body: null, * // footer: null, * // }] * * const commit = { header: { type: 'fix' } }; * const { error } = validate(commit, true); * console.log(error); * // => TypeError: header.subject should be non empty string * * * const commit = { header: { type: 'fix', scope: 123, subject: 'okk' } }; * const { error } = validate(commit, true); * console.log(error); * // => TypeError: header.scope should be non empty string when given * * @name .validate * @param {string|object|array} commits a value to be parsed & validated into an object like `Commit` type * @param {boolean} [ret] to return result instead of throwing, default `false` * @returns {boolean|object} if `ret` is `true` then returns `{ value, error }` object, * where `value` is `Commit|Array<Commit>` and `error` a standard `Error` * @public */ export function validate(commits, ret = false) { return tryCatch(() => check(commits), ret); } /** * Receives a single or multiple commit message(s) in form of string, * object, array of strings, array of objects or mixed. * * Basically the return result is the same as if you run `.validate()` with * the `ret` option, but instead it throws if find problems. * * @example * import { check } from 'parse-commit-message'; * * try { * check({ header: { type: 'fix' } }); * } catch(err) { * console.log(err); * // => TypeError: header.subject should be non empty string * } * * // Can also validate/check a strings, array of strings, * // or even mixed - array of strings and objects * try { * check('fix(): invalid scope, it cannot be empty') * } catch(err) { * console.log(err); * // => TypeError: header.scope should be non empty string when given * } * * @name .check * @param {string|object|array} commits a value to be parsed & validated into an object like `Commit` type * @param {boolean} [flat] if the returned result length is 1, then returns the first item * @returns {Array<Commit>} returns the same as given if no problems, otherwise it will throw; * if `flat: true`, returns a `Commit` * @public */ export function check(commits, flat) { const result = [] .concat(commits) .filter((x) => x !== null || x !== undefined) .reduce((acc, commit) => { if (typeof commit === 'string') { commit = parseCommit(commit); // eslint-disable-line no-param-reassign } return acc.concat(checkCommit(commit)); }, []); return flat === true && result.length === 1 ? result[0] : result; }
Alecto3-D/testable-greeter
bb-master/sandbox/lib/python3.5/site-packages/buildbot/util/maildir.py
<reponame>Alecto3-D/testable-greeter # This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members """ This is a class which watches a maildir for new messages. It uses the linux dirwatcher API (if available) to look for new files. The .messageReceived method is invoked with the filename of the new message, relative to the top of the maildir (so it will look like "new/blahblah"). """ from __future__ import absolute_import from __future__ import print_function import os from twisted.application import internet from twisted.internet import defer from twisted.internet import reactor # We have to put it here, since we use it to provide feedback from twisted.python import log from twisted.python import runtime from buildbot.util import service dnotify = None try: import dnotify except ImportError: log.msg("unable to import dnotify, so Maildir will use polling instead") class NoSuchMaildir(Exception): pass class MaildirService(service.AsyncMultiService): pollinterval = 10 # only used if we don't have DNotify def __init__(self, basedir=None): service.AsyncMultiService.__init__(self) if basedir: self.setBasedir(basedir) self.files = [] self.dnotify = None self.timerService = None def setBasedir(self, basedir): # some users of MaildirService (scheduler.Try_Jobdir, in particular) # don't know their basedir until setServiceParent, since it is # relative to the buildmaster's basedir. So let them set it late. We # don't actually need it until our own startService. self.basedir = basedir self.newdir = os.path.join(self.basedir, "new") self.curdir = os.path.join(self.basedir, "cur") def startService(self): if not os.path.isdir(self.newdir) or not os.path.isdir(self.curdir): raise NoSuchMaildir("invalid maildir '%s'" % self.basedir) try: if dnotify: # we must hold an fd open on the directory, so we can get # notified when it changes. self.dnotify = dnotify.DNotify(self.newdir, self.dnotify_callback, [dnotify.DNotify.DN_CREATE]) except (IOError, OverflowError): # IOError is probably linux<2.4.19, which doesn't support # dnotify. OverflowError will occur on some 64-bit machines # because of a python bug log.msg("DNotify failed, falling back to polling") if not self.dnotify: self.timerService = internet.TimerService( self.pollinterval, self.poll) self.timerService.setServiceParent(self) self.poll() return service.AsyncMultiService.startService(self) def dnotify_callback(self): log.msg("dnotify noticed something, now polling") # give it a moment. I found that qmail had problems when the message # was removed from the maildir instantly. It shouldn't, that's what # maildirs are made for. I wasn't able to eyeball any reason for the # problem, and safecat didn't behave the same way, but qmail reports # "Temporary_error_on_maildir_delivery" (qmail-local.c:165, # maildir_child() process exited with rc not in 0,2,3,4). Not sure # why, and I'd have to hack qmail to investigate further, so it's # easier to just wait a second before yanking the message out of new/ reactor.callLater(0.1, self.poll) def stopService(self): if self.dnotify: self.dnotify.remove() self.dnotify = None if self.timerService is not None: self.timerService.disownServiceParent() self.timerService = None return service.AsyncMultiService.stopService(self) @defer.inlineCallbacks def poll(self): try: assert self.basedir # see what's new for f in self.files: if not os.path.isfile(os.path.join(self.newdir, f)): self.files.remove(f) newfiles = [] for f in os.listdir(self.newdir): if f not in self.files: newfiles.append(f) self.files.extend(newfiles) for n in newfiles: try: yield self.messageReceived(n) except Exception: log.err( None, "while reading '%s' from maildir '%s':" % (n, self.basedir)) except Exception: log.err(None, "while polling maildir '%s':" % (self.basedir,)) def moveToCurDir(self, filename): if runtime.platformType == "posix": # open the file before moving it, because I'm afraid that once # it's in cur/, someone might delete it at any moment path = os.path.join(self.newdir, filename) f = open(path, "r") os.rename(os.path.join(self.newdir, filename), os.path.join(self.curdir, filename)) elif runtime.platformType == "win32": # do this backwards under windows, because you can't move a file # that somebody is holding open. This was causing a Permission # Denied error on bear's win32-twisted1.3 worker. os.rename(os.path.join(self.newdir, filename), os.path.join(self.curdir, filename)) path = os.path.join(self.curdir, filename) f = open(path, "r") return f def messageReceived(self, filename): raise NotImplementedError
fidian/PrettyCSS
test/css/page-test.js
<gh_stars>10-100 "use strict"; var util = require('./util'); exports.batch = util.makeVows('page', { '@page block': { 'input': 'margin: 7em;\n', 'tokenList': ['declaration-page', 'whitespace'], 'tokensRemaining': 0, 'toString': 'margin:7em;' } });
EnvironmentAgency/flood_risk_engine
db/migrate/20160513144337_add_uprn_to_address.rb
<reponame>EnvironmentAgency/flood_risk_engine class AddUprnToAddress < ActiveRecord::Migration[4.2] def change add_column :flood_risk_engine_addresses, :uprn, :string add_index :flood_risk_engine_addresses, :uprn change_column :flood_risk_engine_locations, :easting, :string change_column :flood_risk_engine_locations, :northing, :string end end
octoblu/alljoyn
alljoyn/services/time/ios/inc/alljoyn/time/AJTMTimeServicePeriod.h
<reponame>octoblu/alljoyn /****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, 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. ******************************************************************************/ /** * This class is experimental, and as such has not been tested. * Please help make it more robust by contributing fixes if you find issues **/ #import <Foundation/Foundation.h> #import "alljoyn/Status.h" #import "alljoyn/time/TimeServicePeriod.h" @interface AJTMTimeServicePeriod : NSObject - (id)initWithHandle:(const ajn::services::TimeServicePeriod *)handle; /** * Initialize the object with its data. * * @param hour A positive number * @param minute Expected range: 0-59 * @param second Expected range: 0-59 * @param millisecond Expected range: 0-999 * @return ER_OK if the object was initialized successfully and valid arguments have been passed to this method, * otherwise ER_BAD_ARGUMENT status of the appropriate argument is returned */ -(QStatus)populateWithHour:(uint8_t) hour minute:(uint8_t) minute second:(uint8_t) second millisecond:(uint16_t) millisecond; /** * Checks whether data of the object is valid, the object variables have a correct values. * * @return TRUE of the object is valid */ -(bool)isValid; /** * Returns Hour * * @return Returns hour */ -(uint8_t)hour; /** * Returns Minute * * @return Returns minute */ -(uint8_t)minute; /** * Returns second * * @return Returns second */ -(uint8_t)second; /** * Returns millisecond * * @return Returns millisecond */ -(uint8_t)millisecond; -(const ajn::services::TimeServicePeriod&)getHandle; @end
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/CloudDocsDaemon.framework/BRCAnalyticsReporter.h
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:50:40 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/CloudDocsDaemon.framework/CloudDocsDaemon * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol OS_dispatch_queue; @class BRCAccountSession, NSObject, BRCMetricEndpoint, NSMutableDictionary; @interface BRCAnalyticsReporter : NSObject { BRCAccountSession* _session; NSObject*<OS_dispatch_queue> _queue; BRCMetricEndpoint* _metricEndpoint; NSMutableDictionary* _eventsByKind; } -(id)initWithSession:(id)arg1 ; -(void)dumpToContext:(id)arg1 ; -(void)submitEventMetric:(id)arg1 ; -(void)_forgetEventMetrics:(id)arg1 ; -(void)_cleanupTimedOutEventMetrics:(id)arg1 ; -(void)_withEventMetricsOfKind:(id)arg1 accessor:(/*^block*/id)arg2 ; -(void)forgetEventMetric:(id)arg1 ; -(void)createFSEventToSyncUpEventForFileID:(unsigned long long)arg1 genID:(unsigned)arg2 ; -(void)lookupFSEventToSyncUpEventByFileID:(unsigned long long)arg1 genID:(unsigned)arg2 accessor:(/*^block*/id)arg3 ; -(void)lookupFSEventToSyncUpEventByItemID:(id)arg1 accessor:(/*^block*/id)arg2 ; -(void)createUserDownloadEventForOperationID:(id)arg1 isRecursive:(BOOL)arg2 isForBackup:(BOOL)arg3 ; -(void)lookupUserDownloadEventByOperationID:(id)arg1 accessor:(/*^block*/id)arg2 ; -(void)lookupUserDownloadEventByDocID:(id)arg1 accessor:(/*^block*/id)arg2 ; @end
NCIEVS/nci-meme5
model/src/main/java/com/wci/umls/server/model/content/LexicalClass.java
/** * Copyright 2016 West Coast Informatics, LLC */ package com.wci.umls.server.model.content; /** * Represents a classification by LVG-normalized string. Any two atoms with the * same string class have the same LVG-normalized name. */ public interface LexicalClass extends AtomClass { /** * Returns the normalized string. * * @return the normalized string */ public String getNormalizedName(); /** * Sets the normalized string. * * @param normalizedString the normalized string */ public void setNormalizedName(String normalizedString); /** * Sets the language. * * @param language the language */ public void setLanguage(String language); /** * Returns the language. * * @return the language */ public String getLanguage(); }
VivekChamp/clubcrm
club_crm/club_crm/report/spa_commission_summary/spa_commission_summary.js
<reponame>VivekChamp/clubcrm<gh_stars>0 // Copyright (c) 2016, <NAME> and contributors // For license information, please see license.txt /* eslint-disable */ frappe.query_reports["Spa Commission Summary"] = { "filters": [{ fieldname: "year", label: __("Year"), fieldtype: "Link", options: "Fiscal Year", default: frappe.defaults.get_user_default("fiscal_year"), reqd: 1 }, { fieldname: "date_range", label: __("Range"), fieldtype: "Select", options: "Month\nCustom Range", default: "Month", reqd: 1 }, { fieldname: "month", label: __("Month"), fieldtype: "Select", options: "January\nFebruary\nMarch\nApril\nMay\nJune\nJuly\nAugust\nSeptember\nOctober\nNovember\nDecember", default: "January", depends_on: "eval:doc.date_range=='Month'", mandatory_depends_on: "eval:doc.date_range=='Month'" }, { fieldname: "from_date", label: __("From Date"), default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), fieldtype: "Date", depends_on: "eval:doc.date_range=='Custom Range'", mandatory_depends_on: "eval:doc.date_range=='Custom Range'" }, { fieldname: "to_date", label: __("To Date"), fieldtype: "Date", default: frappe.datetime.get_today(), depends_on: "eval:doc.date_range=='Custom Range'", mandatory_depends_on: "eval:doc.date_range=='Custom Range'" }, { fieldname: "service_staff", label: __("Staff Name"), fieldtype: "Link", options: "Service Staff", filters: { "spa_check": 1 } } ] };
symLogicDMUS/Try-Reactjs
src/game_logic/testObjects/white/pinDicts/pinned_ex2.js
<filename>src/game_logic/testObjects/white/pinDicts/pinned_ex2.js export var pins = { WP1: [ [ 3, 4 ], [ 2, 3 ], [ 1, 2 ] ], WB1: [ [ 4, 4 ], [ 4, 3 ], [ 4, 2 ], [ 4, 1 ] ], WN1: [ [ 5, 4 ], [ 6, 3 ], [ 7, 2 ], [ 8, 1 ] ], WP2: [ [ 3, 5 ], [ 2, 5 ], [ 1, 5 ] ], WK1: [], WR1: [ [ 5, 5 ], [ 6, 5 ], [ 7, 5 ], [ 8, 5 ] ], WN2: [ [ 3, 6 ], [ 2, 7 ], [ 1, 8 ] ], WB2: [ [ 4, 6 ], [ 4, 7 ], [ 4, 8 ] ], WQ1: [ [ 5, 6 ], [ 6, 7 ], [ 7, 8 ] ] } // module.exports = pins;
lukaszlaszuk/insightconnect-plugins
plugins/kolide/komand_kolide/actions/create_query/schema.py
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Create a new query in Kolide" class Input: DESCRIPTION = "description" NAME = "name" QUERY = "query" class Output: RESULTS = "results" class CreateQueryInput(komand.Input): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "description": { "type": "string", "title": "Description", "description": "Description of query", "order": 2 }, "name": { "type": "string", "title": "Name", "description": "Name of query", "order": 1 }, "query": { "type": "string", "title": "Query", "description": "Query to run on fleet", "order": 3 } }, "required": [ "description", "name", "query" ] } """) def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateQueryOutput(komand.Output): schema = json.loads(""" { "type": "object", "title": "Variables", "properties": { "results": { "type": "object", "title": "Results", "description": "Results from creating a new query", "order": 1 } } } """) def __init__(self): super(self.__class__, self).__init__(self.schema)
martinmihov/JavaAdvanced
AbstractionExercises/ToTheStars.java
<reponame>martinmihov/JavaAdvanced package AbstractionExercises; import java.util.Scanner; public class ToTheStars { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[][] stars = new String [3][3]; for (int i = 0; i <stars.length ; i++) { String[] star = scanner.nextLine().split(" "); for (int j = 0; j <stars[i].length ; j++) { stars[i][j] = star[j]; } } String[] NormandyPos = scanner.nextLine().split(" "); int turns = Integer.parseInt(scanner.nextLine()); double positionX = Double.parseDouble(NormandyPos[0]); double positionY = Double.parseDouble(NormandyPos[1]); for (int i = 0; i <=turns ; i++) { boolean isStar = false; for (int j = 0; j <stars.length ; j++) { double starPositionX = Double.parseDouble(stars[j][1]); double starPositionY = Double.parseDouble(stars[j][2]); if ( (positionY >= starPositionY-1) && (positionY <= starPositionY + 1) && (positionX >= starPositionX -1) && (positionX <= starPositionX +1 ) ) { System.out.println(stars[j][0].toLowerCase()); isStar = true; break; } } if (!isStar) { System.out.println("space"); } positionY++; } } }
Phalcon7/framework
ext/mvc/model/transaction/managerinterface.c
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #include "mvc/model/transaction/managerinterface.h" #include "kernel/main.h" zend_class_entry *phalcon_mvc_model_transaction_managerinterface_ce; static const zend_function_entry phalcon_mvc_model_transaction_managerinterface_method_entry[] = { PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, has, NULL) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, get, arginfo_phalcon_mvc_model_transaction_managerinterface_get) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, rollbackPendent, NULL) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, commit, NULL) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, rollback, arginfo_phalcon_mvc_model_transaction_managerinterface_rollback) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, notifyRollback, arginfo_phalcon_mvc_model_transaction_managerinterface_notifyrollback) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, notifyCommit, arginfo_phalcon_mvc_model_transaction_managerinterface_notifycommit) PHP_ABSTRACT_ME(Phalcon_Mvc_Model_Transaction_ManagerInterface, collectTransactions, NULL) PHP_FE_END }; /** * Phalcon\Mvc\Model\Transaction\ManagerInterface initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_Model_Transaction_ManagerInterface){ PHALCON_REGISTER_INTERFACE(Phalcon\\Mvc\\Model\\Transaction, ManagerInterface, mvc_model_transaction_managerinterface, phalcon_mvc_model_transaction_managerinterface_method_entry); return SUCCESS; } /** * Checks whether manager has an active transaction * * @return boolean */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, has); /** * Returns a new Phalcon\Mvc\Model\Transaction or an already created once * * @param boolean $autoBegin * @return Phalcon\Mvc\Model\TransactionInterface */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, get); /** * Rollbacks active transactions within the manager * */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, rollbackPendent); /** * Commmits active transactions within the manager * */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, commit); /** * Rollbacks active transactions within the manager * Collect will remove transaction from the manager * * @param boolean $collect */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, rollback); /** * Notifies the manager about a rollbacked transaction * * @param Phalcon\Mvc\Model\TransactionInterface $transaction */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, notifyRollback); /** * Notifies the manager about a commited transaction * * @param Phalcon\Mvc\Model\TransactionInterface $transaction */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, notifyCommit); /** * Remove all the transactions from the manager * */ PHALCON_DOC_METHOD(Phalcon_Mvc_Model_Transaction_ManagerInterface, collectTransactions);
ikem-krueger/Java-Algorithms
src/main/java/org/calvin/BitManipulation/DivideBy2or3.java
<reponame>ikem-krueger/Java-Algorithms package org.calvin.BitManipulation; class DivideBy2or3 { int add(int n1, int n2) { int x = n1; int y = n2; while (x > 0) { int t = (x & y) << 1; y ^= x; x = t; } return y; } // public static long addRecursive(long a, long b) { // long carry = (a & b) << 1; // long sum = (a ^ b); // return carry == 0 ? sum : addRecursive(carry, sum); // } int divideby2or3(int incoming, int x) { int num = incoming; if (x == 2) { return num >> 1; } int sum = 0; while (num > x) { sum = add(num >> 2, sum); num = add(num >> 2, num & x); } if (num == x) sum = add(sum, 1); return sum; } }
sgrowe/ga
homeworks/javascript-calculator/solution-code/scripts/app.js
// ! 💻 Acuerdate que cuando estas trabajando en el navegador, asegurate de salvar cambios en este archivo, y actualiza la ventana del navegador para volver a ejecutar el código. // ! 👨‍🏫 Leé cuidadosamente el readme, y practica utilizando "window.prompt()" para coger la entrada del usuario. // * Escribe tu código debajo. let calcular = true; while (calcular) { const primerNumero = parseFloat(window.prompt('¿Cual es el primer numero?')); const segundoNumero = parseFloat( window.prompt('¿Cual es el segundo numero?'), ); const operador = window.prompt('¿Te gustaria +,-,* o / ?'); if (operador === '+') { window.alert(primerNumero + segundoNumero); } if (operador === '-') { window.alert(primerNumero - segundoNumero); } if (operador === '/') { window.alert(primerNumero / segundoNumero); } if (operador === '*') { window.alert(primerNumero * segundoNumero); } calcular = window.confirm('¿Te gustaría ir de nuevo?'); } console.log('Gracias, adios');
twitter-zuiwanyuan/finatra
inject/inject-thrift-client/src/test/scala/com/twitter/inject/thrift/integration/http_server/EchoThriftClientModule.scala
<filename>inject/inject-thrift-client/src/test/scala/com/twitter/inject/thrift/integration/http_server/EchoThriftClientModule.scala package com.twitter.inject.thrift.integration.http_server import com.twitter.inject.thrift.modules.ThriftClientModule import com.twitter.test.thriftscala.EchoService import com.twitter.util.Future object EchoThriftClientModule extends ThriftClientModule[EchoService[Future]] { override val label = "echo-service" override val dest = "flag!thrift-echo-service" }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-macie2/include/aws/macie2/model/CreateClassificationJobRequest.h
<reponame>perfectrecall/aws-sdk-cpp /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/macie2/Macie2_EXPORTS.h> #include <aws/macie2/Macie2Request.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/macie2/model/JobType.h> #include <aws/macie2/model/ManagedDataIdentifierSelector.h> #include <aws/macie2/model/S3JobDefinition.h> #include <aws/macie2/model/JobScheduleFrequency.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> #include <aws/core/utils/UUID.h> namespace Aws { namespace Macie2 { namespace Model { /** */ class AWS_MACIE2_API CreateClassificationJobRequest : public Macie2Request { public: CreateClassificationJobRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateClassificationJob"; } Aws::String SerializePayload() const override; /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline CreateClassificationJobRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline CreateClassificationJobRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>A unique, case-sensitive token that you provide to ensure the idempotency of * the request.</p> */ inline CreateClassificationJobRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline const Aws::Vector<Aws::String>& GetCustomDataIdentifierIds() const{ return m_customDataIdentifierIds; } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline bool CustomDataIdentifierIdsHasBeenSet() const { return m_customDataIdentifierIdsHasBeenSet; } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline void SetCustomDataIdentifierIds(const Aws::Vector<Aws::String>& value) { m_customDataIdentifierIdsHasBeenSet = true; m_customDataIdentifierIds = value; } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline void SetCustomDataIdentifierIds(Aws::Vector<Aws::String>&& value) { m_customDataIdentifierIdsHasBeenSet = true; m_customDataIdentifierIds = std::move(value); } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline CreateClassificationJobRequest& WithCustomDataIdentifierIds(const Aws::Vector<Aws::String>& value) { SetCustomDataIdentifierIds(value); return *this;} /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline CreateClassificationJobRequest& WithCustomDataIdentifierIds(Aws::Vector<Aws::String>&& value) { SetCustomDataIdentifierIds(std::move(value)); return *this;} /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline CreateClassificationJobRequest& AddCustomDataIdentifierIds(const Aws::String& value) { m_customDataIdentifierIdsHasBeenSet = true; m_customDataIdentifierIds.push_back(value); return *this; } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline CreateClassificationJobRequest& AddCustomDataIdentifierIds(Aws::String&& value) { m_customDataIdentifierIdsHasBeenSet = true; m_customDataIdentifierIds.push_back(std::move(value)); return *this; } /** * <p>An array of unique identifiers, one for each custom data identifier for the * job to use when it analyzes data. To use only managed data identifiers, don't * specify a value for this property and specify a value other than NONE for the * managedDataIdentifierSelector property.</p> */ inline CreateClassificationJobRequest& AddCustomDataIdentifierIds(const char* value) { m_customDataIdentifierIdsHasBeenSet = true; m_customDataIdentifierIds.push_back(value); return *this; } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline CreateClassificationJobRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline CreateClassificationJobRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>A custom description of the job. The description can contain as many as 200 * characters.</p> */ inline CreateClassificationJobRequest& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>For a recurring job, specifies whether to analyze all existing, eligible * objects immediately after the job is created (true). To analyze only those * objects that are created or changed after you create the job and before the * job's first scheduled run, set this value to false.</p><p>If you configure the * job to run only once, don't specify a value for this property.</p> */ inline bool GetInitialRun() const{ return m_initialRun; } /** * <p>For a recurring job, specifies whether to analyze all existing, eligible * objects immediately after the job is created (true). To analyze only those * objects that are created or changed after you create the job and before the * job's first scheduled run, set this value to false.</p><p>If you configure the * job to run only once, don't specify a value for this property.</p> */ inline bool InitialRunHasBeenSet() const { return m_initialRunHasBeenSet; } /** * <p>For a recurring job, specifies whether to analyze all existing, eligible * objects immediately after the job is created (true). To analyze only those * objects that are created or changed after you create the job and before the * job's first scheduled run, set this value to false.</p><p>If you configure the * job to run only once, don't specify a value for this property.</p> */ inline void SetInitialRun(bool value) { m_initialRunHasBeenSet = true; m_initialRun = value; } /** * <p>For a recurring job, specifies whether to analyze all existing, eligible * objects immediately after the job is created (true). To analyze only those * objects that are created or changed after you create the job and before the * job's first scheduled run, set this value to false.</p><p>If you configure the * job to run only once, don't specify a value for this property.</p> */ inline CreateClassificationJobRequest& WithInitialRun(bool value) { SetInitialRun(value); return *this;} /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline const JobType& GetJobType() const{ return m_jobType; } /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline bool JobTypeHasBeenSet() const { return m_jobTypeHasBeenSet; } /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline void SetJobType(const JobType& value) { m_jobTypeHasBeenSet = true; m_jobType = value; } /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline void SetJobType(JobType&& value) { m_jobTypeHasBeenSet = true; m_jobType = std::move(value); } /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline CreateClassificationJobRequest& WithJobType(const JobType& value) { SetJobType(value); return *this;} /** * <p>The schedule for running the job. Valid values are:</p> <ul><li><p>ONE_TIME - * Run the job only once. If you specify this value, don't specify a value for the * scheduleFrequency property.</p></li> <li><p>SCHEDULED - Run the job on a daily, * weekly, or monthly basis. If you specify this value, use the scheduleFrequency * property to define the recurrence pattern for the job.</p></li></ul> */ inline CreateClassificationJobRequest& WithJobType(JobType&& value) { SetJobType(std::move(value)); return *this;} /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline const Aws::Vector<Aws::String>& GetManagedDataIdentifierIds() const{ return m_managedDataIdentifierIds; } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline bool ManagedDataIdentifierIdsHasBeenSet() const { return m_managedDataIdentifierIdsHasBeenSet; } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline void SetManagedDataIdentifierIds(const Aws::Vector<Aws::String>& value) { m_managedDataIdentifierIdsHasBeenSet = true; m_managedDataIdentifierIds = value; } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline void SetManagedDataIdentifierIds(Aws::Vector<Aws::String>&& value) { m_managedDataIdentifierIdsHasBeenSet = true; m_managedDataIdentifierIds = std::move(value); } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline CreateClassificationJobRequest& WithManagedDataIdentifierIds(const Aws::Vector<Aws::String>& value) { SetManagedDataIdentifierIds(value); return *this;} /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline CreateClassificationJobRequest& WithManagedDataIdentifierIds(Aws::Vector<Aws::String>&& value) { SetManagedDataIdentifierIds(std::move(value)); return *this;} /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline CreateClassificationJobRequest& AddManagedDataIdentifierIds(const Aws::String& value) { m_managedDataIdentifierIdsHasBeenSet = true; m_managedDataIdentifierIds.push_back(value); return *this; } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline CreateClassificationJobRequest& AddManagedDataIdentifierIds(Aws::String&& value) { m_managedDataIdentifierIdsHasBeenSet = true; m_managedDataIdentifierIds.push_back(std::move(value)); return *this; } /** * <p>An array of unique identifiers, one for each managed data identifier for the * job to include (use) or exclude (not use) when it analyzes data. Inclusion or * exclusion depends on the managed data identifier selection type that you specify * for the job (managedDataIdentifierSelector).</p><p>To retrieve a list of valid * values for this property, use the ListManagedDataIdentifiers operation.</p> */ inline CreateClassificationJobRequest& AddManagedDataIdentifierIds(const char* value) { m_managedDataIdentifierIdsHasBeenSet = true; m_managedDataIdentifierIds.push_back(value); return *this; } /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline const ManagedDataIdentifierSelector& GetManagedDataIdentifierSelector() const{ return m_managedDataIdentifierSelector; } /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline bool ManagedDataIdentifierSelectorHasBeenSet() const { return m_managedDataIdentifierSelectorHasBeenSet; } /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline void SetManagedDataIdentifierSelector(const ManagedDataIdentifierSelector& value) { m_managedDataIdentifierSelectorHasBeenSet = true; m_managedDataIdentifierSelector = value; } /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline void SetManagedDataIdentifierSelector(ManagedDataIdentifierSelector&& value) { m_managedDataIdentifierSelectorHasBeenSet = true; m_managedDataIdentifierSelector = std::move(value); } /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline CreateClassificationJobRequest& WithManagedDataIdentifierSelector(const ManagedDataIdentifierSelector& value) { SetManagedDataIdentifierSelector(value); return *this;} /** * <p>The selection type to apply when determining which managed data identifiers * the job uses to analyze data. Valid values are:</p> <ul><li><p>ALL - Use all the * managed data identifiers that Amazon Macie provides. If you specify this value, * don't specify any values for the managedDataIdentifierIds property.</p></li> * <li><p>EXCLUDE - Use all the managed data identifiers that Macie provides except * the managed data identifiers specified by the managedDataIdentifierIds * property.</p></li> <li><p>INCLUDE - Use only the managed data identifiers * specified by the managedDataIdentifierIds property.</p></li> <li><p>NONE - Don't * use any managed data identifiers. If you specify this value, specify at least * one custom data identifier for the job (customDataIdentifierIds) and don't * specify any values for the managedDataIdentifierIds property.</p></li></ul> * <p>If you don't specify a value for this property, the job uses all managed data * identifiers. If you don't specify a value for this property or you specify ALL * or EXCLUDE for a recurring job, the job also uses new managed data identifiers * as they are released.</p> */ inline CreateClassificationJobRequest& WithManagedDataIdentifierSelector(ManagedDataIdentifierSelector&& value) { SetManagedDataIdentifierSelector(std::move(value)); return *this;} /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline CreateClassificationJobRequest& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline CreateClassificationJobRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>A custom name for the job. The name can contain as many as 500 * characters.</p> */ inline CreateClassificationJobRequest& WithName(const char* value) { SetName(value); return *this;} /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline const S3JobDefinition& GetS3JobDefinition() const{ return m_s3JobDefinition; } /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline bool S3JobDefinitionHasBeenSet() const { return m_s3JobDefinitionHasBeenSet; } /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline void SetS3JobDefinition(const S3JobDefinition& value) { m_s3JobDefinitionHasBeenSet = true; m_s3JobDefinition = value; } /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline void SetS3JobDefinition(S3JobDefinition&& value) { m_s3JobDefinitionHasBeenSet = true; m_s3JobDefinition = std::move(value); } /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline CreateClassificationJobRequest& WithS3JobDefinition(const S3JobDefinition& value) { SetS3JobDefinition(value); return *this;} /** * <p>The S3 buckets that contain the objects to analyze, and the scope of that * analysis.</p> */ inline CreateClassificationJobRequest& WithS3JobDefinition(S3JobDefinition&& value) { SetS3JobDefinition(std::move(value)); return *this;} /** * <p>The sampling depth, as a percentage, for the job to apply when processing * objects. This value determines the percentage of eligible objects that the job * analyzes. If this value is less than 100, Amazon Macie selects the objects to * analyze at random, up to the specified percentage, and analyzes all the data in * those objects.</p> */ inline int GetSamplingPercentage() const{ return m_samplingPercentage; } /** * <p>The sampling depth, as a percentage, for the job to apply when processing * objects. This value determines the percentage of eligible objects that the job * analyzes. If this value is less than 100, Amazon Macie selects the objects to * analyze at random, up to the specified percentage, and analyzes all the data in * those objects.</p> */ inline bool SamplingPercentageHasBeenSet() const { return m_samplingPercentageHasBeenSet; } /** * <p>The sampling depth, as a percentage, for the job to apply when processing * objects. This value determines the percentage of eligible objects that the job * analyzes. If this value is less than 100, Amazon Macie selects the objects to * analyze at random, up to the specified percentage, and analyzes all the data in * those objects.</p> */ inline void SetSamplingPercentage(int value) { m_samplingPercentageHasBeenSet = true; m_samplingPercentage = value; } /** * <p>The sampling depth, as a percentage, for the job to apply when processing * objects. This value determines the percentage of eligible objects that the job * analyzes. If this value is less than 100, Amazon Macie selects the objects to * analyze at random, up to the specified percentage, and analyzes all the data in * those objects.</p> */ inline CreateClassificationJobRequest& WithSamplingPercentage(int value) { SetSamplingPercentage(value); return *this;} /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline const JobScheduleFrequency& GetScheduleFrequency() const{ return m_scheduleFrequency; } /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline bool ScheduleFrequencyHasBeenSet() const { return m_scheduleFrequencyHasBeenSet; } /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline void SetScheduleFrequency(const JobScheduleFrequency& value) { m_scheduleFrequencyHasBeenSet = true; m_scheduleFrequency = value; } /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline void SetScheduleFrequency(JobScheduleFrequency&& value) { m_scheduleFrequencyHasBeenSet = true; m_scheduleFrequency = std::move(value); } /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline CreateClassificationJobRequest& WithScheduleFrequency(const JobScheduleFrequency& value) { SetScheduleFrequency(value); return *this;} /** * <p>The recurrence pattern for running the job. To run the job only once, don't * specify a value for this property and set the value for the jobType property to * ONE_TIME.</p> */ inline CreateClassificationJobRequest& WithScheduleFrequency(JobScheduleFrequency&& value) { SetScheduleFrequency(std::move(value)); return *this;} /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;} /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;} /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>A map of key-value pairs that specifies the tags to associate with the * job.</p> <p>A job can have a maximum of 50 tags. Each tag consists of a tag key * and an associated tag value. The maximum length of a tag key is 128 characters. * The maximum length of a tag value is 256 characters.</p> */ inline CreateClassificationJobRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } private: Aws::String m_clientToken; bool m_clientTokenHasBeenSet; Aws::Vector<Aws::String> m_customDataIdentifierIds; bool m_customDataIdentifierIdsHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; bool m_initialRun; bool m_initialRunHasBeenSet; JobType m_jobType; bool m_jobTypeHasBeenSet; Aws::Vector<Aws::String> m_managedDataIdentifierIds; bool m_managedDataIdentifierIdsHasBeenSet; ManagedDataIdentifierSelector m_managedDataIdentifierSelector; bool m_managedDataIdentifierSelectorHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; S3JobDefinition m_s3JobDefinition; bool m_s3JobDefinitionHasBeenSet; int m_samplingPercentage; bool m_samplingPercentageHasBeenSet; JobScheduleFrequency m_scheduleFrequency; bool m_scheduleFrequencyHasBeenSet; Aws::Map<Aws::String, Aws::String> m_tags; bool m_tagsHasBeenSet; }; } // namespace Model } // namespace Macie2 } // namespace Aws
UniversityOfHelsinkiCS/mobvita
client/components/PracticeView/PreviousSnippets/Word/index.js
import React from 'react' import { useHistory } from 'react-router-dom' import { hiddenFeatures } from 'Utilities/common' import PlainWord from 'Components/PracticeView/PlainWord' import PreviousExerciseWord from './PreviousExerciseWord' const Word = ({ word, answer, tiedAnswer, hideFeedback }) => { const history = useHistory() const isPreviewMode = history.location.pathname.includes('preview') // "Display feedback" toggle is off if (hideFeedback) return <PlainWord word={word} annotatingAllowed /> // in stag, also highlight words with no exercise concepts in preview mode if (hiddenFeatures && isPreviewMode && word.concepts?.length === 0) { return <PreviousExerciseWord word={word} /> } // preview mode (if concept list is not empty) if (isPreviewMode && word.concepts?.length > 0) { return <PreviousExerciseWord word={word} /> } // session history in practice & compete mode if (word.tested) { return <PreviousExerciseWord word={word} answer={answer} tiedAnswer={tiedAnswer} /> } // review mode (highlight all word objs that have 'wrong' field)) if ({}.propertyIsEnumerable.call(word, 'wrong')) { // field exists but might be empty const answerObj = { correct: word.surface, concept: word.concept, users_answer: word.wrong, id: word.ID, } return <PreviousExerciseWord word={word} answer={answerObj} tiedAnswer={null} /> } return <PlainWord word={word} annotatingAllowed /> } export default Word
kamlesh-00/algorithms-in-java
iii/elementary_data_structures/AQueue.java
package com.iii.elementary_data_structures; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AQueue<T> { public List<T> items; public int head; public int tail; public int capacity; public AQueue() { } public AQueue(int capacity) { this.items = new ArrayList<>(Collections.nCopies(capacity, null)); this.head = 0; this.tail = 0; this.capacity = capacity; } public boolean isEmpty() { if (this.head == this.tail) return true; return false; } public boolean isFull() { if (this.head == this.tail + 1) return true; if (this.head == 0 && this.tail == this.capacity - 1) return true; return false; } public void enqueue(T item) throws Exception { if (isFull()) throw new Exception("queue is full"); this.items.set(this.tail, item); if (this.tail == this.capacity - 1) this.tail = 0; else this.tail += 1; } public T dequeue() throws Exception { if (isEmpty()) throw new Exception("queue is empty"); T x = this.items.get(this.head); if (this.head == this.capacity - 1) this.head = 0; else this.head += 1; return x; } @Override public String toString() { return "{\n" + " items='" + items + "'" + "\n}"; } }
lauracristinaes/aula-java
hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.idgen.enhanced.forcedtable; import org.junit.Test; import org.hibernate.Session; import org.hibernate.id.IdentifierGeneratorHelper.BasicHolder; import org.hibernate.id.enhanced.HiLoOptimizer; import org.hibernate.id.enhanced.SequenceStyleGenerator; import org.hibernate.id.enhanced.TableStructure; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * {@inheritDoc} * * @author <NAME> */ public class HiLoForcedTableSequenceTest extends BaseCoreFunctionalTestCase { public String[] getMappings() { return new String[] { "idgen/enhanced/forcedtable/HiLo.hbm.xml" }; } @Test public void testNormalBoundary() { EntityPersister persister = sessionFactory().getEntityPersister( Entity.class.getName() ); assertTrue( "sequence style generator was not used", SequenceStyleGenerator.class.isInstance( persister.getIdentifierGenerator() ) ); SequenceStyleGenerator generator = ( SequenceStyleGenerator ) persister.getIdentifierGenerator(); assertTrue( "table structure was not used", TableStructure.class.isInstance( generator.getDatabaseStructure() ) ); assertTrue( "hilo optimizer was not used", HiLoOptimizer.class.isInstance( generator.getOptimizer() ) ); HiLoOptimizer optimizer = (HiLoOptimizer) generator.getOptimizer(); int increment = optimizer.getIncrementSize(); Entity[] entities = new Entity[ increment + 1 ]; Session s = openSession(); s.beginTransaction(); for ( int i = 0; i < increment; i++ ) { entities[i] = new Entity( "" + ( i + 1 ) ); s.save( entities[i] ); long expectedId = i + 1; assertEquals( expectedId, entities[i].getId().longValue() ); assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); } // now force a "clock over" entities[ increment ] = new Entity( "" + increment ); s.save( entities[ increment ] ); long expectedId = optimizer.getIncrementSize() + 1; assertEquals( expectedId, entities[ optimizer.getIncrementSize() ].getId().longValue() ); assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization + clock-over assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() ); assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() ); s.getTransaction().commit(); s.beginTransaction(); for ( int i = 0; i < entities.length; i++ ) { assertEquals( i + 1, entities[i].getId().intValue() ); s.delete( entities[i] ); } s.getTransaction().commit(); s.close(); } }
chelini/isl-haystack
test_inputs/codegen/cloog/basic-bounds-2.c
<reponame>chelini/isl-haystack S1(0);
ccantill/qdox
src/main/java/com/thoughtworks/qdox/library/JavaClassContext.java
<filename>src/main/java/com/thoughtworks/qdox/library/JavaClassContext.java package com.thoughtworks.qdox.library; /* * 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. */ import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaPackage; import com.thoughtworks.qdox.model.JavaSource; /** * JavaClassContext gives you a mechanism to get a {@link JavaClass}. * If a class couldn't be found in the cache, the class will be pulled from the classLibrary, the builder will create the corresponding JavaClass and put it in the cache. * * * @author <NAME> * */ public class JavaClassContext implements Serializable { private Map<String, JavaClass> classMap = new LinkedHashMap<String, JavaClass>(); private Map<String, JavaPackage> packageMap = new LinkedHashMap<String, JavaPackage>(); private Set<JavaSource> sourceSet = new LinkedHashSet<JavaSource>(); public JavaClassContext(){ } /** * Retrieve the {@link JavaClass} based on the {@code name}. * * @param name the fully qualified name of the class * @return the stored JavaClass, otherwise <code>null</code> */ public JavaClass getClassByName(String name) { return classMap.get( name ); } /** * Remove and return the {@link JavaClass} based on the {@code name}. * * @param name the fully qualified name of the class * @return the removed JavaClass, otherwise <code>null</code> */ public JavaClass removeClassByName(String name) { return classMap.remove( name ); } /** * Return all stored JavaClasses * * @return a list of JavaClasses, never <code>null</code> */ public List<JavaClass> getClasses() { return Collections.unmodifiableList( new LinkedList<JavaClass>(classMap.values()) ); } /** * Store this {@link JavaClass} based on its fully qualified name * * @param javaClass the JavaClass to add */ public void add(JavaClass javaClass) { classMap.put(javaClass.getBinaryName(), javaClass); } /** * Retrieve the {@link JavaPackage} based on the {@code name}. * * @param name the fully qualified name of the package * @return the stored JavaPackage, otherwise <code>null</code> */ public JavaPackage getPackageByName( String name ) { return packageMap.get( name ); } /** * Remove and return the {@link JavaPackage} based on the {@code name}. * * @param name the fully qualified name of the class * @return the removed JavaPackage, otherwise <code>null</code> */ public JavaPackage removePackageByName( String name ) { return packageMap.remove( name ); } /** * A null-safe implementation to store a {@link JavaPackage} in this context * * @param jPackage the JavaPackage to add */ public void add( JavaPackage jPackage ) { if(jPackage != null) { packageMap.put( jPackage.getName(), jPackage ); } } /** * Return all stored JavaPackages * * @return a list of JavaPackages, never <code>null</code> */ public List<JavaPackage> getPackages() { return Collections.unmodifiableList( new LinkedList<JavaPackage>(packageMap.values()) ); } /** * Store a {@link JavaSource} in this context * * @param source the JavaSource to add */ public void add( JavaSource source ) { sourceSet.add( source ); } /** * Return all stored JavaSources * * @return a list of JavaSources, never <code>null</code> */ public List<JavaSource> getSources() { return Collections.unmodifiableList( new LinkedList<JavaSource>(sourceSet) ); } }
luciVuc/openui5
src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/v5/media-play.js
<reponame>luciVuc/openui5<gh_stars>0 sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "media-play"; const pathData = "M425.5 226c11 7 19 19 19 30s-8 23-19 30l-301 188c-6 4-12 6-19 6s-14-2-20-6c-10-7-18-18-18-33V64c0-8 8-19 18-26 6-4 13-6 20-6s13 2 19 6zm-283 154l192-120-192-121v241z"; const ltr = true; const collection = "SAP-icons-v5"; const packageName = "@ui5/webcomponents-icons"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var pathDataV4 = { pathData }; return pathDataV4; });
Grace951/ReactAU
src/shared/components/Admin/AdminListProductPage.js
<reponame>Grace951/ReactAU import { connect } from 'react-redux'; import React from 'react'; import connectDataFetchers from '../../lib/connectDataFetchers.jsx'; import { Breadcrumb , BigHeader, OrangeBoard} from "../Shared/Shared"; import { loadProductList } from '../../actions/productsActions'; import ProductsTblPage from '../Products/ProductsTblPage'; class AdminListProductPage extends React.Component{ constructor(props) { super(props); this.setCategory = this.setCategory.bind(this); } componentDidMount() { } componentWillReceiveProps(nextProps) { } setCategory (e){ let productType = this.props.categories.filter((item) => {return item._id===parseInt(e.target.value) ;})[0].categoryName; this.context.router.history.push(`/admin/productList/${productType}`); } render () { let {match, categories, products, ajaxState} = this.props; let cat = 1, t = categories.filter((item) => {return item.categoryName===match.params.cat ;}); if (t && t[0]) cat = t[0]._id || 1 ; return ( <form> <div className="row"> <div className="col-lg-12"> <Breadcrumb linkPair={[{link:"/home", desc:"Home"},{link:"/admin/productChange/0", desc:"Administration"},{link:"", desc:"Edit Products"}]}/> <BigHeader smallTitle="">Edit Products</BigHeader> </div> <div className="col-xs-12"> <div className="form-group"> <label htmlFor="productCategory">Product Category</label> <select className="form-control" id="productCategory" value={cat} onChange={this.setCategory}> { categories.map( function(item, id){ return (<option key={id} value={item._id}> {item.categoryName}</option>); }) } </select> </div> </div> <div className="col-xs-12"> <ProductsTblPage productType={match.params.cat} match={match} ajaxState={ajaxState} products={products} edit={true} editBaseLink="/admin/productChange/" delete={true} /> </div> </div> </form> ); } } AdminListProductPage.propTypes = { categories: React.PropTypes.array, ajaxState: React.PropTypes.number, products: React.PropTypes.array, match: React.PropTypes.object.isRequired, }; AdminListProductPage.contextTypes = { router: React.PropTypes.object }; function mapStateToProps(state, ownProps) { // console.log("AdminListProductPage - mapStateToProps", state); return { products: state.products, categories: state.categories, ajaxState: state.ajaxCallsInProgress, }; } const AdminListProductPageWrap = connect(mapStateToProps)( connectDataFetchers(AdminListProductPage, [ loadProductList ]) ); export default AdminListProductPageWrap;
RP0001/ms2ldaviz
ms2ldaviz/annotation/forms.py
from django import forms example_spectrum = "53.0384:331117.7\n57.0447:798106.4\n65.0386:633125.7\n77.0385:5916789.799999999\n81.0334:27067.0\n85.0396:740633.6\n91.0542:1251226.7000000002\n92.0492:2928042.3\n95.0493:728877.1\n103.0419:59138.40000000001\n104.0495:13185144.700000001\n105.045:1643858.5999999999\n105.0701:129215.0\n110.06:46285.0\n119.0604:12584552.9\n130.04:33153.3\n130.0652:270688.7\n131.0725:203663.6\n131.0734:45999.7\n142.0653:20711.1\n147.0555:63444.99999999999\n160.0871:61955089.8\n188.082:86709805.39999999" class AnnotationForm(forms.Form): parentmass = forms.FloatField(required = True,initial = 188.0818) spectrum = forms.CharField(required = True,widget = forms.Textarea(attrs={'rows': 20, 'cols': 120}),initial = example_spectrum) class BatchAnnotationForm(forms.Form): spectra = forms.CharField(required = True)
leapframework/framework
base/core/src/main/java/leap/core/params/DefaultParamsFactory.java
/* * Copyright 2013 the original author or authors. * * 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 leap.core.params; import java.util.Map; import leap.lang.Beans; import leap.lang.beans.DynaBean; import leap.lang.params.*; public class DefaultParamsFactory implements ParamsFactory { public static final DefaultParamsFactory INSTANCE = new DefaultParamsFactory(); @SuppressWarnings("unchecked") public Params createParams(Object param) throws IllegalStateException { if(null == param){ return new ParamsMap(); } if(param instanceof Params){ return (Params)param; } if(param instanceof ParamsGetter){ return ((ParamsGetter) param).getParams(); } if(param instanceof Map){ return new MapParams((Map<String,Object>)param); } if(param instanceof DynaBean) { return new DynaParams((DynaBean)param); } if(isBeanParameters(param.getClass())){ return new BeanParams(param); } throw new UnsupportedParametersException("unsupported parameters type '" + param.getClass().getName() + "'"); } public Params createParams(Object... params){ if(null == params || params.length == 0){ return EmptyParams.INSTANCE; } CompositeParams compositeParameters = new CompositeParams(); for(int i=0;i<params.length;i++){ Object param = params[i]; if(null != param){ compositeParameters.add(createParams(param)); } } return compositeParameters; } protected static boolean isBeanParameters(Class<?> cls){ if(Iterable.class.isAssignableFrom(cls)){ return false; } if(Map.class.isAssignableFrom(cls)){ return false; } if(Beans.isSimpleProperty(cls)){ return false; } if(cls.equals(Object.class)){ return false; } return true; } protected DefaultParamsFactory(){ } }
chreden/trview
trview.app/Elements/di.hpp
#pragma once #include <external/boost/di.hpp> #include "Level.h" #include "TypeNameLookup.h" #include "Entity.h" #include "StaticMesh.h" #include "Sector.h" #include "Resources/resource.h" #include "Resources/ResourceHelper.h" namespace trview { auto register_app_elements_module() noexcept { using namespace boost; using namespace graphics; return di::make_injector( di::bind<ITypeNameLookup>.to( []() { Resource type_list = get_resource_memory(IDR_TYPE_NAMES, L"TEXT"); return std::make_shared<TypeNameLookup>(std::string(type_list.data, type_list.data + type_list.size)); }), di::bind<IEntity::EntitySource>.to( [](const auto& injector) -> IEntity::EntitySource { return [&](auto&& level, auto&& entity, auto&& index, auto&& mesh_storage) { const auto type_names = injector.create<std::shared_ptr<ITypeNameLookup>>(); return std::make_shared<Entity>(injector.create<IMesh::Source>(), level, entity, mesh_storage, index, type_names->is_pickup(level.get_version(), entity.TypeID)); }; }), di::bind<IEntity::AiSource>.to( [](const auto& injector) -> IEntity::AiSource { return [&](auto&& level, auto&& ai_object, auto&& index, auto&& mesh_storage) { return std::make_shared<Entity>(injector.create<IMesh::Source>(), level, ai_object, mesh_storage, index); }; }), di::bind<IRoom::Source>.to( [](const auto& injector) -> IRoom::Source { return [&](auto&& level, auto&& room, auto&& texture_storage, auto&& mesh_storage, auto&& index, auto&& parent_level) { return std::make_shared<Room>(injector.create<IMesh::Source>(), level, room, texture_storage, mesh_storage, index, parent_level, injector.create<IStaticMesh::MeshSource>(), injector.create<IStaticMesh::PositionSource>(), injector.create<ISector::Source>()); }; }), di::bind<ITrigger::Source>.to( [](const auto& injector) -> ITrigger::Source { return [&](auto&& number, auto&& room, auto&& x, auto&& z, auto&& trigger_info) { return std::make_shared<Trigger>(number, room, x, z, trigger_info, injector.create<IMesh::TransparentSource>()); }; }), di::bind<IStaticMesh::MeshSource>.to( [](const auto& injector) -> IStaticMesh::MeshSource { auto bounding_mesh = create_cube_mesh(injector.create<IMesh::Source>()); return [=](auto&& room_mesh, auto&& level_mesh, auto&& mesh) { return std::make_shared<StaticMesh>(room_mesh, level_mesh, mesh, bounding_mesh); }; }), di::bind<IStaticMesh::PositionSource>.to( [](const auto&) -> IStaticMesh::PositionSource { return [&](auto&& position, auto&& scale, auto&& mesh) { return std::make_shared<StaticMesh>(position, scale, mesh); }; }), di::bind<ISector::Source>.to( [](const auto&) -> ISector::Source { return [&](auto&& level, auto&& room, auto&& room_sector, auto&& sector_id, auto&& room_number) { return std::make_shared<Sector>(level, room, room_sector, sector_id, room_number); }; }), di::bind<ILevel::Source>.to( [](const auto& injector) -> ILevel::Source { return [&](auto&& level) { auto texture_storage = injector.create<ILevelTextureStorage::Source>()(*level); auto mesh_storage = injector.create<IMeshStorage::Source>()(*level, *texture_storage); return std::make_unique<Level>( injector.create<std::shared_ptr<IDevice>>(), injector.create<std::shared_ptr<IShaderStorage>>(), std::move(level), texture_storage, std::move(mesh_storage), injector.create<std::unique_ptr<ITransparencyBuffer>>(), injector.create<std::unique_ptr<ISelectionRenderer>>(), injector.create<std::shared_ptr<ITypeNameLookup>>(), injector.create<IEntity::EntitySource>(), injector.create<IEntity::AiSource>(), injector.create<IRoom::Source>(), injector.create<ITrigger::Source>()); }; }) ); } }
w2ogroup/rave-old
rave-components/rave-core/src/main/java/org/apache/rave/portal/service/WidgetMarketplaceService.java
/* * 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.rave.portal.service; import java.util.List; import org.apache.rave.portal.model.Widget; import org.apache.rave.portal.model.util.SearchResult; /** * Provides capabilities for discovering widgets * from an external marketplace (e.g. Edukapp, Widgr, OMR etc.) */ public interface WidgetMarketplaceService { /** * Gets a SearchResult for {@link Widget}'s by performing a free text search * * @param searchTerm free text search term * @param offset start point within the resultset (for paging) * @param pageSize maximum number of items to be returned (for paging) * @throws Exception if the external marketplace is not configured, not available, or returns an error * @return SearchResult */ SearchResult<Widget> getWidgetsByFreeTextSearch(String searchTerm, int offset, int pageSize) throws Exception; /** * Gets a SearchResult for {@link Widget}'s by performing a category keyword search * * @param category category keyword * @param offset start point within the resultSet (for paging) * @param pageSize maximum number of items to be returned (for paging) * @throws Exception if the external marketplace is not configured, not available, or returns an error * @return SearchResult */ SearchResult<Widget> getWidgetsByCategory(String category, int offset, int pageSize) throws Exception; /** * Gets the list of categories used for widgets in the marketplace * @throws Exception if the external marketplace is not configured, not available, or returns an error * @return List */ List<String> getCategories() throws Exception; /** * Adds the specified widget; for W3C widgets this implies POSTing the .wgt to Wookie and then parsing * the resulting metadata; for OpenSocial this implies processing the metadata from Shindig and then adding * the widget. * * @param widget the widget to be added from the marketplace * @return the widget from the local Rave widget store * @throws Exception if there was a problem adding the widget to the rave store */ Widget addWidget(Widget widget) throws Exception; /** * Obtains the widget metadata so it can be validated * @param url * @param type * @return * @throws Exception */ Widget resolveWidgetMetadata(String url, String type) throws Exception; /** * Gets the specified Widget * @param id the value identifying the widget in the marketplace, e.g. Widget URI or GUID * @return a Widget * @throws Exception if no match is found */ Widget getWidget(String id) throws Exception; }
l3onardo-oliv3ira/interpolator4j
src/test/java/interpolator4j/test/InterpolatorTester.java
package interpolator4j.test; import interpolator4j.ScopeProvider; import interpolator4j.imp.BasicScopeProvider; import interpolator4j.imp.DefaultScopeProvider; public class InterpolatorTester { private static ScopeProvider BASIC_PROVIDER = new BasicScopeProvider(); private static ScopeProvider DEFAULT_PROVIDER = new DefaultScopeProvider(); protected static ScopeProvider getBasicProvider() { return BASIC_PROVIDER; } protected static ScopeProvider getDefaultProvider() { return DEFAULT_PROVIDER; } }
Ethiopia-COVID19/api-gateway
models/common/BiographicalData.js
const mongoose = require('mongoose'); const { Schema } = mongoose; const ContactInformation = require('./ContactInformation'); const BiographicalDataSchema = new Schema({ firstName: { type: String, required: true, max: 100 }, middleName: { type: String, max: 100 }, lastName: { type: String, required: true, max: 100 }, age: { type: Number, required: true }, dateOfBirth: { type: Date }, gender: { type: String, required: true }, preferredLanguage: { type: String, max: 100 }, occupation: { type: String, max: 100 }, nationality: { type: String, max: 100 }, passportNumber: { type: String, max: 100 }, governmentIssuedId: { type: String, max: 100 }, contactInformation: { type: ContactInformation }, }); module.exports = BiographicalDataSchema;
Grosskopf/openoffice
main/sc/source/ui/inc/tpsubt.hxx
<filename>main/sc/source/ui/inc/tpsubt.hxx<gh_stars>100-1000 /************************************************************** * * 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. * *************************************************************/ #ifndef SC_TPSUBT_HXX #define SC_TPSUBT_HXX #include <sfx2/tabdlg.hxx> #include <svx/checklbx.hxx> #include <vcl/fixed.hxx> #include "global.hxx" //------------------------------------------------------------------------ // +1 because one field is reserved for the "- none -" entry #define SC_MAXFIELDS MAXCOLCOUNT+1 class ScViewData; class ScDocument; //======================================================================== // Gruppenseiten: Basisklasse class ScTpSubTotalGroup : public SfxTabPage { protected: ScTpSubTotalGroup( Window* pParent, sal_uInt16 nResId, const SfxItemSet& rArgSet ); public: virtual ~ScTpSubTotalGroup(); static sal_uInt16* GetRanges (); sal_Bool DoReset ( sal_uInt16 nGroupNo, const SfxItemSet& rArgSet ); sal_Bool DoFillItemSet ( sal_uInt16 nGroupNo, SfxItemSet& rArgSet ); protected: FixedText aFtGroup; ListBox aLbGroup; FixedText aFtColumns; SvxCheckListBox aLbColumns; FixedText aFtFunctions; ListBox aLbFunctions; const String aStrNone; const String aStrColumn; ScViewData* pViewData; ScDocument* pDoc; const sal_uInt16 nWhichSubTotals; const ScSubTotalParam& rSubTotalData; SCCOL nFieldArr[SC_MAXFIELDS]; const sal_uInt16 nFieldCount; private: void Init (); void FillListBoxes (); ScSubTotalFunc LbPosToFunc ( sal_uInt16 nPos ); sal_uInt16 FuncToLbPos ( ScSubTotalFunc eFunc ); sal_uInt16 GetFieldSelPos ( SCCOL nField ); // Handler ------------------------ DECL_LINK( SelectHdl, ListBox * ); DECL_LINK( CheckHdl, ListBox * ); }; //------------------------------------------------------------------------ class ScTpSubTotalGroup1 : public ScTpSubTotalGroup { protected: ScTpSubTotalGroup1( Window* pParent, const SfxItemSet& rArgSet ); public: virtual ~ScTpSubTotalGroup1(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); virtual sal_Bool FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); }; //------------------------------------------------------------------------ class ScTpSubTotalGroup2 : public ScTpSubTotalGroup { protected: ScTpSubTotalGroup2( Window* pParent, const SfxItemSet& rArgSet ); public: virtual ~ScTpSubTotalGroup2(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); virtual sal_Bool FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); }; //------------------------------------------------------------------------ class ScTpSubTotalGroup3 : public ScTpSubTotalGroup { protected: ScTpSubTotalGroup3( Window* pParent, const SfxItemSet& rArgSet ); public: virtual ~ScTpSubTotalGroup3(); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); virtual sal_Bool FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); }; //======================================================================== // Optionen: class ScTpSubTotalOptions : public SfxTabPage { protected: ScTpSubTotalOptions( Window* pParent, const SfxItemSet& rArgSet ); public: virtual ~ScTpSubTotalOptions(); static sal_uInt16* GetRanges (); static SfxTabPage* Create ( Window* pParent, const SfxItemSet& rArgSet ); virtual sal_Bool FillItemSet ( SfxItemSet& rArgSet ); virtual void Reset ( const SfxItemSet& rArgSet ); private: FixedLine aFlGroup; CheckBox aBtnPagebreak; CheckBox aBtnCase; CheckBox aBtnSort; FixedLine aFlSort; RadioButton aBtnAscending; RadioButton aBtnDescending; CheckBox aBtnFormats; CheckBox aBtnUserDef; ListBox aLbUserDef; ScViewData* pViewData; ScDocument* pDoc; const sal_uInt16 nWhichSubTotals; const ScSubTotalParam& rSubTotalData; private: void Init (); void FillUserSortListBox (); // Handler ------------------------ DECL_LINK( CheckHdl, CheckBox * ); }; #endif // SC_TPSORT_HXX
gitter-badger/data-io
src/test/scala/com/zeotap/data/io/source/spark/loader/JSONSparkLoaderTest.scala
package com.zeotap.data.io.source.spark.loader import com.holdenkarau.spark.testing.DataFrameSuiteBase import com.zeotap.data.io.common.test.helpers.DataFrameUtils.assertDataFrameEquality import org.apache.commons.io.FileUtils import org.apache.spark.sql.Row import org.apache.spark.sql.types._ import org.scalatest.FunSuite import java.io.File class JSONSparkLoaderTest extends FunSuite with DataFrameSuiteBase { val inputJsonPath1 : String = "src/test/resources/custom-input-format/yr=2021/mon=07/dt=19" val inputJsonPath2 : String = "src/test/resources/custom-input-format/yr=2021/mon=07/dt=18" override def beforeAll(): Unit = { super.beforeAll() val testSchema = List( StructField("Common_DataPartnerID", IntegerType, true), StructField("DeviceId", StringType, true), StructField("Demographic_Country", StringType, true), StructField("Common_TS", StringType, true) ) val sampleDf = spark.createDataFrame( spark.sparkContext.parallelize(Seq( Row(1,"1","India","1504679559"), Row(1,"2","India","1504679359"), Row(1,"3","Spain","1504679459"), Row(1,"4","India","1504679659") )), StructType(testSchema) ) sampleDf.write.format("json").save(inputJsonPath1) val testSchema2 = List( StructField("Common_DataPartnerID", IntegerType, true), StructField("Demographic_Country", StringType, true), StructField("Common_TS", StringType, true), StructField("DeviceId", StringType, true) ) val sampleDf2 = spark.createDataFrame( spark.sparkContext.parallelize(Seq( Row(1,"France","1504679559","5"), Row(1,"Germany","1504679359","6"), Row(1,"Italy","1504679459","7"), Row(1,"Belgium","1504679659","8") )), StructType(testSchema2) ) sampleDf2.write.option("multiLine", "true").format("json").save(inputJsonPath2) } override def afterAll(): Unit = { super.afterAll() FileUtils.forceDelete(new File(inputJsonPath1)) FileUtils.forceDelete(new File(inputJsonPath2)) } test("testForLoadPath") { val expectedSchema = List( StructField("Common_DataPartnerID", LongType, true), StructField("DeviceId", StringType, true), StructField("Demographic_Country", StringType, true), StructField("Common_TS", StringType, true) ) val expectedDf = spark.createDataFrame( spark.sparkContext.parallelize(Seq( Row(1L,"1","India","1504679559"), Row(1L,"2","India","1504679359"), Row(1L,"3","Spain","1504679459"), Row(1L,"4","India","1504679659") )), StructType(expectedSchema) ) val df = JSONSparkLoader() .load(inputJsonPath1) .buildUnsafe(spark) assertDataFrameEquality(expectedDf, df, "DeviceId") } test("testForMultiLine") { val expectedSchema = List( StructField("Common_DataPartnerID", LongType, true), StructField("Demographic_Country", StringType, true), StructField("Common_TS", StringType, true), StructField("DeviceId", StringType, true) ) val expectedDf = spark.createDataFrame( spark.sparkContext.parallelize(Seq( Row(1L,"France","1504679559","5"), Row(1L,"Germany","1504679359","6"), Row(1L,"Italy","1504679459","7"), Row(1L,"Belgium","1504679659","8") )), StructType(expectedSchema) ) val df = JSONSparkLoader() .multiLine .load(inputJsonPath2) .buildUnsafe(spark) assertDataFrameEquality(expectedDf, df, "DeviceId") } }
axoloto/CaptainAsteroid
NativePlugin/CaptainAsteroid/src/physics/systems/Collide.hpp
#pragma once #include "components/Position.hpp" #include "entityx/System.h" #include "entityx/Event.h" namespace CaptainAsteroidCPP { namespace Sys { class Collide : public entityx::System<Collide> { public: Collide() = default; void update( entityx::EntityManager &entities, entityx::EventManager &events, double dt); private: bool areColliding( const Comp::Position::Handle &pos1, float rad1, const Comp::Position::Handle &pos2, float rad2) const; void handleCollision( entityx::EntityManager &entities, entityx::EventManager &events, entityx::Entity entityA, entityx::Entity entityB); void bounceAsteroids( entityx::Entity asteroidA, entityx::Entity asteroidB); void splitAsteroid( entityx::Entity asteroid); }; }// namespace Sys }// namespace CaptainAsteroidCPP
Vixxth/Origin
Origin/js/plugins/Ours/CGMZ_Achievements.js
/*: * @author <NAME> * @url https://www.caspergaming.com/plugins/cgmz/achievements/ * @target MZ * @base CGMZ_Core * @orderAfter CGMZ_Core * @plugindesc Creates a powerful achievement system * @help * ============================================================================ * For terms and conditions using this plugin in your game please visit: * https://www.caspergaming.com/terms-of-use/ * ============================================================================ * Become a Patron to get access to beta/alpha plugins plus other goodies! * https://www.patreon.com/CasperGamingRPGM * ============================================================================ * Version: 1.1.0 * ---------------------------------------------------------------------------- * Compatibility: Only tested with my CGMZ plugins. * Made for RPG Maker MZ 1.0.0 * ---------------------------------------------------------------------------- * Description: Adds an achievements system including achievement points, * secret achievements, difficulty, and more. Achievements offer automatic * tracking as well as manual unlocking. Achievements can also have rewards * such as items or gold, or even switches/variables. This plugin works well * with CGMZ Toast Manager for pop ups when an achievement is earned. This * plugin also allows for achievements based off of CGMZ Encyclopedia and * Bestiary completion percentage. * ---------------------------------------------------------------------------- * Documentation: * This plugin supports the following plugin commands: * Earn Achievement by Name - This earns the achievement with the name * provided * * Earn Achievement by ID - This earns the achievement with the provided ID. * IDs are the order the achievements are listed in the plugin manager. * * Call Scene - This calls the achievement scene. * * Update - This will not touch existing achievements, but add any new ones to * the achievement data * * Reinitialize - This will reset all achievement progress as if you had * started a new game. * * To call the achievement scene via JavaScript command, use: * SceneManager.push(CGMZ_Scene_Achievements); * * ADDITIONAL NOTES: * CGMZ Toast Manager * This plugin has additional functionality when using CGMZ Toast Manager. * CGMZ Toast allows for the display of a pop-up window on the map screen when * an achievement is earned. Settings for this can be found under the popup * settings for an achievement. * * CGMZ Encyclopedia * This plugin has additional functionality when using CGMZ Encyclopedia. * CGMZ Encyclopedia can be used for achievements, such as "Discover the * entire encyclopedia" * * Date Format Option help: * 0: MM/DD/YYYY (ex: 1/20/2001) * 1: DD/MM/YYYY (ex: 20/1/2001) * 2: YYYY/MM/DD (ex: 2001/1/20) * 3: Month DD, YYYY (ex: January 20, 2001) * 4: DD Month YYYY (ex: 20 January 2001) * 5: Mon. DD, YYYY (ex: Jan 20, 2001) * 6: DD Mon. YYYY (ex: 20 Jan 2001) * 7: MM/DD (ex: 1/20) * 8: DD/MM (ex: 20/1) * * Version History: * Version 1.0 - Initial Release * * Version 1.1.0: * - Fixed crash if there are no achievements * - Added support for CGMZ Professions * * @command Earn Achievement By Name * @text Earn Achievement By Name * @desc Earns an achievement by its name * * @arg name * @type text * @text Achievement Name * @desc The name of the achievement to earn * @default * * @command Earn Achievement By ID * @text Earn Achievement By ID * @desc Earns an achievement by its id * * @arg id * @type number * @text Achievement ID * @desc The id of the achievement to earn. * @default 0 * * @command Call Scene * @text Call Scene * @desc Calls the Achievement Scene * * @arg callScene * @type boolean * @text Call Scene * @desc Calls the Achievement scene if true. No functionality if false. * @default true * * @command Update * @text Update * @desc Adds new achievement data to the plugin. Use for saved games to recognize newly added data * * @arg update * @type boolean * @text Update * @desc Adds new achievement data to the plugin. Will not affect existing achievements * @default true * * @command Reinitialize * @text Reinitialize * @desc Resets all of the achievement data. Use for saved games to recognize changed data * * @arg reinitialize * @type boolean * @text Reinitialize * @desc Resets all of the achievement data as if you started a new game. * @default true * * @param CGMZ Achievements * * @param Achievements * @parent CGMZ Achievements * @type struct<Achievement>[] * @default [] * @desc Achievements * * @param Requires CGMZ Toast Plugin * * @param ShowAchievementPop * @parent Requires CGMZ Toast Plugin * @type boolean * @desc Determines whether a pop window is shown when achievement is earned. * @default false * * @param AchievementEarnedText * @parent Requires CGMZ Toast Plugin * @desc Text to show on first line of achievement pop window * @default Achievement Earned * * @param AchievementEarnedColor * @parent Requires CGMZ Toast Plugin * @type number * @min 0 * @max 31 * @desc Color for text on the first line of achievement pop window. Uses windowskin colors. Range: 0-31 * @default 3 * * @param AchievementEarnedAlignment * @parent Requires CGMZ Toast Plugin * @desc Alignment for pop text. Valid values: left, right, center * @default center * * @param AchievementEarnedSound * @parent Requires CGMZ Toast Plugin * @type file * @dir audio/se/ * @desc Default sound to play when achievement pop-up window pops * @default Applause1 * * @param Achievement Scene Options * * @param ShowSecretAchievements * @parent Achievement Scene Options * @type boolean * @desc Determine whether secret achievements are displayed in the achievement scene * @default false * * @param SecretText * @parent Achievement Scene Options * @desc Text to show as achievement name if secret achievement is displayed in scene * @default ?????? * * @param ShowCriteriaAfterCompletion * @parent Achievement Scene Options * @type boolean * @desc true = still show criteria, false = stop showing criteria after completion. * @default true * * @param DateFormat * @parent Achievement Scene Options * @type number * @min 0 * @max 8 * @desc Number specifying date format. See documentation for help. Valid Range: 0-8 * @default 0 * * @param ScrollSpeed * @parent Achievement Scene Options * @type number * @min 0 * @desc speed at which the achievement window display scrolls (if needed) * @default 1 * * @param ScrollWait * @parent Achievement Scene Options * @type number * @min 0 * @desc amount of time (in frames) to wait before beginning to scroll * @default 300 * * @param Scroll Deceleration * @parent Achievement Scene Options * @type number * @min 0.01 * @max 0.99 * @decimals 2 * @desc Rate of deceleration after letting go of touch * @default 0.92 * * @param Auto Scroll * @parent Achievement Scene Options * @type boolean * @desc Determine if the display window should automatically scroll after so long of no user input * @default true * * @param Text Options * @parent Achievement Scene Options * * @param Reward Text * @parent Text Options * @desc Text to describe Rewards * @default Rewards * * @param Requirement Text * @parent Text Options * @desc Text to describe Requirements * @default Requirements * * @param Difficulty Text * @parent Text Options * @desc Text to describe Difficulty * @default Difficulty * * @param Description Text * @parent Text Options * @desc Text to describe Description * @default Description * * @param Points Text * @parent Text Options * @desc Text to describe Points * @default Points * * @param Unearned Text * @parent Text Options * @desc Text to appear at the top of the achievement window when unearned. * @default Keep playing to earn this achievement * * @param Earned Text * @parent Text Options * @desc Text to appear at the top of the achievement window when earned. * @default Achievement earned on * * @param Earned Count Text * @parent Text Options * @desc Text to appear when counting earned achievements * @default Earned * * @param Currency Unit Space * @parent Text Options * @type boolean * @desc Add a space between the Currency Value and Currency Unit? * @default false * * @param Gauge Colors * @parent Achievement Scene Options * * @param CurrencyGaugeColor1 * @type number * @min 0 * @parent Gauge Colors * @desc Color 1 for currency gauge * @default 6 * * @param CurrencyGaugeColor2 * @type number * @min 0 * @parent Gauge Colors * @desc Color 2 for currency gauge * @default 17 * * @param GenericGaugeColor1 * @type number * @min 0 * @parent Gauge Colors * @desc Color 1 for miscellaneous gauges * @default 28 * * @param GenericGaugeColor2 * @type number * @min 0 * @parent Gauge Colors * @desc Color 2 for miscellaneous gauges * @default 29 * * @param ItemGaugeColor1 * @type number * @min 0 * @parent Gauge Colors * @desc Color 1 for item gauges * @default 22 * * @param ItemGaugeColor2 * @type number * @min 0 * @parent Gauge Colors * @desc Color 2 for item gauges * @default 23 * * @param SwitchVarGaugeColor1 * @type number * @min 0 * @parent Gauge Colors * @desc Color 1 for switch and variable gauges * @default 20 * * @param SwitchVarGaugeColor2 * @type number * @min 0 * @parent Gauge Colors * @desc Color 2 for switch and variable gauges * @default 21 */ /*~struct~Item: * @param Item * @type item * * @param Amount * @type number * @min 1 * @max 99 * @default 1 */ /*~struct~Weapon: * @param Weapon * @type weapon * * @param Amount * @type number * @min 1 * @max 99 * @default 1 */ /*~struct~Armor: * @param Armor * @type armor * * @param Amount * @type number * @min 1 * @max 99 * @default 1 */ /*~struct~Switch: * @param Switch * @type switch * * @param On/Off * @type boolean * @on ON * @off OFF * @default true * * @param Description * @type text * @default * @desc description for this switch */ /*~struct~Variable: * @param Variable * @type variable * * @param Operator * @type text * @desc Valid operators for criteria: < <= > >= = * Valid operators for reward: + - / * % = * @default > * * @param Amount * @type number * @default 0 * @desc Criteria: the value to check the variable against * Reward: the value to award to the variable * * @param Description * @type text * @default * @desc description for this variable */ /*~struct~Requirement: * @param Currency * @type number * @min 0 * @default 0 * @desc Amount of currency needed to earn the achievement * * @param Items * @type struct<Item>[] * @desc Items needed to earn the achievement * @default [] * * @param Weapons * @type struct<Weapon>[] * @desc Weapons needed to earn the achievement * @default [] * * @param Armors * @type struct<Armor>[] * @desc Armors needed to earn the achievement * @default [] * * @param Switches * @type struct<Switch>[] * @desc Switches needed to earn the achievement * @default [] * * @param Variables * @type struct<Variable>[] * @desc Variables needed to earn the achievement * @default [] * * @param Saves * @type number * @min 0 * @default 0 * @desc Save count needed to earn the achievement * * @param Playtime * @type number * @min 0 * @default 0 * @desc Playtime needed to earn the achievement. In frames (60f/1sec) * * @param Steps * @type number * @min 0 * @default 0 * @desc Step count needed to earn the achievement * * @param Battles * @type number * @min 0 * @default 0 * @desc Battle count needed to earn the achievement * * @param Wins * @type number * @min 0 * @default 0 * @desc Win count needed to earn the achievement * * @param Escapes * @type number * @min 0 * @default 0 * @desc Escape count needed to earn the achievement * * @param Achievements Earned * @type number * @min 0 * @default 0 * @desc Earned achievements needed to earn the achievement * * @param Achievement Points * @type number * @min 0 * @default 0 * @desc Achievement points needed to earn the achievement * * @param Encyclopedia Total * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia discovered % needed to earn the achievement * * @param Encyclopedia Bestiary * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia bestiary discovered % needed to earn the achievement * * @param Encyclopedia Items * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia items discovered % needed to earn the achievement * * @param Encyclopedia Armors * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia armors discovered % needed to earn the achievement * * @param Encyclopedia Weapons * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia weapons discovered % needed to earn the achievement * * @param Encyclopedia Skills * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia skills discovered % needed to earn the achievement * * @param Encyclopedia States * @type number * @min 0 * @max 100 * @default 0 * @desc Total Encyclopedia states discovered % needed to earn the achievement * * @param Professions * @type struct<Profession>[] * @default [] * @desc profession requirements */ /*~struct~Reward: * @param Currency * @type number * @default 0 * @desc Amount of currency to award upon achievement earn * * @param Items * @type struct<Item>[] * @desc Items to award upon achievement earn * @default [] * * @param Weapons * @type struct<Weapon>[] * @desc Weapons to award upon achievement earn * @default [] * * @param Armors * @type struct<Armor>[] * @desc Armors to award upon achievement earn * @default [] * * @param Switches * @type struct<Switch>[] * @desc Switches to manipulate upon achievement earn * @default [] * * @param Variables * @type struct<Variable>[] * @desc Variables to manipulate upon achievement earn * @default [] */ /*~struct~Popup: * @param Display? * @type boolean * @default true * @desc Display a pop up window on the map on achievement earn? No popup will display if not using CGMZ Toast Manager * * @param Sound * @type file * @dir audio/se/ * @desc Sound to play on achievement earn * * @param Image * @type file * @dir img/pictures * @desc Image to show on achievement earn. Leave blank to show a text window instead * * @param Color * @type number * @min 0 * @default 0 * @desc Color to show achievement name with in text window upon earn. No effect if showing image instead. */ /*~struct~Achievement: * @param Name * @type text * @desc Name of the achievement * * @param Points * @type number * @min 0 * @default 10 * @desc Amount of points the achievement is worth * * @param Pre Description * @type note * @default "" * @desc Achievement description before it is earned * * @param Post Description * @type note * @default "" * @desc Achievement description after it is earned. Leave blank to always use Pre Description * * @param Difficulty * @type text * @default Easy * @desc Achievement difficulty * * @param Secret * @type boolean * @default false * @desc Is the achievement a secret achievement? * * @param Automatic * @type boolean * @default false * @desc Automatically track the achievement progress? * * @param Rewards * @type struct<Reward> * @default {"Currency":"0","Items":"[]","Weapons":"[]","Armors":"[]","Switches":"[]","Variables":"[]"} * @desc Achievement Rewards * * @param Requirements * @type struct<Requirement> * @default {"Currency":"0","Items":"[]","Weapons":"[]","Armors":"[]","Switches":"[]","Variables":"[]","Saves":"0","Playtime":"0","Steps":"0","Battles":"0","Wins":"0","Escapes":"0","Achievements Earned":"0","Achievement Points":"0","Encyclopedia Total":"0","Encyclopedia Bestiary":"0","Encyclopedia Items":"0","Encyclopedia Armors":"0","Encyclopedia Weapons":"0","Encyclopedia Skills":"0","Encyclopedia States":"0","Professions":"[]"} * @desc Achievement Requirements * * @param Popup * @type struct<Popup> * @default {"Display?":"true","Sound":"Applause1","Image":"","Color":"0"} * @desc Settings for the pop up window if using CGMZ Toast Manager */ /*~struct~Profession: * @param Name * @type text * @desc The name of the profession to track * * @param Level Requirement * @type number * @min 1 * @default 1 * @desc The level requirement for the profession. */ var Imported = Imported || {}; Imported.CGMZ_Achievements = true; var CGMZ = CGMZ || {}; CGMZ.Achievements = CGMZ.Achievements || {}; CGMZ.Versions = CGMZ.Versions || {}; CGMZ.Versions["Achievements"] = "1.1.0"; CGMZ.Achievements.parameters = PluginManager.parameters('CGMZ_Achievements'); CGMZ.Achievements.FileName = CGMZ.Achievements.parameters["File"] || "Achievements.txt"; CGMZ.Achievements.FolderName = CGMZ.Achievements.parameters["Folder"] || "Data"; CGMZ.Achievements.ShowAchievementPop = (CGMZ.Achievements.parameters["ShowAchievementPop"] === "true") ? true : false; CGMZ.Achievements.AchievementEarnedText = CGMZ.Achievements.parameters["AchievementEarnedText"] || "Achievement Earned"; CGMZ.Achievements.AchievementEarnedColor = Number(CGMZ.Achievements.parameters["AchievementEarnedColor"]) || 0; CGMZ.Achievements.AchievementEarnedAlignment = CGMZ.Achievements.parameters["AchievementEarnedAlignment"] || "center"; CGMZ.Achievements.AchievementEarnedSound = CGMZ.Achievements.parameters["AchievementEarnedSound"] || "Applause1"; CGMZ.Achievements.ShowSecretAchievements = (CGMZ.Achievements.parameters["ShowSecretAchievements"] === "true") ? true : false; CGMZ.Achievements.SecretText = CGMZ.Achievements.parameters["SecretText"] || "??????"; CGMZ.Achievements.ShowCriteriaAfterCompletion = (CGMZ.Achievements.parameters["ShowCriteriaAfterCompletion"] === "true") ? true : false; CGMZ.Achievements.DateFormat = Number(CGMZ.Achievements.parameters["DateFormat"]) || 0; CGMZ.Achievements.CurrencyGaugeColor1 = Number(CGMZ.Achievements.parameters["CurrencyGaugeColor1"]) || 6; CGMZ.Achievements.CurrencyGaugeColor2 = Number(CGMZ.Achievements.parameters["CurrencyGaugeColor2"]) || 17; CGMZ.Achievements.GenericGaugeColor1 = Number(CGMZ.Achievements.parameters["GenericGaugeColor1"]) || 28; CGMZ.Achievements.GenericGaugeColor2 = Number(CGMZ.Achievements.parameters["GenericGaugeColor2"]) || 29; CGMZ.Achievements.ItemGaugeColor1 = Number(CGMZ.Achievements.parameters["ItemGaugeColor1"]) || 22; CGMZ.Achievements.ItemGaugeColor2 = Number(CGMZ.Achievements.parameters["ItemGaugeColor2"]) || 23; CGMZ.Achievements.SwitchVarGaugeColor1 = Number(CGMZ.Achievements.parameters["SwitchVarGaugeColor1"]) || 20; CGMZ.Achievements.SwitchVarGaugeColor2 = Number(CGMZ.Achievements.parameters["SwitchVarGaugeColor2"]) || 21; CGMZ.Achievements.ScrollSpeed = Number(CGMZ.Achievements.parameters["ScrollSpeed"]) || 1; CGMZ.Achievements.ScrollWait = Number(CGMZ.Achievements.parameters["ScrollWait"]) || 300; CGMZ.Achievements.ScrollDeceleration = parseFloat(CGMZ.Achievements.parameters["Scroll Deceleration"]) || 0.92; CGMZ.Achievements.AutoScroll = (CGMZ.Achievements.parameters["Auto Scroll"] === "true") ? true : false; CGMZ.Achievements.CurrencyUnitSpace = (CGMZ.Achievements.parameters["Currency Unit Space"] === "true") ? true : false; CGMZ.Achievements.RewardText = CGMZ.Achievements.parameters["Reward Text"] || "Rewards"; CGMZ.Achievements.RequirementText = CGMZ.Achievements.parameters["Requirement Text"] || "Requirements"; CGMZ.Achievements.DifficultyText = CGMZ.Achievements.parameters["Difficulty Text"] || "Difficulty"; CGMZ.Achievements.DescriptionText = CGMZ.Achievements.parameters["Description Text"] || "Description"; CGMZ.Achievements.PointsText = CGMZ.Achievements.parameters["Points Text"] || "Points"; CGMZ.Achievements.UnearnedText = CGMZ.Achievements.parameters["Unearned Text"] || "Keep playing to earn this achievement"; CGMZ.Achievements.EarnedText = CGMZ.Achievements.parameters["Earned Text"] || "Achievement earned on"; CGMZ.Achievements.EarnedCountText = CGMZ.Achievements.parameters["Earned Count Text"] || "Earned"; CGMZ.Achievements.Achievements = JSON.parse(CGMZ.Achievements.parameters["Achievements"]); //============================================================================= // CGMZ_Achievement //----------------------------------------------------------------------------- // Store and manage achievement data. //============================================================================= function CGMZ_Achievement() { this.initialize.apply(this, arguments); } //----------------------------------------------------------------------------- // Initialize Achievement //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.initialize = function(achievementData, id) { this._id = id; this._earned = false; this._earndate = ""; achievementData = JSON.parse(achievementData); this._name = achievementData["Name"]; this._points = Number(achievementData["Points"]); this._difficulty = achievementData["Difficulty"]; this._predesc = JSON.parse(achievementData["Pre Description"].replace(/\\n/g, " \\\\n ")); this._postdesc = JSON.parse(achievementData["Post Description"].replace(/\\n/g, " \\\\n ")); if(this._postdesc === "") { this._postdesc = this._predesc; } this._automatic = (achievementData["Automatic"] === "true") ? true : false; this._secret = (achievementData["Secret"] === "true") ? true : false; const popupData = JSON.parse(achievementData["Popup"]); this._popup = {"display": (popupData["Display?"] === "true") ? true : false, "sound": popupData["Sound"], "image": popupData["Image"], "color": Number(popupData["Color"])}; const rewards = JSON.parse(achievementData["Rewards"]); this._rewards = {}; this._rewards["items"] = []; this._rewards["switches"] = []; this._rewards["variables"] = []; this._rewards["currency"] = Number(rewards["Currency"]); this.initializeItems(this._rewards.items, rewards["Items"], "Item", "Amount", "item"); this.initializeItems(this._rewards.items, rewards["Weapons"], "Weapon", "Amount", "weapon"); this.initializeItems(this._rewards.items, rewards["Armors"], "Armor", "Amount", "armor"); this.initializeSwitches(this._rewards.switches, rewards["Switches"], "Switch", "On/Off", "Description"); this.initializeVariables(this._rewards.variables, rewards["Variables"], "Variable", "Amount", "Description", "Operator"); const requirements = JSON.parse(achievementData["Requirements"]); this._requirements = {}; this._requirements["items"] = []; this._requirements["switches"] = []; this._requirements["variables"] = []; this._requirements["currency"] = Number(requirements["Currency"]); this.initializeItems(this._requirements.items, requirements["Items"], "Item", "Amount", "item"); this.initializeItems(this._requirements.items, requirements["Weapons"], "Weapon", "Amount", "weapon"); this.initializeItems(this._requirements.items, requirements["Armors"], "Armor", "Amount", "armor"); this.initializeSwitches(this._requirements.switches, requirements["Switches"], "Switch", "On/Off", "Description"); this.initializeVariables(this._requirements.variables, requirements["Variables"], "Variable", "Amount", "Description", "Operator"); this._requirements["saves"] = Number(requirements["Saves"]); this._requirements["steps"] = Number(requirements["Steps"]); this._requirements["battles"] = Number(requirements["Battles"]); this._requirements["wins"] = Number(requirements["Wins"]); this._requirements["escapes"] = Number(requirements["Escapes"]); this._requirements["achievetotal"] = Number(requirements["Achievements Earned"]); this._requirements["achievepts"] = Number(requirements["Achievement Points"]); this._requirements["playtime"] = Math.floor(Number(requirements["Playtime"]) / 60); this._requirements["encyclopediatotal"] = Number(requirements["Encyclopedia Total"]); this._requirements["encyclopediabestiary"] = Number(requirements["Encyclopedia Bestiary"]); this._requirements["encyclopediaitems"] = Number(requirements["Encyclopedia Items"]); this._requirements["encyclopediaweapons"] = Number(requirements["Encyclopedia Weapons"]); this._requirements["encyclopediaarmors"] = Number(requirements["Encyclopedia Armors"]); this._requirements["encyclopediaskills"] = Number(requirements["Encyclopedia Skills"]); this._requirements["encyclopediastates"] = Number(requirements["Encyclopedia States"]); this._requirements["professions"] = this.initializeProfessionRequirements(requirements["Professions"]); this.setRewardFlag(this._rewards); this.setRequirementFlag(this._requirements); }; //----------------------------------------------------------------------------- // Initialize Achievement items (requirement or reward) //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.initializeItems = function(itemArray, JSONtext, idText, amtText, type) { if(JSONtext !== "[]") { var parsedItems = JSON.parse(JSONtext); for(var i = 0; i < parsedItems.length; i++) { var obj = JSON.parse(parsedItems[i]); var id = Number(obj[idText]); var amt = Number(obj[amtText]); itemArray.push({"type": type, "id": id, "amt": amt}); } } }; //----------------------------------------------------------------------------- // Initialize Achievement switches (requirement or reward) //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.initializeSwitches = function(switchArray, JSONtext, idText, valueText, descText) { if(JSONtext !== "[]") { var parsedItems = JSON.parse(JSONtext); for(var i = 0; i < parsedItems.length; i++) { var obj = JSON.parse(parsedItems[i]); var id = Number(obj[idText]); var value = (obj[valueText] === "true") ? true : false; var description = obj[descText]; switchArray.push({"value": value, "id": id, "description": description}); } } }; //----------------------------------------------------------------------------- // Initialize Achievement switches (requirement or reward) //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.initializeVariables = function(variableArray, JSONtext, idText, valueText, descText, opText) { if(JSONtext !== "[]") { var parsedItems = JSON.parse(JSONtext); for(let i = 0; i < parsedItems.length; i++) { var obj = JSON.parse(parsedItems[i]); var id = Number(obj[idText]); var value = Number(obj[valueText]); var operator = obj[opText]; var description = obj[descText]; variableArray.push({"value": value, "id": id, "description": description, "operator": operator}); } } }; //----------------------------------------------------------------------------- // Initialize Achievement profession requirements //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.initializeProfessionRequirements = function(reqs) { var required = []; if(Imported.CGMZ_Professions) { reqs = JSON.parse(reqs); for(var i = 0; i < reqs.length; i++) { var reqTemp = JSON.parse(reqs[i]); var req = {}; req.name = reqTemp.Name; req.level = Number(reqTemp["Level Requirement"]); required.push(req); } } return required; }; //----------------------------------------------------------------------------- // Set flag if achievement has rewards //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.setRewardFlag = function(rewards) { this._hasRewards = (rewards.currency > 0 || rewards.items.length > 0 || rewards.switches.length > 0 || rewards.variables.length > 0); }; //----------------------------------------------------------------------------- // Set flag if achievement has requirements //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.setRequirementFlag = function(req) { this._hasRequirements = (req.currency > 0 || req.items.length > 0 || req.switches.length > 0 || req.variables.length > 0 || req.saves > 0 || req.steps > 0 || req.playtime > 0 || req.wins > 0 || req.battles > 0 || req.escapes > 0 || req.achievepts > 0 || req.achievetotal > 0 || req.encyclopediatotal || req.encyclopediaarmors || req.encyclopediabestiary || req.encyclopediaitems || req.encyclopediaweapons || req.encyclopediaskills || req.encyclopediastates || req.professions.length > 0); }; //----------------------------------------------------------------------------- // Get achievement name //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.getName = function() { return this._name; }; //----------------------------------------------------------------------------- // Determine if achievement should be automatically tracked //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.isAutomatic = function() { return this._automatic; }; //----------------------------------------------------------------------------- // Determine if achievement should be automatically tracked //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.isSecret = function() { return this._secret; }; //----------------------------------------------------------------------------- // Determine if achievement should be automatically tracked //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.isEarned = function() { return this._earned; }; //----------------------------------------------------------------------------- // Determine if achievement should be automatically tracked //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.hasRewards = function() { return this._hasRewards; }; //----------------------------------------------------------------------------- // Determine if achievement should be automatically tracked //----------------------------------------------------------------------------- CGMZ_Achievement.prototype.hasRequirements = function() { return this._hasRequirements; }; //============================================================================= // CGMZ //----------------------------------------------------------------------------- // Manage achievement data. Stored as an array of achievement objects. // alias functions: createPluginData //============================================================================= //----------------------------------------------------------------------------- // Alias. Call Initialize for achievements //----------------------------------------------------------------------------- var alias_CGMZ_Achievements_createPluginData = CGMZ_Core.prototype.createPluginData; CGMZ_Core.prototype.createPluginData = function() { alias_CGMZ_Achievements_createPluginData.call(this); this.initializeAchievements(false); }; //----------------------------------------------------------------------------- // Initializes achievements // If new achievements have been added, these will be added onto the end of the // existing array. //----------------------------------------------------------------------------- CGMZ_Core.prototype.initializeAchievements = function(reinitialize) { if(!this._achievements || reinitialize) { this.setupAchievementVariables(); } var id = this._achievements.length + 1; for(let i = 0; i < CGMZ.Achievements.Achievements.length; i++) { var achievement = new CGMZ_Achievement(CGMZ.Achievements.Achievements[i], id); if(!this.getAchievementByName(achievement.getName())) { this.commitAchievement(achievement); id++; } } }; //----------------------------------------------------------------------------- // Set up variables for achievements //----------------------------------------------------------------------------- CGMZ_Core.prototype.setupAchievementVariables = function() { this._achievements = []; this.setupAchievementCriteriaTypeArrays(); this._usingAchievementPoints = false; this._achievetotal = 0; this._achievepts = 0; }; //----------------------------------------------------------------------------- // Commit the achievement to the achievement array // Also store achievement criteria informations //----------------------------------------------------------------------------- CGMZ_Core.prototype.commitAchievement = function(achievement) { this._achievements.push(achievement); if(achievement._points > 0) { this._usingAchievementPoints = true; } if(achievement.hasRequirements() && achievement.isAutomatic()) { const req = achievement._requirements if(req.currency > 0) { this._achievementTypes.currency.push(achievement._id); } if(req.steps > 0) { this._achievementTypes.steps.push(achievement._id); } if(req.saves > 0) { this._achievementTypes.saves.push(achievement._id); } if(req.playtime > 0) { this._achievementTypes.playtime.push(achievement._id); } if(req.battles > 0) { this._achievementTypes.battles.push(achievement._id); } if(req.escapes > 0) { this._achievementTypes.escapes.push(achievement._id); } if(req.wins > 0) { this._achievementTypes.wins.push(achievement._id); } if(req.achievepts > 0) { this._achievementTypes.achievepts.push(achievement._id); } if(req.achievetotal > 0) { this._achievementTypes.achievetotal.push(achievement._id); } if(req.encyclopediatotal > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediabestiary > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediaarmors > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediaitems > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediaweapons > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediaskills > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.encyclopediastates > 0) { this._achievementTypes.encyclopedia.push(achievement._id); } if(req.items.length > 0) { this._achievementTypes.items.push(achievement._id); } if(req.switches.length > 0) { this._achievementTypes.switches.push(achievement._id); } if(req.variables.length > 0) { this._achievementTypes.variables.push(achievement._id); } if(req.professions.length > 0) { this._achievementTypes.professions.push(achievement._id); } } }; //----------------------------------------------------------------------------- // Setup Achievement Type Arrays (for faster checking criteria) //----------------------------------------------------------------------------- CGMZ_Core.prototype.setupAchievementCriteriaTypeArrays = function() { this._achievementTypes = {}; // each property stores IDs of achievements with those criteria this._achievementTypes.currency = []; this._achievementTypes.steps = []; this._achievementTypes.battles = []; this._achievementTypes.escapes = []; this._achievementTypes.wins = []; this._achievementTypes.playtime = []; this._achievementTypes.saves = []; this._achievementTypes.achievetotal = []; this._achievementTypes.achievepts = []; this._achievementTypes.items = []; this._achievementTypes.switches = []; this._achievementTypes.variables = []; this._achievementTypes.encyclopedia = []; this._achievementTypes.professions = []; }; //----------------------------------------------------------------------------- // Earn achievement //----------------------------------------------------------------------------- CGMZ_Core.prototype.earnAchievement = function(id) { let achievement = this.getAchievementByID(id); if(achievement.isEarned()) { return; } achievement._earned = true; this._achievetotal++; this._achievepts += achievement._points; const date = new Date(); const day = date.getDate(); const month = date.getMonth(); const year = date.getFullYear(); achievement._earndate = $cgmzTemp.createDateText(day, month, year, CGMZ.Achievements.DateFormat, "/"); if(achievement.hasRewards()) { this.giveAchievementRewards(achievement._rewards); } if(Imported.CGMZ_ToastManager && CGMZ.Achievements.ShowAchievementPop && achievement._popup.display) { this.setupAchievementToast(achievement); } this.checkAchievementAchieveptsCriteria(); this.checkAchievementAchievetotalCriteria(); }; //----------------------------------------------------------------------------- // Give achievement rewards //----------------------------------------------------------------------------- CGMZ_Core.prototype.giveAchievementRewards = function(reward) { if(reward.currency > 0) { $gameParty.gainGold(reward.currency); } if(reward.items.length > 0) { reward.items.forEach(function(item) { if(item.type === "item") { $gameParty.gainItem($dataItems[item.id], item.amt); } else if(item.type === "weapon") { $gameParty.gainItem($dataWeapons[item.id], item.amt); } else if(item.type === "armor") { $gameParty.gainItem($dataArmors[item.id], item.amt); } }); } if(reward.switches.length > 0) { reward.switches.forEach(function(switchobj) { $gameSwitches.setValue(switchobj.id, switchobj.value); }); } if(reward.variables.length > 0) { var oldValue; reward.variables.forEach(function(variableobj) { try { oldValue = $gameVariables.value(variableobj.id); if(variableobj.operator == '=') { $gameVariables.setValue(variableobj.id, variableobj.value); } else if(variableobj.operator == '+') { $gameVariables.setValue(variableobj.id, oldValue + variableobj.value); } else if(variableobj.operator == '-') { $gameVariables.setValue(variableobj.id, oldValue - variableobj.value); } else if(variableobj.operator == '*') { $gameVariables.setValue(variableobj.id, oldValue * variableobj.value); } else if(variableobj.operator == '/') { $gameVariables.setValue(variableobj.id, oldValue / variableobj.value); } else if(variableobj.operator == '%') { $gameVariables.setValue(variableobj.id, oldValue % variableobj.value); } } catch (e) { $gameVariables.setValue(variableobj.id, 0); } }); } }; //----------------------------------------------------------------------------- // Sets up achievement toast window //----------------------------------------------------------------------------- CGMZ_Core.prototype.setupAchievementToast = function(achievement) { let toastobj = {}; const pop = achievement._popup; const seName = (pop.sound === "") ? CGMZ.Achievements.AchievementEarnedSound : pop.sound; toastobj.SE = {name: seName, pan: 100, pitch: 100, volume: 100}; if(pop.image !== "") { toastobj.isImage = true; toastobj.picture = pop.image; toastobj.showBackground = false; } else { toastobj.isText = true; toastobj.lineOneAlignment = CGMZ.Achievements.AchievementEarnedAlignment; toastobj.lineOne = CGMZ.Achievements.AchievementEarnedText; toastobj.lineOneColor = CGMZ.Achievements.AchievementEarnedColor; toastobj.lineTwoAlignment = CGMZ.Achievements.AchievementEarnedAlignment; toastobj.lineTwo = achievement._name; toastobj.lineTwoColor = pop.color; } $cgmzTemp.createNewToast(toastobj); }; //----------------------------------------------------------------------------- // Check Achievement Criteria and Award if achievement is earned //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementForEarn = function(achievement) { if(!this.needCriteriaCheck(achievement)) { return; } var criteria = achievement._requirements; if(criteria.currency > 0 && $gameParty.gold() < criteria.currency) return; if(criteria.steps > 0 && $gameParty.steps() < criteria.steps) return; if(criteria.saves > 0 && $gameSystem.saveCount() < criteria.saves) return; if(criteria.battles > 0 && $gameSystem.battleCount() < criteria.battles) return; if(criteria.wins > 0 && $gameSystem.winCount() < criteria.wins) return; if(criteria.escapes > 0 && $gameSystem.escapeCount() < criteria.escapes) return; if(criteria.achievepts > 0 && this._achievepts < criteria.achievepts) return; if(criteria.achievetotal > 0 && this._achievetotal < criteria.achievetotal) return; if(criteria.playtime > 0 && $gameSystem.playtime() < criteria.playtime) return; if(criteria.encyclopediatotal > 0 && this.getEncyclopediaTotalPercent() < criteria.encyclopediatotal) return; if(criteria.encyclopediabestiary > 0 && this.getEncyclopediaBestiaryPercent() < criteria.encyclopediabestiary) return; if(criteria.encyclopediaitems > 0 && this.getEncyclopediaItemsPercent() < criteria.encyclopediaitems) return; if(criteria.encyclopediaarmors > 0 && this.getEncyclopediaArmorsPercent() < criteria.encyclopediaarmors) return; if(criteria.encyclopediaweapons > 0 && this.getEncyclopediaWeaponsPercent() < criteria.encyclopediaweapons) return; if(criteria.encyclopediaskills > 0 && this.getEncyclopediaSkillsPercent() < criteria.encyclopediaskills) return; if(criteria.encyclopediastates > 0 && this.getEncyclopediaStatesPercent() < criteria.encyclopediastates) return; for(var i = 0; i < criteria.professions.length; i++) { var profession = $cgmz.getProfession(criteria.professions[i].name); if(profession._level < criteria.professions[i].level) return; } for(let i = 0; i < criteria.items.length; i++) { var item = criteria.items[i]; if(item.type === "item") { if($gameParty.numItems($dataItems[item.id]) < item.amt) return; } else if(item.type === "weapon") { if($gameParty.numItems($dataWeapons[item.id]) < item.amt) return; } else if(item.type === "armor") { if($gameParty.numItems($dataArmors[item.id]) < item.amt) return; } } for(let i = 0; i < criteria.switches.length; i++) { var switchObj = criteria.switches[i]; if(switchObj.value != $gameSwitches.value(switchObj.id)) return; } for(let i = 0; i < criteria.variables.length; i++) { var variableObj = criteria.variables[i]; var gameVariable = $gameVariables.value(variableObj.id); if(variableObj.operator === ">") { if(gameVariable <= variableObj.value) return; } else if(variableObj.operator === ">=") { if(gameVariable < variableObj.value) return; } else if(variableObj.operator === "=") { if(variableObj.value != gameVariable) return; } else if(variableObj.operator === "<=") { if(gameVariable > variableObj.value) return; } else if(variableObj.operator === "<") { if(gameVariable >= variableObj.value) return; } } this.earnAchievement(achievement._id); }; //----------------------------------------------------------------------------- // Determine if need to check for criteria? //----------------------------------------------------------------------------- CGMZ_Core.prototype.needCriteriaCheck = function(achievement) { return !achievement._earned && achievement.hasRequirements(); }; //----------------------------------------------------------------------------- // Check Achievement Currency Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementCurrencyCriteria = function() { this._achievementTypes.currency.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameParty.gold() >= achievement._requirements.currency) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Steps Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementStepsCriteria = function() { this._achievementTypes.steps.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameParty.steps() >= achievement._requirements.steps) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Saves Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementSavesCriteria = function() { this._achievementTypes.saves.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameSystem.saveCount() >= achievement._requirements.saves) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Battles Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementBattlesCriteria = function() { this._achievementTypes.battles.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameSystem.battleCount() >= achievement._requirements.battles) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Wins Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementWinsCriteria = function() { this._achievementTypes.wins.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameSystem.winCount() >= achievement._requirements.wins) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Escapes Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementEscapesCriteria = function() { this._achievementTypes.escapes.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameSystem.escapeCount() >= achievement._requirements.escapes) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Playtime Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementPlaytimeCriteria = function() { this._achievementTypes.playtime.forEach(function(id) { var achievement = this.getAchievementByID(id); if($gameSystem.playtime() >= achievement._requirements.playtime) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Achievepts Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementAchieveptsCriteria = function() { this._achievementTypes.achievepts.forEach(function(id) { var achievement = this.getAchievementByID(id); if($cgmz.countEarnedAchievementPoints() >= achievement._requirements.achievepts) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Achievetotal Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementAchievetotalCriteria = function() { this._achievementTypes.achievetotal.forEach(function(id) { var achievement = this.getAchievementByID(id); if($cgmz.countEarnedAchievements() >= achievement._requirements.achievetotal) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Encyclopedia Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementEncyclopediaCriteria = function() { this._achievementTypes.encyclopedia.forEach(function(id) { var achievement = this.getAchievementByID(id); if(achievement._requirements.encyclopediatotal > 0 && $cgmz.getEncyclopediaTotalPercent() >= achievement._requirements.encyclopediatotal) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediabestiary > 0 && $cgmz.getEncyclopediaBestiaryPercent() >= achievement._requirements.encyclopediabestiary) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediaitems > 0 && $cgmz.getEncyclopediaItemsPercent() >= achievement._requirements.encyclopediaitems) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediaarmors > 0 && $cgmz.getEncyclopediaArmorsPercent() >= achievement._requirements.encyclopediaarmors) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediaweapons > 0 && $cgmz.getEncyclopediaWeaponsPercent() >= achievement._requirements.encyclopediaweapons) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediaskills > 0 && $cgmz.getEncyclopediaSkillsPercent() >= achievement._requirements.encyclopediaskills) { this.checkAchievementForEarn(achievement); } else if(achievement._requirements.encyclopediastates > 0 && $cgmz.getEncyclopediaStatesPercent() >= achievement._requirements.encyclopediastates) { this.checkAchievementForEarn(achievement); } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Items Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementItemsCriteria = function() { this._achievementTypes.items.forEach(function(id) { var achievement = this.getAchievementByID(id); var criteria = achievement._requirements; for(let i = 0; i < criteria.items.length; i++) { var item = criteria.items[i]; if(item.type === "item") { if($gameParty.numItems($dataItems[item.id]) >= item.amt) { this.checkAchievementForEarn(achievement); return; } } else if(item.type === "weapon") { if($gameParty.numItems($dataWeapons[item.id]) >= item.amt) { this.checkAchievementForEarn(achievement); return; } } else if(item.type === "armor") { if($gameParty.numItems($dataArmors[item.id]) >= item.amt) { this.checkAchievementForEarn(achievement); return; } } } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Switches Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementSwitchesCriteria = function() { this._achievementTypes.switches.forEach(function(id) { var achievement = this.getAchievementByID(id); var criteria = achievement._requirements; for(let i = 0; i < criteria.switches.length; i++) { var switchObj = criteria.switches[i]; if(switchObj.value == $gameSwitches.value(switchObj.id)) { this.checkAchievementForEarn(achievement); return; } } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Variables Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementVariablesCriteria = function() { this._achievementTypes.variables.forEach(function(id) { var achievement = this.getAchievementByID(id); var criteria = achievement._requirements; for(let i = 0; i < criteria.variables.length; i++) { var variableObj = criteria.variables[i]; var gameVariable = $gameVariables.value(variableObj.id); if(variableObj.operator === ">") { if(gameVariable > variableObj.value) { this.checkAchievementForEarn(achievement); return; } } else if(variableObj.operator === ">=") { if(gameVariable >= variableObj.value) { this.checkAchievementForEarn(achievement); return; } } else if(variableObj.operator === "=") { if(gameVariable == variableObj.value) { this.checkAchievementForEarn(achievement); return; } } else if(variableObj.operator === "<=") { if(gameVariable <= variableObj.value) { this.checkAchievementForEarn(achievement); return; } } else if(variableObj.operator === "<") { if(gameVariable < variableObj.value) { this.checkAchievementForEarn(achievement); return; } } } }, this); }; //----------------------------------------------------------------------------- // Check Achievement Professions Criteria //----------------------------------------------------------------------------- CGMZ_Core.prototype.checkAchievementProfessionCriteria = function() { this._achievementTypes.professions.forEach(function(id) { var achievement = this.getAchievementByID(id); var needCheck = true; for(var i = 0; i < achievement._requirements.professions.length; i++) { var profession = $cgmz.getProfession(achievement._requirements.professions[i].name); if(achievement._requirements.professions[i].level > profession._level) { needCheck = false; } } if(needCheck) this.checkAchievementForEarn(achievement); }, this); }; //----------------------------------------------------------------------------- // Get achievement array //----------------------------------------------------------------------------- CGMZ_Core.prototype.getAchievements = function() { return this._achievements; }; //----------------------------------------------------------------------------- // Get achievement by ID, returns false if no achievement found //----------------------------------------------------------------------------- CGMZ_Core.prototype.getAchievementByID = function(id) { for(let i = 0; i < this._achievements.length; i++) { if(this._achievements[i]._id === id) { return this._achievements[i]; } } return null; }; //----------------------------------------------------------------------------- // Get achievement by ID, returns false if no achievement found //----------------------------------------------------------------------------- CGMZ_Core.prototype.getAchievementByName = function(achname) { for(let i = 0; i < this._achievements.length; i++) { if(this._achievements[i].getName() === achname) { return this._achievements[i]; } } return null; }; //----------------------------------------------------------------------------- // Get achievement earned count //----------------------------------------------------------------------------- CGMZ_Core.prototype.countEarnedAchievements = function() { return this._achievetotal; }; //----------------------------------------------------------------------------- // Get achievement point count //----------------------------------------------------------------------------- CGMZ_Core.prototype.countEarnedAchievementPoints = function() { return this._achievepts; }; //----------------------------------------------------------------------------- // Achievements have points? //----------------------------------------------------------------------------- CGMZ_Core.prototype.usingAchievementPoints = function() { return this._usingAchievementPoints; }; //============================================================================= // CGMZ_Temp //----------------------------------------------------------------------------- // Adds plugin commands //============================================================================= //----------------------------------------------------------------------------- // Register Plugin Commands //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_registerPluginCommands = CGMZ_Temp.prototype.registerPluginCommands; CGMZ_Temp.prototype.registerPluginCommands = function() { alias_CGMZ_Achievements_registerPluginCommands.call(this); PluginManager.registerCommand("CGMZ_Achievements", "Reinitialize", this.pluginCommandAchievementsReinitialize); PluginManager.registerCommand("CGMZ_Achievements", "Update", this.pluginCommandAchievementsUpdate); PluginManager.registerCommand("CGMZ_Achievements", "Call Scene", this.pluginCommandAchievementsCallScene); PluginManager.registerCommand("CGMZ_Achievements", "Earn Achievement By Name", this.pluginCommandAchievementsEarnByName); PluginManager.registerCommand("CGMZ_Achievements", "Earn Achievement By ID", this.pluginCommandAchievementsEarnByID); }; //----------------------------------------------------------------------------- // Earn an achievement by its name //----------------------------------------------------------------------------- CGMZ_Temp.prototype.pluginCommandAchievementsEarnByName = function(args) { let achievement = $cgmz.getAchievementByName(args.name); if(achievement) { $cgmz.earnAchievement(achievement._id); } }; //----------------------------------------------------------------------------- // Earn an achievement by its ID //----------------------------------------------------------------------------- CGMZ_Temp.prototype.pluginCommandAchievementsEarnByID = function(args) { let achievement = $cgmz.getAchievementByID(Number(args.id)); if(achievement) { $cgmz.earnAchievement(achievement._id); } }; //----------------------------------------------------------------------------- // Reinitialize the achievement data //----------------------------------------------------------------------------- CGMZ_Temp.prototype.pluginCommandAchievementsReinitialize = function(args) { if (args.reinitialize === "true") { $cgmz.initializeAchievements(true); } }; //----------------------------------------------------------------------------- // Update achievement data for new achievements only //----------------------------------------------------------------------------- CGMZ_Temp.prototype.pluginCommandAchievementsUpdate = function(args) { if (args.update === "true") { $cgmz.initializeAchievements(false); } }; //----------------------------------------------------------------------------- // Call the Encyclopedia Scene //----------------------------------------------------------------------------- CGMZ_Temp.prototype.pluginCommandAchievementsCallScene = function(args) { if (args.callScene === "true") { SceneManager.push(CGMZ_Scene_Achievements); } }; //============================================================================= // CGMZ_Scene_Achievements //----------------------------------------------------------------------------- // Scene that controls achievement display windows. // Call with SceneManager.push(CGMZ_Scene_Achievements); //============================================================================= function CGMZ_Scene_Achievements() { this.initialize.apply(this, arguments); } CGMZ_Scene_Achievements.prototype = Object.create(Scene_MenuBase.prototype); CGMZ_Scene_Achievements.prototype.constructor = CGMZ_Scene_Achievements; //----------------------------------------------------------------------------- // Initialize //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.initialize = function() { Scene_MenuBase.prototype.initialize.call(this); }; //----------------------------------------------------------------------------- // Create achievement windows //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.create = function() { Scene_MenuBase.prototype.create.call(this); this.createListWindow(); this.createTotalsWindow(); this.createAchievementWindow(); }; //----------------------------------------------------------------------------- // Create achievement list window //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.createListWindow = function() { const rect = this.listWindowRect(); this._listWindow = new CGMZ_Achievement_Window_List(rect); this._listWindow.setHandler('cancel', this.popScene.bind(this)); this._listWindow.setHandler('ok', this.onListOk.bind(this)); this._listWindow.activate(); this.addWindow(this._listWindow); }; //----------------------------------------------------------------------------- // Get list window rect //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.listWindowRect = function() { const x = 0; const y = this.mainAreaTop(); const width = Graphics.boxWidth / 3; const lines = 1 + ($cgmz.usingAchievementPoints())*1; const height = Graphics.boxHeight - y - this.calcWindowHeight(lines, false); return new Rectangle(x, y, width, height); }; //----------------------------------------------------------------------------- // Create achievement totals window //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.createTotalsWindow = function() { const rect = this.totalsWindowRect(); this._totalsWindow = new CGMZ_Achievement_Window_Totals(rect); this.addWindow(this._totalsWindow); }; //----------------------------------------------------------------------------- // Get totals window rect //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.totalsWindowRect = function() { const x = 0; const y = this._listWindow.y + this._listWindow.height; const width = Graphics.boxWidth / 3; const lines = 1 + ($cgmz.usingAchievementPoints())*1; const height = this.calcWindowHeight(lines, false); return new Rectangle(x, y, width, height); }; //----------------------------------------------------------------------------- // Create achievement window //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.createAchievementWindow = function() { const rect = this.achievementWindowRect(); this._achievementWindow = new CGMZ_Achievement_Window_Display(rect); this._listWindow.setHelpWindow(this._achievementWindow); this._achievementWindow.setHandler('cancel', this.onDisplayCancel.bind(this)); this._achievementWindow.deactivate(); this.addWindow(this._achievementWindow); }; //----------------------------------------------------------------------------- // Get achievement window rect //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.achievementWindowRect = function() { const x = this._listWindow.width; const y = this.mainAreaTop(); const width = Graphics.boxWidth - x; const height = Graphics.boxHeight - y; return new Rectangle(x, y, width, height); }; //----------------------------------------------------------------------------- // On list OK //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.onListOk = function() { this._achievementWindow.activate(); this._listWindow.deactivate(); }; //----------------------------------------------------------------------------- // On display cancel //----------------------------------------------------------------------------- CGMZ_Scene_Achievements.prototype.onDisplayCancel = function() { this._achievementWindow.deactivate(); this._listWindow.activate(); }; //============================================================================= // CGMZ_Achievement_Window_List //----------------------------------------------------------------------------- // Selectable window for choosing an achievement in a list. // Will not show hidden achievements. //============================================================================= function CGMZ_Achievement_Window_List() { this.initialize.apply(this, arguments); } CGMZ_Achievement_Window_List.prototype = Object.create(Window_Selectable.prototype); CGMZ_Achievement_Window_List.prototype.constructor = CGMZ_Achievement_Window_List; //----------------------------------------------------------------------------- // Initialize //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.initialize = function(rect) { Window_Selectable.prototype.initialize.call(this, rect); this.refresh(); this.select(0); }; //----------------------------------------------------------------------------- // Max achievements to be shown //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.maxItems = function() { return this._data ? this._data.length : 1; }; //----------------------------------------------------------------------------- // Currently selected achievement //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.item = function() { return this._data[this.index()]; }; //----------------------------------------------------------------------------- // Determine if current item enabled //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.isCurrentItemEnabled = function() { return true; }; //----------------------------------------------------------------------------- // Determine if achievement is enabled //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.isEnabled = function(achievement) { return (achievement && achievement.isEarned()); }; //----------------------------------------------------------------------------- // Refresh window //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.refresh = function() { this.makeItemList(); this.createContents(); this.drawAllItems(); }; //----------------------------------------------------------------------------- // Make list of achievements //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.makeItemList = function() { this._data = []; var achievements = $cgmz.getAchievements(); achievements.forEach(function(achievement) { if(!achievement.isSecret() || achievement.isEarned() || CGMZ.Achievements.ShowSecretAchievements) { this._data.push(achievement); } }, this); }; //----------------------------------------------------------------------------- // Draw achievement names //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.drawItem = function(index) { const achievement = this._data[index]; let rect = this.itemRect(index); rect.width -= $gameSystem.windowPadding(); this.changePaintOpacity(this.isEnabled(achievement)); if(achievement.isSecret() && !achievement.isEarned()) { this.drawText(CGMZ.Achievements.SecretText, rect.x, rect.y, rect.width, 'left'); } else { this.drawText(achievement.getName(), rect.x, rect.y, rect.width, 'left'); } this.changePaintOpacity(true); }; //----------------------------------------------------------------------------- // Update helper window //----------------------------------------------------------------------------- CGMZ_Achievement_Window_List.prototype.updateHelp = function() { this.setHelpWindowItem(this.item()); }; //============================================================================= // CGMZ_Achievement_Window_Totals //----------------------------------------------------------------------------- // Window displaying total achievements earned and points (if applicable) //============================================================================= function CGMZ_Achievement_Window_Totals() { this.initialize.apply(this, arguments); } CGMZ_Achievement_Window_Totals.prototype = Object.create(Window_Base.prototype); CGMZ_Achievement_Window_Totals.prototype.constructor = CGMZ_Achievement_Window_Totals; //----------------------------------------------------------------------------- // Initialize //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Totals.prototype.initialize = function(rect) { Window_Base.prototype.initialize.call(this, rect); this.refresh(); }; //----------------------------------------------------------------------------- // Refresh //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Totals.prototype.refresh = function() { this.contents.clear(); const width = this.contents.width - $gameSystem.windowPadding() * 2; const earned = $cgmz.countEarnedAchievements(); let text = CGMZ.Achievements.EarnedCountText + ": " + earned; this.drawText(text, 0, 0, width, 'left'); if($cgmz.usingAchievementPoints()) { const points = $cgmz.countEarnedAchievementPoints(); text = CGMZ.Achievements.PointsText + ": " + points; this.drawText(text, 0, this.lineHeight(), width, 'left'); } }; //============================================================================= // CGMZ_Achievement_Window_Display //----------------------------------------------------------------------------- // Window displaying total achievements earned and points (if applicable) //============================================================================= function CGMZ_Achievement_Window_Display() { this.initialize.apply(this, arguments); } CGMZ_Achievement_Window_Display.prototype = Object.create(CGMZ_Window_Scrollable.prototype); CGMZ_Achievement_Window_Display.prototype.constructor = CGMZ_Achievement_Window_Display; //----------------------------------------------------------------------------- // Initialize //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.initialize = function(rect) { const heightMultiplier = 5; // maximum of 5 windows tall of data to scroll CGMZ_Window_Scrollable.prototype.initialize.call(this, rect, heightMultiplier, CGMZ.Achievements.ScrollWait, CGMZ.Achievements.ScrollSpeed, CGMZ.Achievements.AutoScroll, CGMZ.Achievements.ScrollDeceleration); this._achievement = null; }; //----------------------------------------------------------------------------- // Set the achievement to be displayed //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.setItem = function(achievement) { this._achievement = achievement; this.refresh(); }; //----------------------------------------------------------------------------- // Refresh //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.refresh = function() { if(!this._achievement) return; this.setupWindowForNewEntry(); var achievement = this._achievement; var totalWidth = this.contents.width - $gameSystem.windowPadding() * 2; if(achievement.isSecret() && !achievement.isEarned()) { this.drawText(CGMZ.Achievements.SecretText, 0, 0, totalWidth, 'center') } else { this.drawText(achievement.getName(), 0, 0, totalWidth, 'center'); } var descriptor = ""; var x = 0; var lines = 1; if(achievement.isEarned()) { descriptor = CGMZ.Achievements.EarnedText + ": "; this.changeTextColor(ColorManager.systemColor()); this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); x = this.textWidth(descriptor); descriptor = achievement._earndate; this.changeTextColor(ColorManager.normalColor()); this.drawText(descriptor, x, this.lineHeight()*lines, totalWidth-x, 'left'); } else { this.changeTextColor(ColorManager.normalColor()); descriptor = CGMZ.Achievements.UnearnedText; this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); } lines++; if(achievement._difficulty !== "") { descriptor = CGMZ.Achievements.DifficultyText + ": "; this.changeTextColor(ColorManager.systemColor()); this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); x = this.textWidth(descriptor); descriptor = achievement._difficulty; this.changeTextColor(ColorManager.normalColor()); this.drawText(descriptor, x, this.lineHeight()*lines, totalWidth-x, 'left'); lines++; } if(achievement._points > 0) { descriptor = CGMZ.Achievements.PointsText + ": "; this.changeTextColor(ColorManager.systemColor()); this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); x = this.textWidth(descriptor); descriptor = achievement._points; this.changeTextColor(ColorManager.normalColor()); this.drawText(descriptor, x, this.lineHeight()*lines, totalWidth-x, 'left'); lines++; } if(achievement._predesc !== "" && !achievement.isEarned()) { lines = this.drawAchievementDescription(achievement._predesc, lines); } else if(achievement._postdesc !== "" && achievement.isEarned()) { lines = this.drawAchievementDescription(achievement._postdesc, lines); } // Colors used for currency criteria gauges var currencyColor1 = ColorManager.textColor(CGMZ.Achievements.CurrencyGaugeColor1); var currencyColor2 = ColorManager.textColor(CGMZ.Achievements.CurrencyGaugeColor2); // Colors used for item criteria gauges var itemGaugeColor1 = ColorManager.textColor(CGMZ.Achievements.ItemGaugeColor1); var itemGaugeColor2 = ColorManager.textColor(CGMZ.Achievements.ItemGaugeColor2); // Colors used for switch and variable gauges var switchVarGaugeColor1 = ColorManager.textColor(CGMZ.Achievements.SwitchVarGaugeColor1); var switchVarGaugeColor2 = ColorManager.textColor(CGMZ.Achievements.SwitchVarGaugeColor2); // Common colors used for multiple criteria gauges var genericGaugeColor1 = ColorManager.textColor(CGMZ.Achievements.GenericGaugeColor1); var genericGaugeColor2 = ColorManager.textColor(CGMZ.Achievements.GenericGaugeColor2); // Draw criteria if(this.canShowCriteria(achievement)) { var req = achievement._requirements; this.changeTextColor(ColorManager.systemColor()); descriptor = CGMZ.Achievements.RequirementText + ": "; x = this.textWidth(descriptor); this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); this.changeTextColor(ColorManager.normalColor()); if(req.currency > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameParty.gold(), req.currency, currencyColor1, currencyColor2, TextManager.currencyUnit, achievement); x = 0; } if(req.steps > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameParty.steps(), req.steps, genericGaugeColor1, genericGaugeColor2, "Steps", achievement); x = 0; } if(req.saves > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameSystem.saveCount(), req.saves, genericGaugeColor1, genericGaugeColor2, "Saves", achievement); x = 0; } if(req.battles > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameSystem.battleCount(), req.battles, genericGaugeColor1, genericGaugeColor2, "Battles", achievement); x = 0; } if(req.wins > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameSystem.winCount(), req.wins, genericGaugeColor1, genericGaugeColor2, "Wins", achievement); x = 0; } if(req.escapes > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $gameSystem.escapeCount(), req.escapes, genericGaugeColor1, genericGaugeColor2, "Escapes", achievement); x = 0; } if(req.achievetotal > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.countEarnedAchievements(), req.achievetotal, genericGaugeColor1, genericGaugeColor2, "Achievements", achievement); x = 0; } if(req.achievepts > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.countEarnedAchievementPoints(), req.achievepts, genericGaugeColor1, genericGaugeColor2, "Points", achievement); x = 0; } if(req.encyclopediatotal > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaTotalPercent(), req.encyclopediatotal, genericGaugeColor1, genericGaugeColor2, "% Enc. Total", achievement); x = 0; } if(req.encyclopediabestiary > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaBestiaryPercent(), req.encyclopediabestiary, genericGaugeColor1, genericGaugeColor2, "% Enc. Bestiary", achievement); x = 0; } if(req.encyclopediaitems > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaItemsPercent(), req.encyclopediaitems, genericGaugeColor1, genericGaugeColor2, "% Enc. Items", achievement); x = 0; } if(req.encyclopediaweapons > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaWeaponsPercent(), req.encyclopediaweapons, genericGaugeColor1, genericGaugeColor2, "% Enc. Weapons", achievement); x = 0; } if(req.encyclopediaarmors > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaArmorsPercent(), req.encyclopediaarmors, genericGaugeColor1, genericGaugeColor2, "% Enc. Armors", achievement); x = 0; } if(req.encyclopediaskills > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaSkillsPercent(), req.encyclopediaskills, genericGaugeColor1, genericGaugeColor2, "% Enc. Skills", achievement); x = 0; } if(req.encyclopediastates > 0) { lines = this.drawCriteriaProgress(x, lines, totalWidth-x, $cgmz.getEncyclopediaStatesPercent(), req.encyclopediastates, genericGaugeColor1, genericGaugeColor2, "% Enc. States", achievement); x = 0; } for(var i = 0; i < req.professions.length; i++) { var name = req.professions[i].name; var profession = $cgmz.getProfession(name); lines = this.drawCriteriaProgress(x, lines, totalWidth-x, profession._level, req.professions[i].level, genericGaugeColor1, genericGaugeColor2, " " + name + " Level", achievement); x = 0; } if(req.playtime > 0) { var max = $gameSystem.playtime(); if(achievement.isEarned() || max > req.playtime) { max = req.playtime; } var timeArray1 = $cgmzTemp.approximateTimeValue(req.playtime); var timeArray2 = $cgmzTemp.approximateTimeValue(max); var descriptor = timeArray2[0].toString() + " " + timeArray2[1] + " / " + timeArray1[0].toString() + " " + timeArray1[1] + " Played"; this.drawGauge(x, this.lineHeight()*lines, totalWidth-x, genericGaugeColor1, genericGaugeColor2, max, req.playtime, descriptor); lines++; x = 0; } if(req.items.length > 0) { lines = this.drawCriteriaItems(achievement.isEarned(), req.items, x, lines, totalWidth-x, itemGaugeColor1, itemGaugeColor2); x = 0; } if(req.switches.length > 0) { lines = this.drawCriteriaSwitches(achievement.isEarned(), req.switches, x, lines, totalWidth-x, switchVarGaugeColor1, switchVarGaugeColor2); x = 0; } if(req.variables.length > 0) { lines = this.drawCriteriaVariables(achievement.isEarned(), req.variables, x, lines, totalWidth-x, switchVarGaugeColor1, switchVarGaugeColor2); x = 0; } } if(this.canShowRewards(achievement)) { var rew = achievement._rewards; this.changeTextColor(ColorManager.systemColor()); descriptor = CGMZ.Achievements.RewardText + ": "; x = this.textWidth(descriptor); this.drawText(descriptor, 0, this.lineHeight()*lines, totalWidth, 'left'); this.changeTextColor(ColorManager.normalColor()); if(rew.currency > 0) { var space = CGMZ.Achievements.CurrencyUnitSpace ? " " : ""; var descriptor = rew.currency.toString() + space + TextManager.currencyUnit; this.drawText(descriptor, x, this.lineHeight()*lines, totalWidth, 'left'); x = 0; lines++; } if(rew.items.length > 0) { lines = this.drawRewardsItems(rew.items, x, lines, totalWidth-x); x = 0; } if(rew.switches.length > 0) { lines = this.drawRewardsSwitches(rew.switches, x, lines, totalWidth); x = 0; } if(rew.variables.length > 0) { lines = this.drawRewardsSwitches(rew.variables, x, lines, totalWidth); x = 0; } } this._neededHeight = this.lineHeight()*lines; this._neededHeight += $gameSystem.windowPadding()*2; this.checkForScroll(); }; //----------------------------------------------------------------------------- // Draw criteria progress with gauge // Returns the line counter + 1 (this function draws 1 line when called) //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawCriteriaProgress = function(x, lines, width, numerator, denominator, color1, color2, criteriaText, achievement) { const y = this.lineHeight()*lines; let max = numerator; if(achievement.isEarned() || numerator > denominator) { max = denominator; } const descriptor = max.toString() + " / " + denominator.toString() + " " + criteriaText; this.drawGauge(x, y, width, color1, color2, max, denominator, descriptor); return lines + 1; }; //----------------------------------------------------------------------------- // Draw criteria items progress // Returns the line counter + amount of lines drawn via this function //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawCriteriaItems = function(earned, itemArray, x, lines, width, color1, color2) { for(let i = 0; i < itemArray.length; i++) { var y = this.lineHeight()*lines; var criteriaObj = itemArray[i]; var item = this.getItemObject(criteriaObj); var max = $gameParty.numItems(item); var denominator = criteriaObj.amt; if(earned || max > denominator) { max = denominator; } var descriptor = max.toString() + " / " + criteriaObj.amt.toString(); this.drawGauge(x, y, width, color1, color2, max, denominator, descriptor, item); width = this.contents.width - $gameSystem.windowPadding() * 2; x = 0; lines++; } return lines; }; //----------------------------------------------------------------------------- // Draw criteria switches progress // Returns the line counter + amount of lines drawn via this function //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawCriteriaSwitches = function(earned, switchArray, x, lines, width, color1, color2) { for(let i = 0; i < switchArray.length; i++) { var y = this.lineHeight()*lines; var switchObj = switchArray[i]; var switchval = $gameSwitches.value(switchObj.id); var max = (switchval == switchObj.value) ? 1 : 0; if(earned) { max = 1; } var descriptor = switchObj.description + " " + max.toString() + " / 1"; this.drawGauge(x, y, width, color1, color2, max, 1, descriptor); width = this.contents.width - $gameSystem.windowPadding() * 2; x = 0; lines++; } return lines; }; //----------------------------------------------------------------------------- // Draw criteria variables progress // Due to so many options for variables and not really making sense for gauges, // it treats it like a switch. //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawCriteriaVariables = function(earned, variableArray, x, lines, width, color1, color2) { for(let i = 0; i < variableArray.length; i++) { var y = this.lineHeight()*lines; var variableObj = variableArray[i]; var max = 0; var denominator = 1; var descriptor = ""; if(variableObj.operator != ">" && variableObj.operator != ">=") { max = 0 if(earned || $gameVariables.value(variableObj.id) <= variableObj.value) { max = 1; } denominator = 1; descriptor = variableObj.description + " " + max.toString() + " / 1"; } else { denominator = (variableObj.operator === '>') ? variableObj.value+1 : variableObj.value; max = $gameVariables.value(variableObj.id); if(earned || max > denominator) { max = denominator; } descriptor = variableObj.description + " " + max.toString() + " / " + denominator.toString(); } this.drawGauge(x, y, width, color1, color2, max, denominator, descriptor); width = this.contents.width - $gameSystem.windowPadding() * 2; x = 0; lines++; } return lines; }; //----------------------------------------------------------------------------- // Draw item rewards //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawRewardsItems = function(itemArray, x, lines, width) { for(let i = 0; i < itemArray.length; i++) { var y = this.lineHeight()*lines; var rewardObj = itemArray[i]; var item = this.getItemObject(rewardObj); var descriptor = rewardObj.amt.toString() + "x "; this.drawText(descriptor, x, y, width, 'left'); var newWidth = width - this.textWidth(descriptor); x += this.textWidth(descriptor); this.drawItemName(item, x, y, newWidth); width = this.contents.width - $gameSystem.windowPadding() * 2; x = 0; lines++; } return lines; }; //----------------------------------------------------------------------------- // Draw switch rewards //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawRewardsSwitches = function(switchArray, x, lines, width) { if(x != 0) { lines++; x = 0; } for(let i = 0; i < switchArray.length; i++) { var y = this.lineHeight()*lines; var descriptor = switchArray[i].description; this.drawText(descriptor, x, y, width, 'left'); lines++; } return lines; }; //----------------------------------------------------------------------------- // Draw variable rewards //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawRewardsVariables = function(variableArray, x, lines, width) { if(x != 0) { lines++; x = 0; } for(let i = 0; i < variableArray.length; i++) { var y = this.lineHeight()*lines; var descriptor = variableArray[i].description; this.drawText(descriptor, x, y, width, 'left'); lines++; } return lines; }; //----------------------------------------------------------------------------- // Returns the item object from system data type. //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.getItemObject = function(itemObj) { let item = null; if(itemObj.type === "item") { item = $dataItems[itemObj.id]; } else if(itemObj.type === "weapon") { item = $dataWeapons[itemObj.id]; } else if(itemObj.type === "armor") { item = $dataArmors[itemObj.id]; } return item; }; //----------------------------------------------------------------------------- // Determine if the window should show criteria //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.canShowCriteria = function(achievement) { if(achievement.isEarned() && !CGMZ.Achievements.ShowCriteriaAfterCompletion) return false; if(achievement.isSecret() && !achievement.isEarned()) return false; return achievement.hasRequirements(); }; //----------------------------------------------------------------------------- // Determine if the window should show rewards //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.canShowRewards = function(achievement) { if(achievement.isSecret() && !achievement.isEarned()) return false; return achievement.hasRewards(); }; //----------------------------------------------------------------------------- // Draw achievement description - returns y-value of line below last line drawn //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawAchievementDescription = function(description, lines) { var descriptor1 = CGMZ.Achievements.DescriptionText + ": "; var descriptor2 = description.split(" "); var x = 0; var y = this.lineHeight()*lines; this.changeTextColor(ColorManager.systemColor()); this.drawText(descriptor1, x, y, this.contents.width, 'left'); x += this.textWidth(descriptor1); this.changeTextColor(ColorManager.normalColor()); for(var i = 0; i < descriptor2.length; i++) { if(descriptor2[i] === "") continue; if(descriptor2[i] === '\\n') { y += this.lineHeight(); lines++; x = 0; continue; } var tempWidth = this.textWidth(descriptor2[i] + " "); if(tempWidth + x > this.contents.width) { if(tempWidth <= this.contents.width) { y += this.lineHeight(); lines++; x = 0; } } this.drawText(descriptor2[i] + " ", x, y, this.contents.width-x, 'left'); x += tempWidth; } return lines + 1; }; //----------------------------------------------------------------------------- // Draw a gauge //----------------------------------------------------------------------------- CGMZ_Achievement_Window_Display.prototype.drawGauge = function(x, y, width, color1, color2, numerator, denominator, descriptor, item = null) { const gaugeHeight = 12; const gaugeRect = new Rectangle(x, y + this.lineHeight() - gaugeHeight, width, gaugeHeight); const rate = (denominator !== 0) ? numerator/denominator : 0; this.CGMZ_drawGauge(gaugeRect, rate, color1, color2); const padding = 10; this.drawText(descriptor, x + padding, y, width); if(item) { const itemX = x + padding + this.textWidth(descriptor + " "); this.drawItemName(item, itemX, y, width-x); } }; //============================================================================= // Game_Party //----------------------------------------------------------------------------- // Automatic tracking for gold, steps, and items // modified functions: gainGold, increaseSteps, gainItem //============================================================================= //----------------------------------------------------------------------------- // Alias: Check achievements that have currency criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameParty_gainGold = Game_Party.prototype.gainGold; Game_Party.prototype.gainGold = function(amount) { alias_CGMZ_Achievements_GameParty_gainGold.call(this, amount); if(amount > 0) { $cgmz.checkAchievementCurrencyCriteria(); } }; //----------------------------------------------------------------------------- // Alias: Check achievements that have steps criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameParty_increaseSteps = Game_Party.prototype.increaseSteps; Game_Party.prototype.increaseSteps = function() { alias_CGMZ_Achievements_GameParty_increaseSteps.call(this); $cgmz.checkAchievementStepsCriteria(); }; //----------------------------------------------------------------------------- // Alias: Check achievements that have items criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameParty_gainItem = Game_Party.prototype.gainItem; Game_Party.prototype.gainItem = function(item, amount, includeEquip) { alias_CGMZ_Achievements_GameParty_gainItem.call(this, item, amount, includeEquip); if(amount > 0) { $cgmz.checkAchievementItemsCriteria(); } }; //============================================================================= // Game_System //----------------------------------------------------------------------------- // Automatic tracking for battles, wins, escapes, saves // modified functions: onBattleStart, onBattleEscape, onBattleWin, onBeforeSave //============================================================================= //----------------------------------------------------------------------------- // Alias: Check achievements that have battles criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameSystem_onBattleStart = Game_System.prototype.onBattleStart; Game_System.prototype.onBattleStart = function() { alias_CGMZ_Achievements_GameSystem_onBattleStart.call(this); $cgmz.checkAchievementBattlesCriteria(); }; //----------------------------------------------------------------------------- // Alias: Check achievements that have wins criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameSystem_onBattleWin = Game_System.prototype.onBattleWin; Game_System.prototype.onBattleWin = function() { alias_CGMZ_Achievements_GameSystem_onBattleWin.call(this); $cgmz.checkAchievementWinsCriteria(); }; //----------------------------------------------------------------------------- // Alias: Check achievements that have escapes criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameSystem_onBattleEscape = Game_System.prototype.onBattleEscape; Game_System.prototype.onBattleEscape = function() { alias_CGMZ_Achievements_GameSystem_onBattleEscape.call(this); $cgmz.checkAchievementEscapesCriteria(); }; //----------------------------------------------------------------------------- // Alias: Check achievements that have saves criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameSystem_onBeforeSave = Game_System.prototype.onBeforeSave; Game_System.prototype.onBeforeSave = function() { alias_CGMZ_Achievements_GameSystem_onBeforeSave.call(this); $cgmz.checkAchievementSavesCriteria(); }; //============================================================================= // Scene_Map //----------------------------------------------------------------------------- // Automatic tracking for playtime (Using Scene Map so playtime achievements do // not update in battle or mid-scene // modified functions: update //============================================================================= //----------------------------------------------------------------------------- // Alias: Check achievements that have playtime criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_SceneMap_update = Scene_Map.prototype.update; Scene_Map.prototype.update = function() { alias_CGMZ_Achievements_SceneMap_update.call(this); if(Graphics.frameCount % 60 == 0) { $cgmz.checkAchievementPlaytimeCriteria(); } }; //============================================================================= // Game_Switches //----------------------------------------------------------------------------- // Automatic tracking for switches // modified functions: onChange //============================================================================= //----------------------------------------------------------------------------- // Alias: Check achievements that have switch criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameSwitches_onChange = Game_Switches.prototype.onChange; Game_Switches.prototype.onChange = function() { alias_CGMZ_Achievements_GameSwitches_onChange.call(this); $cgmz.checkAchievementSwitchesCriteria(); }; //============================================================================= // Game_Variables //----------------------------------------------------------------------------- // Automatic tracking for variables // modified functions: onChange //============================================================================= //----------------------------------------------------------------------------- // Alias: Check achievements that have variable criteria //----------------------------------------------------------------------------- const alias_CGMZ_Achievements_GameVariables_onChange = Game_Variables.prototype.onChange; Game_Variables.prototype.onChange = function() { alias_CGMZ_Achievements_GameVariables_onChange.call(this); $cgmz.checkAchievementVariablesCriteria(); };
SaitoTsutomu/leetcode
codes_/0461_Hamming_Distance.py
<reponame>SaitoTsutomu/leetcode # %% [461. Hamming Distance](https://leetcode.com/problems/hamming-distance/) class Solution: def hammingDistance(self, x: int, y: int) -> int: return sum(i != j for i, j in zip(bin(x)[2:].zfill(31), bin(y)[2:].zfill(31)))
mhazankin/vic
vendor/github.com/go-openapi/runtime/bytestream.go
// Copyright 2015 go-swagger maintainers // // 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 runtime import ( "bytes" "encoding" "errors" "fmt" "io" "reflect" ) // ByteStreamConsumer creates a consmer for byte streams, // takes a Writer/BinaryUnmarshaler interface or binary slice by reference, // and reads from the provided reader func ByteStreamConsumer() Consumer { return ConsumerFunc(func(reader io.Reader, data interface{}) error { if reader == nil { return errors.New("ByteStreamConsumer requires a reader") // early exit } if wrtr, ok := data.(io.Writer); ok { _, err := io.Copy(wrtr, reader) return err } buf := new(bytes.Buffer) _, err := buf.ReadFrom(reader) if err != nil { return err } b := buf.Bytes() if bu, ok := data.(encoding.BinaryUnmarshaler); ok { return bu.UnmarshalBinary(b) } if t := reflect.TypeOf(data); data != nil && t.Kind() == reflect.Ptr { v := reflect.Indirect(reflect.ValueOf(data)) if t = v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { v.SetBytes(b) return nil } } return fmt.Errorf("%v (%T) is not supported by the ByteStreamConsumer, %s", data, data, "can be resolved by supporting Writer/BinaryUnmarshaler interface") }) } // ByteStreamProducer creates a producer for byte streams, // takes a Reader/BinaryMarshaler interface or binary slice, // and writes to a writer (essentially a pipe) func ByteStreamProducer() Producer { return ProducerFunc(func(writer io.Writer, data interface{}) error { if writer == nil { return errors.New("ByteStreamProducer requires a writer") // early exit } if rdr, ok := data.(io.Reader); ok { _, err := io.Copy(writer, rdr) return err } if bm, ok := data.(encoding.BinaryMarshaler); ok { bytes, err := bm.MarshalBinary() if err != nil { return err } _, err = writer.Write(bytes) return err } if data != nil { v := reflect.Indirect(reflect.ValueOf(data)) if t := v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { _, err := writer.Write(v.Bytes()) return err } } return fmt.Errorf("%v (%T) is not supported by the ByteStreamProducer, %s", data, data, "can be resolved by supporting Reader/BinaryMarshaler interface") }) }
WeilerWebServices/Kivy
p4a-pygame-bootstrap-components/pygame_bootstrap_jni/sdl_gfx/SDL_gfxBlitFunc.h
/* SDL_gfxBlitFunc: custom blitters (part of SDL_gfx library) LGPL (c) <NAME> */ #ifndef _SDL_gfxBlitFunc_h #define _SDL_gfxBlitFunc_h /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <stdlib.h> #include <SDL.h> #include <SDL_video.h> /* -------- Prototypes */ #ifdef WIN32 # ifdef DLL_EXPORT # define SDL_GFXBLITFUNC_SCOPE __declspec(dllexport) # else # ifdef LIBSDL_GFX_DLL_IMPORT # define SDL_GFXBLITFUNC_SCOPE __declspec(dllimport) # endif # endif #endif #ifndef SDL_GFXBLITFUNC_SCOPE # define SDL_GFXBLITFUNC_SCOPE extern #endif SDL_GFXBLITFUNC_SCOPE int SDL_gfxBlitRGBA(SDL_Surface * src, SDL_Rect * srcrect, SDL_Surface * dst, SDL_Rect * dstrect); SDL_GFXBLITFUNC_SCOPE int SDL_gfxSetAlpha(SDL_Surface * src, Uint8 a); SDL_GFXBLITFUNC_SCOPE int SDL_gfxMultiplyAlpha(SDL_Surface * src, Uint8 a); /* -------- Macros */ /* Define SDL macros locally as a substitute for an #include "SDL_blit.h", */ /* which doesn't work since the include file doesn't get installed. */ /*! \brief The structure passed to the low level blit functions. */ typedef struct { Uint8 *s_pixels; int s_width; int s_height; int s_skip; Uint8 *d_pixels; int d_width; int d_height; int d_skip; void *aux_data; SDL_PixelFormat *src; Uint8 *table; SDL_PixelFormat *dst; } SDL_gfxBlitInfo; /*! \brief Unwrap RGBA values from a pixel using mask, shift and loss for surface. */ #define GFX_RGBA_FROM_PIXEL(pixel, fmt, r, g, b, a) \ { \ r = ((pixel&fmt->Rmask)>>fmt->Rshift)<<fmt->Rloss; \ g = ((pixel&fmt->Gmask)>>fmt->Gshift)<<fmt->Gloss; \ b = ((pixel&fmt->Bmask)>>fmt->Bshift)<<fmt->Bloss; \ a = ((pixel&fmt->Amask)>>fmt->Ashift)<<fmt->Aloss; \ } /*! \brief Disassemble buffer pointer into a pixel and separate RGBA values. */ #define GFX_DISEMBLE_RGBA(buf, bpp, fmt, pixel, r, g, b, a) \ do { \ pixel = *((Uint32 *)(buf)); \ GFX_RGBA_FROM_PIXEL(pixel, fmt, r, g, b, a); \ pixel &= ~fmt->Amask; \ } while(0) /*! \brief Wrap a pixel from RGBA values using mask, shift and loss for surface. */ #define GFX_PIXEL_FROM_RGBA(pixel, fmt, r, g, b, a) \ { \ pixel = ((r>>fmt->Rloss)<<fmt->Rshift)| \ ((g>>fmt->Gloss)<<fmt->Gshift)| \ ((b>>fmt->Bloss)<<fmt->Bshift)| \ ((a<<fmt->Aloss)<<fmt->Ashift); \ } /*! \brief Assemble pixel into buffer pointer from separate RGBA values. */ #define GFX_ASSEMBLE_RGBA(buf, bpp, fmt, r, g, b, a) \ { \ Uint32 pixel; \ \ GFX_PIXEL_FROM_RGBA(pixel, fmt, r, g, b, a); \ *((Uint32 *)(buf)) = pixel; \ } /*! \brief Blend the RGB values of two pixels based on a source alpha value. */ #define GFX_ALPHA_BLEND(sR, sG, sB, A, dR, dG, dB) \ do { \ dR = (((sR-dR)*(A))/255)+dR; \ dG = (((sG-dG)*(A))/255)+dG; \ dB = (((sB-dB)*(A))/255)+dB; \ } while(0) /*! \brief 4-times unrolled DUFFs loop. This is a very useful loop for optimizing blitters. */ #define GFX_DUFFS_LOOP4(pixel_copy_increment, width) \ { int n = (width+3)/4; \ switch (width & 3) { \ case 0: do { pixel_copy_increment; \ case 3: pixel_copy_increment; \ case 2: pixel_copy_increment; \ case 1: pixel_copy_increment; \ } while ( --n > 0 ); \ } \ } /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #endif /* _SDL_gfxBlitFunc_h */
wynjauu/1.11.1-qtt-flink
flink-formats/flink-protobuf/src/main/java/org/apache/flink/formats/protobuf/messageutils/ProtobufFieldConverterUtil.java
<reponame>wynjauu/1.11.1-qtt-flink package org.apache.flink.formats.protobuf.messageutils; import org.apache.flink.api.java.typeutils.RowTypeInfo; import org.apache.flink.formats.protobuf.exception.ProtobufException; import org.apache.flink.formats.protobuf.typeutils.MessageVersion; /** * @author liufangliang * @date 2020/6/10 8:10 PM */ public class ProtobufFieldConverterUtil { /** * initialize An protobuf schema converter (as a {@link ProtobufFieldConverter} ) * for the {@link MessageVersion } defined by customer. * * @return Subclass of {@link ProtobufFieldConverter} */ public static ProtobufFieldConverter genericFieldConverter(String messageVersion, RowTypeInfo rowTypeInfo, boolean ignoreParseErrors) { switch (MessageVersion.of(messageVersion)) { case MESSAGE_V2: return new NewMessageV3FieldConverter(rowTypeInfo, ignoreParseErrors); case MESSAGE_V1: return new MessageFieldConverter(rowTypeInfo, ignoreParseErrors); case MESSAGE_V1_ETL: return new MessageFieldEtlConverter(rowTypeInfo, ignoreParseErrors); case MESSAGE_V1_DATAX: return new MessageFieldDataXConverter(rowTypeInfo, ignoreParseErrors); case MESSAGE_SIDECAR_LOG: return new MessageSidecarLogFieldConverter(rowTypeInfo, ignoreParseErrors); default: throw new ProtobufException(String.format("No suitable protobuf schema parser found for '%s' ", messageVersion)); } } }
RathmoreChaos/intficpy
tests/verbs/test_get_all_drop_all.py
from ..helpers import IFPTestCase from intficpy.thing_base import Thing class TestInventoryVerbs(IFPTestCase): def test_get_all_drop(self): item1 = Thing(self.game, "miracle") item2 = Thing(self.game, "wonder") item1.invItem = True item2.invItem = True item3 = item2.copyThing() item1.makeKnown(self.me) item3.makeKnown(self.me) self.start_room.addThing(item1) self.start_room.addThing(item3) self.me.addThing(item2) self.assertNotIn(item1.ix, self.me.contains) self.assertIn(item2.ix, self.me.contains) self.assertNotIn(item3, self.me.contains[item2.ix]) self.game.turnMain("take all") getall_msg = self.app.print_stack.pop() self.assertIn( item1.ix, self.me.contains, f"Item not added to inv with get all. Msg: '{getall_msg}'", ) self.assertIn(item1, self.me.contains[item1.ix]) self.assertIn( item2.ix, self.me.contains, f"Item not added to inv with get all. Msg: '{getall_msg}'", ) self.assertIn(item2, self.me.contains[item2.ix]) self.game.turnMain("take all") getall_msg = self.app.print_stack.pop() self.assertEqual(getall_msg, "There are no obvious items here to take. ") def test_drop_all(self): item1 = Thing(self.game, "miracle") item2 = Thing(self.game, "wonder") item1.invItem = True item2.invItem = True item1.makeKnown(self.me) item2.makeKnown(self.me) self.me.addThing(item1) self.me.addThing(item2) self.assertIs( self.me.location, self.start_room, "This test needs the Player to be in the start room", ) self.game.turnMain("drop all") dropall_msg = self.app.print_stack.pop() self.assertEqual( len(self.me.contains), 0, f"Expected empty inv, but found {self.me.contains}", ) self.assertIn(item1.ix, self.start_room.contains) self.assertIn(item1, self.start_room.contains[item1.ix]) self.assertIn(item2.ix, self.start_room.contains) self.assertIn(item2, self.start_room.contains[item2.ix]) self.game.turnMain("drop all") dropall_msg = self.app.print_stack.pop() self.assertEqual(dropall_msg, "Your inventory is empty. ")
cramforce/linkedom
cjs/html/html-video-element.js
<reponame>cramforce/linkedom 'use strict'; const {HTMLElement} = require('./html-element.js'); /** * @implements globalThis.HTMLVideoElement */ class HTMLVideoElement extends HTMLElement { constructor(ownerDocument, localName = 'video') { super(ownerDocument, localName); } } exports.HTMLVideoElement = HTMLVideoElement
SuLab/WikiGenomesBase
scripts/alias_fix.py
<reponame>SuLab/WikiGenomesBase import WD_Utils from wikidataintegrator import wdi_core, wdi_login import getpass username = input("Username: ") password = <PASSWORD>("Password: ") count = 0 sparql = WD_Utils.WDSparqlQueries() login = wdi_login.WDLogin(user=username, pwd=password) def write2wikidata(qid): print("%s" % (qid)) item = wdi_core.WDItemEngine(wd_item_id=qid) aliases = [alias for alias in item.get_aliases() if len(alias) > 1] item.set_aliases(aliases, append=False) item.write(login=login) data = sparql.get_single_alias_genes() for gene in data: qid = gene["gene"]["value"].split("/")[-1] write2wikidata(qid)
ezLeaks/backdoored
com/google/api/client/auth/oauth/OAuthRsaSigner.java
package com.google.api.client.auth.oauth; import com.google.api.client.util.*; import java.security.*; @Beta public final class OAuthRsaSigner implements OAuthSigner { public PrivateKey privateKey; public OAuthRsaSigner() { super(); } @Override public String getSignatureMethod() { return "RSA-SHA1"; } @Override public String computeSignature(final String a1) throws GeneralSecurityException { final Signature v1 = SecurityUtils.getSha1WithRsaSignatureAlgorithm(); final byte[] v2 = StringUtils.getBytesUtf8(a1); return Base64.encodeBase64String(SecurityUtils.sign(v1, this.privateKey, v2)); } }
vaticorp/ssabirov
chapter_001/src/main/java/ru/job4j/calculator/Calculator.java
<reponame>vaticorp/ssabirov package ru.job4j.calculator; /** *This is my first simple calculator. *@author <NAME> *@since 23.01.2017 22:09 *@version 1 */ public class Calculator { private double result; /** *Method sumirzes two numbers. *@param first number. *@param second number. */ public void add(double first, double second) { this.result = first + second; } /** *Method subtracts two numbers. *@param first number. *@param second number. */ public void subtract(double first, double second) { this.result = first - second; } /** * Method setting result. * @param result */ public void setResult(double result) { this.result = result; } /** *Method divides two numbers. *@param first number. *@param second number. */ public void div(double first, double second) { this.result = first / second; } /** *Method multiples two numbers. *@param first number. *@param second number. */ public void multiple(double first, double second) { this.result = first * second; } /** *Method gets result. *@return current result. */ public double getResult() { return this.result; } }
amcp/janusgraph
janusgraph-core/src/main/java/org/janusgraph/graphdb/database/serialize/attribute/EnumSerializer.java
<gh_stars>1000+ // Copyright 2017 JanusGraph Authors // // 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.janusgraph.graphdb.database.serialize.attribute; import com.google.common.base.Preconditions; import org.janusgraph.diskstorage.ScanBuffer; import org.janusgraph.diskstorage.WriteBuffer; import org.janusgraph.graphdb.database.idhandling.VariableLong; import org.janusgraph.graphdb.database.serialize.OrderPreservingSerializer; public class EnumSerializer<E extends Enum> implements OrderPreservingSerializer<E> { private static final long serialVersionUID = 117423419862504186L; private final Class<E> datatype; private final IntegerSerializer ints = new IntegerSerializer(); public EnumSerializer(Class<E> datatype) { Preconditions.checkArgument(datatype != null && datatype.isEnum()); this.datatype = datatype; } private E getValue(long ordinal) { E[] values = datatype.getEnumConstants(); Preconditions.checkArgument(ordinal>=0 && ordinal<values.length,"Invalid ordinal number (max %s): %s",values.length,ordinal); return values[(int)ordinal]; } @Override public E read(ScanBuffer buffer) { return getValue(VariableLong.readPositive(buffer)); } @Override public void write(WriteBuffer out, E object) { VariableLong.writePositive(out, object.ordinal()); } @Override public E readByteOrder(ScanBuffer buffer) { return getValue(ints.readByteOrder(buffer)); } @Override public void writeByteOrder(WriteBuffer buffer, E attribute) { ints.writeByteOrder(buffer,attribute.ordinal()); } }
cjsteel/python3-venv-ansible-2.10.5
lib/python3.8/site-packages/ansible_collections/f5networks/f5_modules/plugins/modules/bigip_asm_policy_signature_set.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: bigip_asm_policy_signature_set short_description: Manages Signature Sets on an ASM policy description: - Manages Signature Sets on an ASM policy. version_added: "1.0.0" options: name: description: - Specifies the name of the signature sets to apply on, or remove from, the ASM policy. - Apart from built-in signature sets that ship with the device, you can create and use custom signature sets. - When C(All Response Signatures), configures all signatures in the attack signature pool that can review responses. - When C(All Signatures), configures all attack signatures in the attack signature pool. - When C(Apache Struts Signatures), configures signatures that target attacks against the Apache Struts web servers. Only available in version 13.x and later. - When C(Apache Tomcat Signatures), configures signatures that target attacks against the Apache Tomcat web servers. Only available in version 13.x and later. - When C(Cisco Signatures), configures signatures that target attacks against Cisco systems. Only available in version 13.x and later. - When C(Command Execution Signatures), configures signatures involving attacks perpetrated by executing commands. - When C(Cross Site Scripting Signatures), configures signatures that target attacks caused by cross-site scripting techniques. - When C(Directory Indexing Signatures), configures signatures targeting attacks that browse directory listings. - When C(Generic Detection Signatures), configures signatures targeting well-known or common web and application attacks. - When C(HTTP Response Splitting Signatures), configures signatures targeting attacks that take advantage of responses for which input values have not been sanitized. - When C(High Accuracy Detection Evasion Signatures), configures signatures with a high level of accuracy that produce few false positives when identifying evasion attacks. Only available in version 13.x and later. - When C(High Accuracy Signatures), configures signatures with a high level of accuracy that produce few false positives when identifying evasion attacks. - When C(IIS and Windows Signatures), configures signatures that target attacks against IIS and Windows-based systems. Only available in version 13.x and later. - When C(Information Leakage Signatures), configures signatures targeting attacks that are looking for system data or debugging information that shows where the system is vulnerable to attack. - When C(Java Servlets/JSP Signatures), configures signatures that target attacks against Java Servlets and Java Server Pages (JSP) based applications. Only available in version 13.x and later. - When C(Low Accuracy Signatures), configures signatures that may result in more false positives when identifying attacks. - When C(Medium Accuracy Signatures), configures signatures with a medium level of accuracy when identifying attacks. - When C(OS Command Injection Signatures), configures signatures targeting attacks that attempt to run system level commands through a vulnerable application. - When C(OWA Signatures), configures signatures that target attacks against the Microsoft Outlook Web Access (OWA) application. - When C(Other Application Attacks Signatures), configures signatures targeting miscellaneous attacks, including session fixation, local file access, injection attempts, header tampering and so on, affecting many applications. - When C(Path Traversal Signatures), configures signatures targeting attacks that attempt to access files and directories that are stored outside the web root folder. - When C(Predictable Resource Location Signatures), configures signatures targeting attacks that attempt to uncover hidden website content and functionality by forceful browsing, or by directory and file enumeration. - When C(Remote File Include Signatures), configures signatures targeting attacks that attempt to exploit a remote file include vulnerability that could enable a remote attacker to execute arbitrary commands on the server hosting the application. - When C(SQL Injection Signatures), configures signatures targeting attacks that attempt to insert (inject) a SQL query using the input data from a client to an application. - When C(Server Side Code Injection Signatures), configures signatures targeting code injection attacks on the server side. - When C(WebSphere signatures), configures signatures targeting attacks on many computing platforms that are integrated using WebSphere, including general database, Microsoft Windows, IIS, Microsoft SQL Server, Apache, Oracle, Unix/Linux, IBM DB2, PostgreSQL, and XML. - When C(XPath Injection Signatures), configures signatures targeting attacks that attempt to gain access to data structures or bypass permissions when a web site uses user-supplied information to construct XPath queries for XML data. type: str required: True policy_name: description: - Specifies the name of an existing ASM policy to add or remove signature sets to. type: str required: True alarm: description: - Specifies if the security policy logs the request data in the Statistics screen when a request matches a signature that is included in the signature set. type: bool block: description: - Effective when the security policy enforcement mode is Blocking. - Determines how the system treats requests that match a signature included in the signature set. - When C(yes), the system blocks all requests that match a signature, and provides the client with a support ID number. - When C(no), the system accepts those requests. type: bool learn: description: - Specifies if the security policy learns all requests that match a signature that is included in the signature set. type: bool state: description: - When C(present), ensures the resource exists. - When C(absent), ensures the resource is removed. type: str default: present choices: - present - absent partition: description: - This parameter is only used when identifying an ASM policy. type: str default: Common notes: - This module is primarily used as a component of configuring an ASM policy in the Ansible Galaxy ASM Policy Role. extends_documentation_fragment: f5networks.f5_modules.f5 author: - <NAME> (@wojtek0806) ''' EXAMPLES = r''' - name: Add Signature Set to ASM Policy bigip_asm_policy_signature_set: name: IIS and Windows Signatures policy_name: FooPolicy provider: password: <PASSWORD> server: lb.mydomain.com user: admin delegate_to: localhost - name: Remove Signature Set to ASM Policy bigip_asm_policy_signature_set: name: IIS and Windows Signatures policy_name: FooPolicy state: absent provider: password: <PASSWORD> server: lb.mydomain.com user: admin delegate_to: localhost ''' RETURN = r''' policy_name: description: The name of the ASM policy returned: changed type: str sample: FooPolicy name: description: The name of the Signature Set added/removed on an ASM policy. returned: changed type: str sample: Cisco Signatures alarm: description: Specifies whether the security policy logs the request data in the Statistics screen. returned: changed type: bool sample: yes block: description: Determines how the system treats requests that match a signature included in the signature set. returned: changed type: bool sample: no learn: description: Specifies if the policy learns all requests that match a signature that is included in the signature set. returned: changed type: bool sample: yes ''' from datetime import datetime from ansible.module_utils.basic import ( AnsibleModule, env_fallback ) from distutils.version import LooseVersion from ..module_utils.bigip import F5RestClient from ..module_utils.common import ( F5ModuleError, AnsibleF5Parameters, f5_argument_spec, flatten_boolean ) from ..module_utils.icontrol import ( module_provisioned, tmos_version ) from ..module_utils.teem import send_teem class Parameters(AnsibleF5Parameters): api_map = { } api_attributes = [ 'alarm', 'block', 'learn', ] returnables = [ 'policy_name', 'name', 'alarm', 'block', 'learn', ] updatables = [ 'alarm', 'block', 'learn', ] class ApiParameters(Parameters): pass class ModuleParameters(Parameters): @property def alarm(self): result = flatten_boolean(self._values['alarm']) if result: if result == 'yes': return True return False @property def block(self): result = flatten_boolean(self._values['block']) if result: if result == 'yes': return True return False @property def learn(self): result = flatten_boolean(self._values['learn']) if result: if result == 'yes': return True return False def _signature_set_exists_on_device(self, name): uri = "https://{0}:{1}/mgmt/tm/asm/signature-sets".format( self.client.provider['server'], self.client.provider['server_port'], ) query = "?$select=name" resp = self.client.api.get(uri + query) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]: raise F5ModuleError(resp.content) if any(p['name'] == name for p in response['items']): return True return False @property def name(self): if self._values['name'] is None: return None version = tmos_version(self.client) if LooseVersion(version) < LooseVersion('13.0.0'): name_list = [ 'All Response Signatures', 'All Signatures', 'Command Execution Signatures', 'Cross Site Scripting Signatures', 'Directory Indexing Signatures', 'Generic Detection Signatures', 'HTTP Response Splitting Signatures', 'High Accuracy Signatures', 'Information Leakage Signatures', 'Low Accuracy Signatures', 'Medium Accuracy Signatures', 'OS Command Injection Signatures', 'OWA Signatures', 'Other Application Attacks Signatures', 'Path Traversal Signatures', 'Predictable Resource Location Signatures', 'Remote File Include Signatures', 'SQL Injection Signatures', 'Server Side Code Injection Signatures', 'WebSphere signatures', 'XPath Injection Signatures' ] else: name_list = [ 'All Response Signatures', 'All Signatures', 'Apache Struts Signatures', 'Apache Tomcat Signatures', 'Cisco Signatures', 'Command Execution Signatures', 'Cross Site Scripting Signatures', 'Directory Indexing Signatures', 'Generic Detection Signatures', 'HTTP Response Splitting Signatures', 'High Accuracy Detection Evasion Signatures', 'High Accuracy Signatures', 'IIS and Windows Signatures', 'Information Leakage Signatures', 'Java Servlets/JSP Signatures', 'Low Accuracy Signatures', 'Medium Accuracy Signatures', 'OS Command Injection Signatures', 'OWA Signatures', 'Other Application Attacks Signatures', 'Path Traversal Signatures', 'Predictable Resource Location Signatures', 'Remote File Include Signatures', 'SQL Injection Signatures', 'Server Side Code Injection Signatures', 'WebSphere signatures', 'XPath Injection Signatures' ] if self._values['name'] in name_list: return self._values['name'] if self._signature_set_exists_on_device(self._values['name']): return self._values['name'] raise F5ModuleError( "The specified signature {0} set does not exist.".format( self._values['name'] ) ) class Changes(Parameters): def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) except Exception: raise return result class UsableChanges(Changes): pass class ReportableChanges(Changes): @property def alarm(self): return flatten_boolean(self._values['alarm']) @property def learn(self): return flatten_boolean(self._values['learn']) @property def block(self): return flatten_boolean(self._values['block']) class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) def __default(self, param): attr1 = getattr(self.want, param) try: attr2 = getattr(self.have, param) if attr1 != attr2: return attr1 except AttributeError: return attr1 class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = F5RestClient(**self.module.params) self.want = ModuleParameters(params=self.module.params, client=self.client) self.have = ApiParameters() self.changes = UsableChanges() def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = UsableChanges(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) return True return False def _announce_deprecations(self, result): warnings = result.pop('__warnings', []) for warning in warnings: self.client.module.deprecate( msg=warning['msg'], version=warning['version'] ) def exec_module(self): start = datetime.now().isoformat() version = tmos_version(self.client) if not module_provisioned(self.client, 'asm'): raise F5ModuleError( "ASM must be provisioned to use this module." ) changed = False result = dict() state = self.want.state if state == "present": changed = self.present() elif state == "absent": changed = self.absent() reportable = ReportableChanges(params=self.changes.to_return()) changes = reportable.to_return() result.update(**changes) result.update(dict(changed=changed)) self._announce_deprecations(result) send_teem(start, self.module, version) return result def present(self): if self.exists(): return self.update() else: return self.create() def absent(self): if self.exists(): return self.remove() return False def should_update(self): result = self._update_changed_options() if result: return True return False def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.module.check_mode: return True self.update_on_device() return True def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the resource.") return True def create(self): self._set_changed_options() if self.module.check_mode: return True self.create_on_device() return True def exists(self): policy_id = self._get_policy_id() set_link = self._get_signature_set_link() uri = 'https://{0}:{1}/mgmt/tm/asm/policies/{2}/signature-sets/'.format( self.client.provider['server'], self.client.provider['server_port'], policy_id, ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) errors = [401, 403, 409, 500, 501, 502, 503, 504] if resp.status in errors or 'code' in response and response['code'] in errors: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) if 'items' in response and response['items'] != []: for st in response['items']: if st['signatureSetReference']['link'] == set_link['link']: self.want.ss_id = st['id'] return True return False def _get_signature_set_link(self): result = None signature_set = self.want.name uri = "https://{0}:{1}/mgmt/tm/asm/signature-sets".format( self.client.provider['server'], self.client.provider['server_port'], ) query = "?$select=name" resp = self.client.api.get(uri + query) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]: raise F5ModuleError(resp.content) if 'items' in response and response['items'] != []: for item in response['items']: if item['name'] == signature_set: result = dict(link=item['selfLink']) return result def _get_policy_id(self): policy_id = None uri = "https://{0}:{1}/mgmt/tm/asm/policies/".format( self.client.provider['server'], self.client.provider['server_port'], ) query = "?$filter=contains(name,'{0}')+and+contains(partition,'{1}')&$select=name,id".format( self.want.policy_name, self.want.partition ) resp = self.client.api.get(uri + query) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]: raise F5ModuleError(resp.content) if 'items' in response and response['items'] != []: policy_id = response['items'][0]['id'] if not policy_id: raise F5ModuleError( "The policy with the name {0} does not exist".format(self.want.policy_name) ) return policy_id def create_on_device(self): policy_id = self._get_policy_id() params = self.changes.api_params() params['signatureSetReference'] = self._get_signature_set_link() uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}/signature-sets/".format( self.client.provider['server'], self.client.provider['server_port'], policy_id ) resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: return True raise F5ModuleError(resp.content) def update_on_device(self): policy_id = self._get_policy_id() params = self.changes.api_params() uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}/signature-sets/{3}".format( self.client.provider['server'], self.client.provider['server_port'], policy_id, self.want.ss_id ) resp = self.client.api.patch(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: return True raise F5ModuleError(resp.content) def remove_from_device(self): policy_id = self._get_policy_id() uri = 'https://{0}:{1}/mgmt/tm/asm/policies/{2}/signature-sets/{3}'.format( self.client.provider['server'], self.client.provider['server_port'], policy_id, self.want.ss_id ) response = self.client.api.delete(uri) if response.status in [200, 201]: return True raise F5ModuleError(response.content) def read_current_from_device(self): policy_id = self._get_policy_id() uri = "https://{0}:{1}/mgmt/tm/asm/policies/{2}/signature-sets/{3}".format( self.client.provider['server'], self.client.provider['server_port'], policy_id, self.want.ss_id ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: return ApiParameters(params=response) raise F5ModuleError(resp.content) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( policy_name=dict( required=True ), name=dict( required=True ), alarm=dict( type='bool' ), block=dict( type='bool' ), learn=dict( type='bool' ), state=dict( default='present', choices=['present', 'absent'] ), partition=dict( default='Common', fallback=(env_fallback, ['F5_PARTITION']) ) ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, ) try: mm = ModuleManager(module=module) results = mm.exec_module() module.exit_json(**results) except F5ModuleError as ex: module.fail_json(msg=str(ex)) if __name__ == '__main__': main()
jai-singhal/djangopy
vendor/bundle/ruby/2.3.0/gems/sass-3.5.6/lib/sass/tree/media_node.rb
module Sass::Tree # A static node representing a `@media` rule. # `@media` rules behave differently from other directives # in that when they're nested within rules, # they bubble up to top-level. # # @see Sass::Tree class MediaNode < DirectiveNode # TODO: parse and cache the query immediately if it has no dynamic elements # The media query for this rule, interspersed with {Sass::Script::Tree::Node}s # representing `#{}`-interpolation. Any adjacent strings will be merged # together. # # @return [Array<String, Sass::Script::Tree::Node>] attr_accessor :query # The media query for this rule, without any unresolved interpolation. It's # only set once {Tree::Visitors::Perform} has been run. # # @return [Sass::Media::QueryList] attr_accessor :resolved_query # @param query [Array<String, Sass::Script::Tree::Node>] See \{#query} def initialize(query) @query = query super('') end # @see DirectiveNode#value def value; raise NotImplementedError; end # @see DirectiveNode#name def name; '@media'; end # @see DirectiveNode#resolved_value def resolved_value @resolved_value ||= "@media #{resolved_query.to_css}" end # True when the directive has no visible children. # # @return [Boolean] def invisible? children.all? {|c| c.invisible?} end end end
GerHobbelt/DOMtastic
src/dom_extra.js
/** * @module DOM (extra) */ import { each } from './util'; import { append, before, after } from './dom'; import { $ } from './selector'; /** * Append each element in the collection to the specified element(s). * * @param {Node|NodeList|Object} element What to append the element(s) to. Clones elements as necessary. * @return {Object} The wrapped collection * @chainable * @example * $('.item').appendTo(container); */ function appendTo(element) { var context = typeof element === 'string' ? $(element) : element; append.call(context, this); return this; } /* * Empty each element in the collection. * * @return {Object} The wrapped collection * @chainable * @example * $('.item').empty(); */ function empty(){ return each(this, function(element) { element.innerHTML = ''; }); } /** * Remove the collection from the DOM. * * @return {Array} Array containing the removed elements * @example * $('.item').remove(); */ function remove() { return each(this, function(element) { if (element.parentNode) { element.parentNode.removeChild(element); } }); } /** * Replace each element in the collection with the provided new content, and return the array of elements that were replaced. * * @return {Array} Array containing the replaced elements */ function replaceWith() { return before.apply(this, arguments).remove(); } /** * Get the `textContent` from the first, or set the `textContent` of each element in the collection. * * @param {String} [value] * @return {Object} The wrapped collection * @chainable * @example * $('.item').text('New content'); */ function text(value){ if(value == null) { return this[0].textContent; } each(this, function(element) { element.textContent = '' + value; }); return this; } /** * Get the `value` from the first, or set the `value` of each element in the collection. * * @param {String} [value] * @return {Object} The wrapped collection * @chainable * @example * $('input.firstName').value('New value'); */ function val(value){ if(value == null) { return this[0].value; } each(this, function(element){ element.value = value; }); return this; } /* * Export interface */ export { appendTo, empty, remove, replaceWith, text, val };
smogpill/core
src/io/stream/coBinaryInputStream.h
// Copyright(c) 2016 <NAME> // Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT). #pragma once #include "io/stream/coInputStream.h" class coBinaryInputStream final : public coInputStream { coDECLARE_SUPER(coInputStream); public: coBinaryInputStream(const coArray<coByte>& buffer); }; coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coBool& v) { stream.Read(reinterpret_cast<coByte&>(v)); return stream; } coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coUint8& v) { stream.Read(v); return stream; } coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coUint16& v) { stream.Read(reinterpret_cast<coByte*>(&v), sizeof(v)); return stream; } coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coUint32& v) { stream.Read(reinterpret_cast<coByte*>(&v), sizeof(v)); return stream; } coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coUint64& v) { stream.Read(reinterpret_cast<coByte*>(&v), sizeof(v)); return stream; } coFORCE_INLINE coBinaryInputStream& operator >> (coBinaryInputStream& stream, coFloat& v) { stream.Read(reinterpret_cast<coByte*>(&v), sizeof(v)); return stream; } template <class T> coFORCE_INLINE coBinaryInputStream& operator>>(coBinaryInputStream& stream, T& a) { a.Read(stream); return stream; }
AsahiOS/gate
usr/src/lib/libnisdb/ldap_glob.c
<filename>usr/src/lib/libnisdb/ldap_glob.c /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2001 by Sun Microsystems, Inc. * All rights reserved. */ #include "ldap_glob.h" /* These are the local versions we use if the app doesn't provide overrides */ int verbose = 0; int justTesting = 0; FILE *cons = 0; int setColumnsDuringConfig = 0; int __local_update_root_object(nis_name root_dir, nis_object *d_obj) { return (0); } nis_object * __local_get_root_object(void) { return (0); } int __local_remove_root_object(nis_name root_dir, nis_object* d_obj) { return (0); } int __local_beginTransaction(void) { return (1); } int __local_abort_transaction(int xid) { return (0); } int __local_endTransaction(int xid, nis_object *dirObj) { return (0); } int __local_addUpdate(log_entry_t type, char *name, int numAttr, nis_attr *attr, nis_object *obj, nis_object *oldDir, uint32_t ttime) { return (-1); } int __local_lockTransLog(const char *msg, int wr, int trylock) { return (0); } void __local_unlockTransLog(const char *msg, int wr) { } int __local__nis_lock_db_table(nis_name name, int readwrite, int *trylock, const char *msg) { return (1); } int __local__nis_ulock_db_table(nis_name name, int readwrite, int remove, const char *msg) { return (1); } /* Weak symbol linkage allows override; default is local versions */ #pragma weak verbose #pragma weak justTesting #pragma weak cons #pragma weak setColumnsDuringConfig #pragma weak update_root_object = __local_update_root_object #pragma weak get_root_object = __local_get_root_object #pragma weak remove_root_object = __local_remove_root_object #pragma weak beginTransaction = __local_beginTransaction #pragma weak abort_transaction = __local_abort_transaction #pragma weak endTransaction = __local_endTransaction #pragma weak addUpdate = __local_addUpdate #pragma weak lockTransLog = __local_lockTransLog #pragma weak unlockTransLog = __local_unlockTransLog #pragma weak __nis_lock_db_table = __local__nis_lock_db_table #pragma weak __nis_ulock_db_table = __local__nis_ulock_db_table
niektuytel/Machine_Learning
reinforcement_learning/double_deep_q_learning/sample_keras.py
<gh_stars>10-100 from tensorflow.keras.layers import Dense, Activation from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam import numpy as np import gym class ReplayBuffer(object): def __init__(self, max_size, input_shape, n_actions, discrete=False): self.mem_size = max_size self.mem_cntr = 0 self.discrete = discrete self.state_memory = np.zeros((self.mem_size, input_shape)) self.new_state_memory = np.zeros((self.mem_size, input_shape)) dtype = np.int8 if self.discrete else np.float32 self.action_memory = np.zeros((self.mem_size, n_actions), dtype=dtype) self.reward_memory = np.zeros(self.mem_size) self.terminal_memory = np.zeros(self.mem_size, dtype=np.float32) def store_transition(self, state, action, reward, state_, done): index = self.mem_size % self.mem_size self.state_memory[index] = state self.new_state_memory[index] = state_ if self.discrete: actions = np.zeros(self.action_memory.shape[1]) actions[action] = 1.0 self.action_memory[index] = actions else: self.action_memory[index] = action self.reward_memory[index] = reward self.terminal_memory[index] = 1 - int(done) self.mem_cntr += 1 def sample_buffer(self, batch_size): max_mem = min(self.mem_cntr, self.mem_size) batch = np.random.choice(max_mem, batch_size) states = self.state_memory[batch] new_states = self.new_state_memory[batch] actions = self.action_memory[batch] rewards = self.reward_memory[batch] terminal = self.terminal_memory[batch] return states, actions, rewards, new_states, terminal class DDQNAgent(object): def __init__(self, alpha, gamma, n_actions, epsilon, batch_size, input_dims, epsilon_dec=0.996, epsilon_end=0.01, mem_size=1000000, fname="ddqn_model.h5", replace_target=100): self.n_actions = n_actions self.action_space = [i for i in range(self.n_actions)] self.gamma = gamma self.epsilon = epsilon self.epsilon_dec = epsilon_dec self.epsilon_min = epsilon_end self.batch_size = batch_size self.model = fname self.replace_target = replace_target self.memory = ReplayBuffer(mem_size, input_dims, n_actions, True) self.q_eval = build_dqn(alpha, n_actions, input_dims, 256, 256) self.q_target = build_dqn(alpha, n_actions, input_dims, 256, 256) def remember(self, state, action, reward, new_state, done): self.memory.store_transition(state, action, reward, new_state, done) def get_action(self, state): state = state[np.newaxis, :] rand = np.random.random() if rand < self.epsilon: action = np.random.choice(self.action_space) else: actions = self.q_eval.predict(state) action = np.argmax(actions) return action def learn(self): if self.memory.mem_cntr > self.batch_size: # get stored data state, action, reward, new_state, done = self.memory.sample_buffer(self.batch_size) action_values = np.array(self.action_space, dtype=np.int8) action_indices = np.dot(action, action_values) # forward q_next = self.q_target.predict(new_state) q_eval = self.q_eval.predict(new_state) q_pred = self.q_eval.predict(state) max_actions = np.argmax(q_eval, axis=1) q_target = q_pred # update stored data batch_index = np.arange(self.batch_size, dtype=np.int32) q_target[batch_index, action_indices] = reward + self.gamma * q_next[batch_index, max_actions.astype(int)] * done # backward _ = self.q_eval.fit(state, q_target, verbose=0) if self.memory.mem_cntr % self.replace_target == 0: self.q_target.set_weights(self.q_eval.get_weights()) # update randomness self.epsilon = self.epsilon * self.epsilon_dec if self.epsilon > self.epsilon_min else self.epsilon_min def build_dqn(lr, n_actions, input_dims, fc1_dims, fc2_dims): model = Sequential([ Dense(fc1_dims, input_shape=(input_dims, )), Activation("relu"), Dense(fc2_dims), Activation("relu"), Dense(n_actions) ]) model.compile(optimizer=Adam(lr=lr), loss="mse") return model if __name__ == '__main__': env = gym.make("LunarLander-v2") ddqn_agent = DDQNAgent(alpha=0.0005, gamma=0.99, n_actions=4, epsilon=1.0, batch_size=64, input_dims=8) n_games = 500 for i in range(n_games): done = False rewards = 0 state = env.reset() while not done: action = ddqn_agent.get_action(state) next_state, reward, done, info = env.step(action) rewards += reward ddqn_agent.remember(state, action, reward, next_state, done) state = next_state ddqn_agent.learn() if i % 100 == 0: env.render() print(f"[{i}/{n_games}] rewarded:{rewards}")
yunhai281/baseProject
src/main/java/com/boyuyun/base/user/action/BureauUserAction.java
package com.boyuyun.base.user.action; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Controller; import com.boyuyun.base.sys.biz.DictionaryBiz; import com.boyuyun.base.sys.biz.DictionaryItemBiz; import com.boyuyun.base.sys.entity.Dictionary; import com.boyuyun.base.sys.entity.DictionaryItem; import com.boyuyun.base.user.biz.BureauUserBiz; import com.boyuyun.base.user.entity.BureauUser; import com.boyuyun.base.util.ConstantUtil; import com.boyuyun.base.util.base.BaseAction; import com.boyuyun.common.annotation.LogThisOperate; import com.boyuyun.common.autolog.OperateType; import com.boyuyun.common.json.ByyJsonUtil; import com.boyuyun.common.util.ByyDateUtil; import com.boyuyun.common.util.ExcelReader; import com.google.common.base.Strings; import com.opensymphony.xwork2.ModelDriven; @Controller public class BureauUserAction extends BaseAction implements ModelDriven<BureauUser> { /** @Fields serialVersionUID: */ private static final long serialVersionUID = -5061318888080230449L; @Resource private BureauUserBiz bureauUserService; @Resource private DictionaryBiz dictionaryService; @Resource private DictionaryItemBiz dictionaryItemService; private BureauUser bureauUser = new BureauUser(); @Override public BureauUser getModel() { return (BureauUser) initPage(bureauUser); } /** * @author caoyy * @date 2017-03-21 * @see 跳转到教育局用户列表页面 * @return */ public String toList() { return "toList"; } public String toimport(){ return "toimport"; } /** * @author caoyy * @date 2017-03-21 * @see 跳转到教育局用户选择页面 * @return */ public String toSelectList() { response.setCharacterEncoding("utf-8"); String governmentId = request.getParameter("governmentId"); request.setAttribute("governmentId", governmentId); return "toSelectList"; } /** * @author caoyy * @date 2017-03-21 * @see 跳转到教育局用户新建页面 * @return */ public String toAdd() throws Exception{ response.setCharacterEncoding("utf-8"); Dictionary dic = dictionaryService.getByCode("GovernmentPost"); if(dic!=null){ DictionaryItem exampleItem = new DictionaryItem(); exampleItem.setDictionaryId(dic.getId()); List<DictionaryItem> itemList = dictionaryItemService.getListNonePaged(exampleItem); request.setAttribute("items", itemList); } return "toView"; } /** * @author caoyy * @date 2017-03-21 * @see 跳转到教育局用户详情页面 * @return */ public String toView() throws Exception{ response.setCharacterEncoding("utf-8"); return "toDetail"; } /** * @author caoyy * @date 2017-03-21 * @see 跳转到教育局用户编辑页面 * @return */ public String toEdit() throws Exception{ response.setCharacterEncoding("utf-8"); Dictionary dic = dictionaryService.getByCode("GovernmentPost"); if(dic!=null){ DictionaryItem exampleItem = new DictionaryItem(); exampleItem.setDictionaryId(dic.getId()); List<DictionaryItem> itemList = dictionaryItemService.getListNonePaged(exampleItem); request.setAttribute("items", itemList); } return "toView"; } /** * @author caoyy * @date 2017-03-21 * @see 获取教育局用户列表数据 * @return */ public String getList() throws Exception{ response.setCharacterEncoding("utf-8"); String result = ""; try{ List<BureauUser> pageInfo = bureauUserService.getListPaged(bureauUser); int count = bureauUserService.getListPagedCount(bureauUser); result = ByyJsonUtil.serialize(count,pageInfo); }catch(Exception e){ e.printStackTrace(); } this.print(result); return null; } /** * @author caoyy * @date 2017-03-21 * @see 教育局用户数据保存、编辑 * @return */ @LogThisOperate(module="教育局用户",operateType=OperateType.新增或修改) public String save() throws Exception{ response.setCharacterEncoding("utf-8"); PrintWriter out = null; String result = this.getSuccessJson("保存成功"); try { String postId = request.getParameter("postId"); if(!Strings.isNullOrEmpty(postId)){ bureauUserService.saveBureau(bureauUser, postId.split(",")); }else{ result = this.getFailJson("保存失败"); } } catch (Exception e) { e.printStackTrace(); result = this.getFailJson("保存失败"); } this.print(result); return null; } /** * @author caoyy * @date 2017-03-21 * @see 根据唯一标识获取教育局用户数据 * @return */ public String getBean()throws Exception { response.setCharacterEncoding("utf-8"); PrintWriter out = null; String result = ""; String id = request.getParameter("id"); try { if (id != null && id.trim().length() > 0) { bureauUser = (BureauUser) bureauUserService.get(bureauUser); } result = ByyJsonUtil.serialize(bureauUser,null,ByyDateUtil.YYYY_MM_DD); } catch (Exception e) { e.printStackTrace(); } this.print(result); return null; } /** * @author caoyy * @date 2017-03-21 * @see 删除教育局用户;可批量删除 * @return */ @LogThisOperate(module="教育局用户",operateType=OperateType.删除) public String delete() throws Exception{ response.setCharacterEncoding("utf-8"); String result = ""; try { String id = request.getParameter("id"); if(!Strings.isNullOrEmpty(id)){ String[] ids = id.split(","); List<BureauUser> bureauUsers = new ArrayList<BureauUser>(); List IDSToDelete = new ArrayList(); for(String string : ids){ bureauUser = new BureauUser (); bureauUser.setId(string); IDSToDelete.add(string); bureauUsers.add(bureauUser); } if(bureauUsers.size()>0){ bureauUserService.deleteBueau(bureauUsers); this.setBatchListId(IDSToDelete); result = this.getSuccessJson("删除成功"); }else { result = this.getFailJson("删除失败"); } } } catch (Exception e) { e.printStackTrace(); result =this.getFailJson("程序出错"); } this.print(result); return null; } /*** * 导出模版 * @return */ public String exportTemplateExcel() throws Exception{ response.setCharacterEncoding("utf-8"); String strDirPath = request.getSession().getServletContext().getRealPath("/"); String path = strDirPath+"/WEB-INF/page/admin/user/bureau/教育局人员模板.xlsx"; File file = new File(path); if(file.exists()){ // 以流的形式下载文件。 String fileName = "教育局人员模板"; response.setContentType("application/x-msdownload"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")+".xlsx"); InputStream fis = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(fis); String[] governmentPostArr=dictionaryItemService.getArr("GovernmentPost"); XSSFSheet sheet = wb.getSheetAt(0); //设置数据有效性 sheet.addValidationData(ExcelReader.setDataValidation(sheet, governmentPostArr, 1, 6000, 6, 6)); ServletOutputStream out = response.getOutputStream(); wb.write(out); out.flush(); out.close(); } return null; } /** * @Description * @author jms * @return * @throws Exception */ @LogThisOperate(module="教育局用户",operateType=OperateType.导入) public String importExcel() throws Exception{ response.setCharacterEncoding("utf-8"); PrintWriter out = null; String result = this.getFailJson("导入失败!"); String filename = request.getParameter("filename"); String filePath = request.getParameter("filePath"); try { //开始处理文件导入,判断文件类型和存在 if(null != filePath && !"".equals(filePath)){ //判断文件后缀是不是xls或者xlsx if(filePath.endsWith(".xls") || filePath.endsWith(".xlsx")){ String path= ConstantUtil.UPLOAD_FOLDER + filePath; File sourceFile = new File(path); if(sourceFile.exists()){ String fileName = sourceFile.getName(); } // 写入模板 File dirFile = new File(path); if(dirFile.exists()){ //存在该文件.通过POI进行读取数据,然后保存到数据库中。 ExcelReader excelReader = new ExcelReader(); Map<Integer, List> contentMap= excelReader.readExcelContent(new FileInputStream(path)); List listForIds = new ArrayList();//用于存放生成的id String mgs=bureauUserService.insertImportExcel(contentMap,listForIds); if(mgs!=null && !"".equals(mgs)){ result = this.getFailJson(mgs); }else { result = this.getSuccessJson("导入成功!"); } }else{ result = this.getFailJson("文件未上传成功!"); } }else{ result = this.getFailJson("文件后缀不符合.xls,.xlsx的格式!"); } }else{ result = this.getFailJson("文件路径获取失败!"); } } catch (Exception e) { e.printStackTrace(); } this.print(result); return null; } /** * @author jms * @date 2017-04-07 * @see 上移下移部门人员 * @return */ @LogThisOperate(module="教育局用户",operateType=OperateType.更改排序) public String updateSortnum() throws Exception{ response.setCharacterEncoding("utf-8"); String result = this.getSuccessJson("移动成功"); try { String uesrId = request.getParameter("id"); String type = request.getParameter("type"); if(!Strings.isNullOrEmpty(type)){ result= bureauUserService.updateSortNumber(uesrId, type); result =this.getSuccessJson(result); }else{ result = this.getFailJson("移动失败"); } /*if(!Strings.isNullOrEmpty(postId)){ bureauUserService.saveBureau(bureauUser, postId.split(",")); }else{ result = this.getFailJson("移动失败"); }*/ } catch (Exception e) { e.printStackTrace(); result = this.getFailJson("移动失败"); } this.print(result); return null; } }
dcavar/Py3L
src/Intro/ngramtest2.py
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ (C) 2013 by <NAME> This is an example of a simple Naive Bayesian classifier. Make sure that you paste some German and English text for the extraction of language models in text-de-1.txt and text-en-1.txt. The more text you put in these files, the better it should be for your model generation. """ # https://github.com/dcavar/Py3L from ngrams import makeNgramModel # read file ifp = open("text-de-1.txt", mode='r', encoding='utf8') mytext = ifp.read() ifp.close() mymodel_de = makeNgramModel(mytext, 1) total = sum(mymodel_de.values()) for key, value in mymodel_de.items(): mymodel_de[key] = value / total # print(key, mymodel_de[key]) # read file ifp = open("text-en-1.txt", mode='r', encoding='utf8') mytext = ifp.read() ifp.close() mymodel_en = makeNgramModel(mytext, 1) total = sum(mymodel_en.values()) for key, value in mymodel_en.items(): mymodel_en[key] = value / total # print(key, mymodel_en[key]) mytext = "Dies ist ein kleiner Test." #mytext = "This is a small test." mymodel_unk = makeNgramModel(mytext, 1) total = sum(mymodel_unk.values()) en_dist = 1.0 de_dist = 1.0 for key, value in mymodel_unk.items(): # mymodel_unk[key] = value / total # we are using here the sum of the log-probabilities (log to the # base 2), every log-probability multiplied with the times # the n-gram occurs in the unknown/unclassified text en_dist += (mymodel_en.get(key, 0.0000000001) ** 0.5) * mymodel_unk[key] de_dist += (mymodel_de.get(key, 0.0000000001) ** 0.5) * mymodel_unk[key] print(mytext) print(en_dist, de_dist) # the larger the resulting log-prob., the more likely the text could # be related to the corresponding probability distribution if en_dist > de_dist: print("This text is English.") else: print("This text is German.")
mankeyl/elasticsearch
modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/GrokProcessorFactoryTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.ingest.common; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.grok.MatcherWatchdog; import org.elasticsearch.test.ESTestCase; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; public class GrokProcessorFactoryTests extends ESTestCase { public void testBuild() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("(?<foo>\\w+)")); String processorTag = randomAlphaOfLength(10); GrokProcessor processor = factory.create(null, processorTag, null, config); assertThat(processor.getTag(), equalTo(processorTag)); assertThat(processor.getMatchField(), equalTo("_field")); assertThat(processor.getGrok(), notNullValue()); assertThat(processor.isIgnoreMissing(), is(false)); } public void testBuildWithIgnoreMissing() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("(?<foo>\\w+)")); config.put("ignore_missing", true); String processorTag = randomAlphaOfLength(10); GrokProcessor processor = factory.create(null, processorTag, null, config); assertThat(processor.getTag(), equalTo(processorTag)); assertThat(processor.getMatchField(), equalTo("_field")); assertThat(processor.getGrok(), notNullValue()); assertThat(processor.isIgnoreMissing(), is(true)); } public void testBuildMissingField() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("patterns", Collections.singletonList("(?<foo>\\w+)")); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat(e.getMessage(), equalTo("[field] required property is missing")); } public void testBuildMissingPatterns() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "foo"); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat(e.getMessage(), equalTo("[patterns] required property is missing")); } public void testBuildEmptyPatternsList() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "foo"); config.put("patterns", Collections.emptyList()); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat(e.getMessage(), equalTo("[patterns] List of patterns must not be empty")); } public void testCreateWithCustomPatterns() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("%{MY_PATTERN:name}!")); config.put("pattern_definitions", Collections.singletonMap("MY_PATTERN", "foo")); GrokProcessor processor = factory.create(null, null, null, config); assertThat(processor.getMatchField(), equalTo("_field")); assertThat(processor.getGrok(), notNullValue()); assertThat(processor.getGrok().match("foo!"), equalTo(true)); } public void testCreateWithInvalidPattern() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("[")); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat(e.getMessage(), equalTo("[patterns] Invalid regex pattern found in: [[]. premature end of char-class")); } public void testCreateWithInvalidPatternDefinition() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("%{MY_PATTERN:name}!")); config.put("pattern_definitions", Collections.singletonMap("MY_PATTERN", "[")); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat( e.getMessage(), equalTo("[patterns] Invalid regex pattern found in: [%{MY_PATTERN:name}!]. premature end of char-class") ); } public void testCreateWithInvalidEcsCompatibilityMode() throws Exception { GrokProcessor.Factory factory = new GrokProcessor.Factory(MatcherWatchdog.noop()); Map<String, Object> config = new HashMap<>(); config.put("field", "_field"); config.put("patterns", Collections.singletonList("(?<foo>\\w+)")); String invalidEcsMode = randomAlphaOfLength(3); config.put("ecs_compatibility", invalidEcsMode); ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class, () -> factory.create(null, null, null, config)); assertThat(e.getMessage(), equalTo("[ecs_compatibility] unsupported mode '" + invalidEcsMode + "'")); } }
TheDIM47/canoe
core/shared/src/main/scala/canoe/models/passport/PassportElementError.scala
<reponame>TheDIM47/canoe<filename>core/shared/src/main/scala/canoe/models/passport/PassportElementError.scala<gh_stars>100-1000 package canoe.models.passport /** * Error in the Telegram Passport element which was submitted that should be resolved by the user */ sealed trait PassportElementError extends Product /** * Issue in one of the data fields that was provided by the user. * The error is considered resolved when the field's value changes. * * @param `type` The section of the user's Telegram Passport which has the error. * One of “personal_details”, “passport”, “driver_license”, “identity_card”, “internal_passport”, “address” * @param fieldName Name of the data field which has the error * @param dataHash Base64-encoded data hash * @param message Error message * @param source Error source, must be 'data' */ final case class PassportElementErrorDataField(`type`: String, fieldName: String, dataHash: String, message: String, source: String = "data") extends PassportElementError /** * Issue with the front side of a document. * The error is considered resolved when the file with the front side of the document changes. * * @param source Error source, must be 'front_side' * @param `type` The section of the user's Telegram Passport which has the issue. * One of “passport”, “driver_license”, “identity_card”, “internal_passport” * @param fileHash Base64-encoded hash of the file with the front side of the document * @param message Error message */ final case class PassportElementErrorFrontSide(`type`: String, fileHash: String, message: String, source: String = "front_side") extends PassportElementError /** * Issue with the reverse side of a document. * The error is considered resolved when the file with reverse side of the document changes. * * @param `type` The section of the user's Telegram Passport which has the issue. * One of “driver_license”, “identity_card” * @param fileHash Base64-encoded hash of the file with the reverse side of the document * @param message Error message * @param source Error source, must be 'reverse_side' */ final case class PassportElementErrorReverseSide(`type`: String, fileHash: String, message: String, source: String = "reverse_side") extends PassportElementError /** * Issue with the selfie with a document. * The error is considered resolved when the file with the selfie * * @param `type` The section of the user's Telegram Passport which has the issue, * One of “passport”, “driver_license”, “identity_card”, “internal_passport” * @param fileHash Base64-encoded hash of the file with the selfie * @param message Error message * @param source Error source, must be 'selfie' */ final case class PassportElementErrorSelfie(`type`: String, fileHash: String, message: String, source: String = "selfie") extends PassportElementError /** * Issue with a document scan. * The error is considered resolved when the file with the document scan changes. * * @param `type` The section of the user's Telegram Passport which has the issue. * One of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” * @param fileHash Base64-encoded file hash * @param message Error message * @param source Error source, must be 'file' */ final case class PassportElementErrorFile(`type`: String, fileHash: String, message: String, source: String = "file") extends PassportElementError /** * Issue with a list of scans. * The error is considered resolved when the list of files containing the scans changes. * * @param `type` The section of the user's Telegram Passport which has the issue. * One of “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” * @param fileHashes List of base64-encoded file hashes * @param message Error message * @param source Error source, must be 'files' */ final case class PassportElementErrorFiles(`type`: String, fileHashes: List[String], message: String, source: String = "files") extends PassportElementError /** * Issue with the translated version of a document. * The error is considered resolved when a file with the document translation change. * * @param source Error source, must be 'translation_file' * @param `type` Type of element of the user's Telegram Passport which has the issue. * One of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, * “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” * @param fileHash Base64-encoded file hash * @param message Error message */ final case class PassportElementErrorTranslationFile(`type`: String, fileHash: String, message: String, source: String = "translation_file") extends PassportElementError /** * Issue with the translated version of a document. * The error is considered resolved when a file with the document translation change. * * @param `type` Type of element of the user's Telegram Passport which has the issue. * One of “passport”, “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, * “bank_statement”, “rental_agreement”, “passport_registration”, “temporary_registration” * @param fileHashes List of base64-encoded file hashes * @param message Error message * @param source Error source, must be 'translation_files' */ final case class PassportElementErrorTranslationFiles(`type`: String, fileHashes: List[String], message: String, source: String = "translation_files") extends PassportElementError /** * Issue in an unspecified place. * The error is considered resolved when new data is added. * * @param `type` Type of element of the user's Telegram Passport which has the issue * @param element_hash Base64-encoded element hash * @param message Error message * @param source Error source, must be 'unspecified' */ final case class PassportElementErrorUnspecified(`type`: String, element_hash: String, message: String, source: String = "unspecified") extends PassportElementError
CIDARLAB/fpSelection
fpSelection/src/main/java/org/cidarlab/fpSelection/parsers/ScrapedCSVParse.java
<gh_stars>1-10 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.cidarlab.fpSelection.parsers; import com.panayotis.gnuplot.JavaPlot; import com.panayotis.gnuplot.plot.AbstractPlot; import com.panayotis.gnuplot.plot.DataSetPlot; import com.panayotis.gnuplot.style.PlotStyle; import com.panayotis.gnuplot.style.Style; import com.panayotis.gnuplot.swing.JPlot; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.TreeMap; import javax.swing.JFrame; import org.cidarlab.fpSelection.dom.Fluorophore; /** * * @author david */ public class ScrapedCSVParse { public static HashMap<String, Fluorophore> parse(File directory) throws FileNotFoundException, IOException { HashMap<String, Fluorophore> masterList = new HashMap<>(); File[] listOfFiles = directory.listFiles(); BufferedReader reader; Fluorophore fp; //JFrame frame = new JFrame("FP Spectrum"); for (File next : listOfFiles) { String name = next.getName().replace(".csv", ""); fp = new Fluorophore(); fp.name = name; TreeMap<Double, Double> EMSpectrum = new TreeMap<>(); TreeMap<Double, Double> EXSpectrum = new TreeMap<>(); reader = new BufferedReader(new FileReader(next)); String line = reader.readLine(); String splitter = ";"; String tokens[]; //Read again cause first line is labels showing [0];[1];[2];[3]; line = reader.readLine(); while (line != null) { //[0] Absorption wavelength (nm); //[1] Normalized Absorption; //[2] Emission wavelength (nm); //[3] Normalized emission; tokens = line.split(splitter); if (tokens != null && !tokens[0].isEmpty()) { EXSpectrum.put(Double.parseDouble(tokens[0]), 100 * Double.parseDouble(tokens[1])); } if (tokens != null && tokens.length >= 3 && !tokens[2].isEmpty()) { EMSpectrum.put(Double.parseDouble(tokens[2]), 100 * Double.parseDouble(tokens[3])); } line = reader.readLine(); } fp.EMspectrum = EMSpectrum; fp.EXspectrum = EXSpectrum; masterList.put(fp.name, fp); // JavaPlot plotPls = new JavaPlot(); // AbstractPlot styled = new DataSetPlot(fp.makeEMDataSet()); // PlotStyle stylish = new PlotStyle(Style.LINES); // // styled.setPlotStyle(stylish); // styled.setTitle(fp.getName()); // // plotPls.addPlot(styled); // // JPlot jj = new JPlot(plotPls); // jj.plot(); // jj.repaint(); // // frame.getContentPane().removeAll(); // frame.getContentPane().add(jj); // frame.pack(); // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame.setVisible(true); } return masterList; } }
becca-bailey/amphtml
build-system/babel-plugins/babel-plugin-transform-log-methods/test/fixtures/transform-log-methods/template-literals/input.js
user().assert(true, `I'm a ${template} literal with one argument.`); user().assert(x != y, `I have ${foo}, ${bar} and ${baz}.`); userAssert(false, `Template ${index} = 2`); devAssert(1, `Template ${index} = 3`);
rajatenzyme/Coding-Journey-
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Circular_Queue/Circular_Queue.c
/* Circular Queue is based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. */ #include<stdio.h> int queue[5]; int front = -1, rear = -1, size = 5; void insert (int value); void deleteQueue(); void display(); int main() { int choice, value; printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display\n"); do { printf("Enter choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("Enter the value: "); scanf("%d", &value); insert (value); break; case 2: deleteQueue(); break; case 3: display(); break; } } while(choice != 3); return 0; } /* Insertion: 1) Check whether queue is Full by ((rear == SIZE-1 && front == 0) || (rear == front-1)). 2) If it is full then display Queue is full. If queue is not full then, check if (rear == SIZE – 1 && front != 0) if it is true then set rear = 0 and insert element. */ // Inserting the value in the queue void insert (int value) { if ((front == 0 && rear == size - 1) || (rear == (front - 1) % (size - 1))) { printf("\nQueue is full\n"); return; } else if (front == -1) { front = rear = 0; queue[rear] = value; } else if (rear == size - 1 && front != 0) { rear = 0; queue[rear] = value; } else { rear++; queue[rear] = value; } } /* Deletion: 1) Check whether queue is Empty means check (front==-1). 2) If it is empty then display Queue is empty. If queue is not empty then Check if (front==rear) if it is true then set front=rear= -1 else check if (front==size-1), if it is true then set front=0 and return the element. */ // Deleting from queue void deleteQueue() { if (front == -1) { printf("Queue Underflow\n"); return ; } printf("Element deleted from queue is : %d\n", queue[front]); if (front == rear) { front = -1; rear = -1; } else { if (front == size - 1) front = 0; else front = front + 1; } } // Displaying the queue void display() { if (front == -1) { printf("\nQueue is Empty"); return; } printf("\nCircular Queue elements are: "); if (front <= rear) { for (int i = front; i <= rear; i++) printf("%d ", queue[i]); } else { for (int i = front; i < size; i++) printf("%d ", queue[i]); for (int i = 0; i <= rear; i++) printf("%d ", queue[i]); } } /*1.Insert 2.Delete 3.Display Enter choice: 1 Enter the value: 1 Enter choice: 1 Enter the value: 2 Enter choice: 1 Enter the value: 3 Enter choice: 1 Enter the value: 4 Enter choice: 2 Element deleted from queue is : 1 Enter choice: 3 Circular Queue elements are: 2 3 4*/
Emmettwoo/LearningDataStructures
test/src/top/woohoo/map/LeetCode350.java
<reponame>Emmettwoo/LearningDataStructures<filename>test/src/top/woohoo/map/LeetCode350.java<gh_stars>0 package top.woohoo.map; import top.woohoo.array.Array; public class LeetCode350 { public int[] intersect(int[] nums1, int[] nums2) { BSTMap<Integer, Integer> set = new BSTMap<>(); Array<Integer> list = new Array<>(); // nums1计数 for (int number : nums1) { if (set.contains(number)) { set.set(number, set.get(number) + 1); } else { set.add(number, 1); } } // nums2求同 for (int number : nums2) { if (set.contains(number) && set.get(number) > 0) { list.add(number); set.set(number, set.get(number) - 1); } } // 转换结果集 int [] results = new int[list.getSize()]; for (int index = 0; index < list.getSize(); index++) { results[index] = list.get(index); } return results; } public static void main(String[] args) { int[] nums1 = {4, 4, 9, 5}; int[] nums2 = {9, 4, 9, 8, 4}; LeetCode350 leetCode350 = new LeetCode350(); int[] results = leetCode350.intersect(nums1, nums2); System.out.print("["); for (int index = 0; index < results.length; index++) { System.out.print(results[index]); if (index != results.length - 1) { System.out.print(","); } } System.out.print("]"); } }
goldmann/pnc
dto/src/main/java/org/jboss/pnc/dto/BuildPushResult.java
<reponame>goldmann/pnc /** * JBoss, Home of Professional Open Source. * Copyright 2014-2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.dto; import org.jboss.pnc.dto.validation.groups.WhenCreatingNew; import org.jboss.pnc.dto.validation.groups.WhenUpdating; import org.jboss.pnc.enums.BuildPushStatus; import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import java.util.List; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import lombok.Builder; import lombok.Data; /** * * @author <NAME> &lt;<EMAIL>&gt; */ @Data @Builder(builderClassName = "Builder") @JsonDeserialize(builder = BuildPushResult.Builder.class) public class BuildPushResult implements DTOEntity { @NotNull(groups = WhenUpdating.class) @Null(groups = WhenCreatingNew.class) private final Integer id; @NotNull private final Integer buildId; @NotNull private final BuildPushStatus status; @NotNull private final String log; /** * list of errors for artifact imports */ private final List<ArtifactImportError> artifactImportErrors; /** * build id assigned by brew */ private final Integer brewBuildId; /** * link to brew */ private final String brewBuildUrl; @JsonPOJOBuilder(withPrefix = "") public static final class Builder { } }
Gladg/Triburg
app/controllers/goods-received-notes.server.controller.js
<gh_stars>0 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), GoodsReceivedNote = mongoose.model('GoodsReceivedNote'), _ = require('lodash'); /** * Create a Goods received note */ exports.create = function(req, res) { var goodsReceivedNote = new GoodsReceivedNote(req.body); goodsReceivedNote.user = req.user; goodsReceivedNote.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(goodsReceivedNote); } }); }; /** * Show the current Goods received note */ exports.read = function(req, res) { res.jsonp(req.goodsReceivedNote); }; /** * Update a Goods received note */ exports.update = function(req, res) { var goodsReceivedNote = req.goodsReceivedNote ; goodsReceivedNote = _.extend(goodsReceivedNote , req.body); goodsReceivedNote.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(goodsReceivedNote); } }); }; /** * Delete an Goods received note */ exports.delete = function(req, res) { var goodsReceivedNote = req.goodsReceivedNote ; goodsReceivedNote.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(goodsReceivedNote); } }); }; /** * List of Goods received notes */ exports.list = function(req, res) { GoodsReceivedNote.find().sort('-created').populate('user', 'displayName').exec(function(err, goodsReceivedNotes) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(goodsReceivedNotes); } }); }; /** * Goods received note middleware */ exports.goodsReceivedNoteByID = function(req, res, next, id) { GoodsReceivedNote.findById(id).populate('user', 'displayName').exec(function(err, goodsReceivedNote) { if (err) return next(err); if (! goodsReceivedNote) return next(new Error('Failed to load Goods received note ' + id)); req.goodsReceivedNote = goodsReceivedNote ; next(); }); }; /** * Goods received note authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.goodsReceivedNote.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
osoco/better-ways-of-thinking-about-software
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/cms/static/js/spec/models/component_template_spec.js
<reponame>osoco/better-ways-of-thinking-about-software define(['js/models/component_template'], function(ComponentTemplate) { describe('ComponentTemplates', function() { var mockTemplateJSON = { templates: [ { category: 'problem', boilerplate_name: 'formularesponse.yaml', display_name: 'Math Expression Input' }, { category: 'problem', boilerplate_name: null, display_name: 'Blank Advanced Problem' }, { category: 'problem', boilerplate_name: 'checkboxes.yaml', display_name: 'Checkboxes' }, { category: 'problem', boilerplate_name: 'multiple_choice.yaml', display_name: 'Multiple Choice' }, { category: 'problem', boilerplate_name: 'drag_and_drop.yaml', display_name: 'Drag and Drop' }, { category: 'problem', boilerplate_name: 'problem_with_hint.yaml', display_name: 'Problem with Adaptive Hint' }, { category: 'problem', boilerplate_name: 'imageresponse.yaml', display_name: 'Image Mapped Input' }, { category: 'openassessment', boilerplate_name: null, display_name: 'Peer Assessment' }, { category: 'problem', boilerplate_name: 'an_easy_problem.yaml', display_name: 'An Easy Problem' }, { category: 'word_cloud', boilerplate_name: null, display_name: 'Word Cloud' }, { // duplicate display name to verify sort behavior category: 'word_cloud', boilerplate_name: 'alternate_word_cloud.yaml', display_name: 'Word Cloud' }], type: 'problem', support_legend: {show_legend: false} }; it('orders templates correctly', function() { var lastTemplate = null, firstComparison = true, componentTemplate = new ComponentTemplate(), template, templateName, i; componentTemplate.parse(mockTemplateJSON); for (i = 0; i < componentTemplate.templates.length; i++) { template = componentTemplate.templates[i]; templateName = template.display_name; if (lastTemplate) { if (!firstComparison || lastTemplate.boilerplate_name) { expect(lastTemplate.display_name < templateName).toBeTruthy(); } firstComparison = false; } else { // If the first template is blank, make sure that it has the correct category if (!template.boilerplate_name) { expect(template.category).toBe('problem'); } lastTemplate = template; } } }); }); });
whywhywhyw/o3de
Gems/AtomTressFX/Code/Builders/HairBuilderComponent.h
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/Component/Component.h> #include <AzCore/Asset/AssetCommon.h> #include <AzCore/Asset/AssetManager.h> #include <AssetBuilderSDK/AssetBuilderBusses.h> #include <Assets/HairAsset.h> #include <Builders/HairAssetBuilder.h> namespace AZ { namespace Render { namespace Hair { class HairBuilderComponent final : public Component { public: AZ_COMPONENT(HairBuilderComponent, "{88233F79-98DA-4DC6-A60B-0405BD810479}"); HairBuilderComponent() = default; ~HairBuilderComponent() = default; static void Reflect(ReflectContext* context); static void GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible); private: HairBuilderComponent(const HairBuilderComponent&) = delete; //////////////////////////////////////////////////////////////////////// // Component interface implementation void Activate() override; void Deactivate() override; //////////////////////////////////////////////////////////////////////// HairAssetBuilder m_hairAssetBuilder; HairAssetHandler m_hairAssetHandler; }; } // namespace Hair } // End Render namespace } // End AZ namespace
hfming/core-java
basic-concurrent/src/com/hfm/alternate/PackUnpackWay.java
<filename>basic-concurrent/src/com/hfm/alternate/PackUnpackWay.java package com.hfm.alternate; import org.junit.jupiter.api.Test; import java.util.concurrent.locks.LockSupport; /** * @author <EMAIL> * @version 1.01 2021-09-15 16:38 * @Description * @date 2021/9/15 */ public class PackUnpackWay { static Thread thread1; static Thread thread2; static Thread thread3; static final int FIVWTIME = 5; /** * 两条线程 */ @Test public void twoThread() { thread1 = new Thread(() -> { for (int i = 0; i < FIVWTIME; i++) { // 停止 LockSupport.park(); // 运行 System.out.println(Thread.currentThread().getName()); LockSupport.unpark(thread2); } }, "线程A"); thread2 = new Thread(() -> { for (int i = 0; i < FIVWTIME; i++) { LockSupport.park(); // 运行 System.out.println(Thread.currentThread().getName()); // 运行 1 LockSupport.unpark(thread1); } }, "线程B"); thread1.start(); thread2.start(); LockSupport.unpark(thread2); } /** * 三条线程 */ @Test public void twoThree() { thread1 = new Thread(() -> { for (int i = 0; i < FIVWTIME; i++) { LockSupport.park(); System.out.println(Thread.currentThread().getName()); LockSupport.unpark(thread3); } }, "线程A"); thread2 = new Thread(() -> { for (int i = 0; i < FIVWTIME; i++) { // 停止 LockSupport.park(); // 运行 System.out.println(Thread.currentThread().getName()); // 运行 1 LockSupport.unpark(thread1); } }, "线程B"); thread3 = new Thread(() -> { for (int i = 0; i < FIVWTIME; i++) { LockSupport.park(); // 运行 System.out.println(Thread.currentThread().getName()); // 运行 2 LockSupport.unpark(thread2); } }, "线程C"); thread1.start(); thread2.start(); thread3.start(); LockSupport.unpark(thread3); } static Thread thread11; static Thread thread22; static Thread thread33; /** * 通用方法 */ @Test public void universalWay() { Pack pack = new Pack(); thread11 = new Thread(() -> { pack.run("线程A", thread33); }); thread22 = new Thread(() -> { pack.run("线程B", thread11); }); thread33 = new Thread(() -> { pack.run("线程C", thread22); }); thread11.start(); thread22.start(); thread33.start(); LockSupport.unpark(thread33); } static class Pack { /** * 下一个线程 */ private Thread nextThread; /** * 是否需要停止自身线程 */ private static final int FIVWTIME = 5; public void run(String name, Thread nextThread) { this.nextThread = nextThread; Thread.currentThread().setName(name); for (int i = 0; i < FIVWTIME; i++) { LockSupport.park(); // 运行 System.out.println(Thread.currentThread().getName()); // 运行 2 LockSupport.unpark(nextThread); } } } }
andrasigneczi/TravelOptimiser
DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/ImageData.h
<gh_stars>1-10 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:set ts=2 sw=2 et tw=78: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_ImageData_h #define mozilla_dom_ImageData_h #include "nsIDOMCanvasRenderingContext2D.h" #include "mozilla/Attributes.h" #include "mozilla/dom/BindingUtils.h" #include "mozilla/dom/TypedArray.h" #include <stdint.h> #include "nsCycleCollectionParticipant.h" #include "nsISupportsImpl.h" #include "js/GCAPI.h" namespace mozilla { namespace dom { class ImageData final : public nsISupports { ~ImageData() { MOZ_COUNT_DTOR(ImageData); DropData(); } public: ImageData(uint32_t aWidth, uint32_t aHeight, JSObject& aData) : mWidth(aWidth) , mHeight(aHeight) , mData(&aData) { MOZ_COUNT_CTOR(ImageData); HoldData(); } NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(ImageData) static already_AddRefed<ImageData> Constructor(const GlobalObject& aGlobal, const uint32_t aWidth, const uint32_t aHeight, ErrorResult& aRv); static already_AddRefed<ImageData> Constructor(const GlobalObject& aGlobal, const Uint8ClampedArray& aData, const uint32_t aWidth, const Optional<uint32_t>& aHeight, ErrorResult& aRv); uint32_t Width() const { return mWidth; } uint32_t Height() const { return mHeight; } void GetData(JSContext* cx, JS::MutableHandle<JSObject*> aData) const { aData.set(GetDataObject()); } JSObject* GetDataObject() const { JS::ExposeObjectToActiveJS(mData); return mData; } bool WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector); private: void HoldData(); void DropData(); ImageData() = delete; uint32_t mWidth, mHeight; JS::Heap<JSObject*> mData; }; } // namespace dom } // namespace mozilla #endif // mozilla_dom_ImageData_h
iboxdb/db4o-gpl
db4o.j/db4o-core/core/src/com/db4o/reflect/jdk/ClassLoaderJdkLoader.java
<reponame>iboxdb/db4o-gpl /* Copyright (C) 2007 Versant Inc. http://www.db4o.com */ package com.db4o.reflect.jdk; /** * @sharpen.ignore */ public class ClassLoaderJdkLoader implements JdkLoader { private final ClassLoader _loader; /** * @exclude */ public ClassLoaderJdkLoader(ClassLoader loader) { _loader = loader; } public Class loadClass(String className) { try { return (_loader == null ? Class.forName(className) : Class.forName(className, true, _loader)); } catch (Exception e) { // e.printStackTrace(); } catch (LinkageError e) { // e.printStackTrace(); } return null; } public Object deepClone(Object context) { return new ClassLoaderJdkLoader(_loader); } }
FantasyVII/Blue-Flame-Engine
Blue-Flame-Engine/Core/BF/Graphics/Animation/DataType.h
<filename>Blue-Flame-Engine/Core/BF/Graphics/Animation/DataType.h #pragma once #include "BF/Graphics/Animation/IDataType.h" #include "BF/Common.h" namespace BF { namespace Graphics { namespace Animation { template <class T, IDataType::InternalDataType internalDataType> class DataType : public IDataType { friend class IDataType; public: T value; DataType(T value); ~DataType(); bool operator>(const DataType& rhs); bool operator>=(const DataType& rhs); bool operator<(const DataType& rhs); bool operator<=(const DataType& rhs); bool operator==(const DataType& rhs); bool operator!=(const DataType& rhs); }; #include "DataType.inl" typedef DataType<int, IDataType::InternalDataType::Int> AInt; typedef DataType<float, IDataType::InternalDataType::Float> AFloat; typedef DataType<bool, IDataType::InternalDataType::Bool> ABool; } } }
kayinli/bk-bcs
bcs-services/bcs-cluster-manager/internal/cloudprovider/state.go
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 cloudprovider import ( "context" "fmt" "time" proto "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager" "github.com/Tencent/bk-bcs/bcs-common/common/blog" ) // TaskState handle task state type TaskState struct { Task *proto.Task JobResult *SyncJobResult } // IsTerminated check task already terminated func (stat *TaskState) IsTerminated() bool { if stat.Task.Status == TaskStatusFailure || stat.Task.Status == TaskStatusForceTerminate || stat.Task.Status == TaskStatusTimeout || stat.Task.Status == TaskStatusSuccess { return true } return false } // IsReadyToStep check current step or switch step func (stat *TaskState) IsReadyToStep(stepName string) (*proto.Step, error) { switch stat.Task.Status { case TaskStatusRunning, TaskStatusInit: case TaskStatusForceTerminate: return nil, fmt.Errorf("task %s state for terminate", stat.Task.TaskID) default: return nil, fmt.Errorf("task %s is not running, state is %s", stat.Task.TaskID, stat.Task.Status) } // validate step existence curStep, exist := stat.Task.Steps[stepName] if !exist { return nil, fmt.Errorf("lost step") } // previous step success when retry task scene if curStep.Status == TaskStatusSuccess { blog.Infof("task[%s] current step[%s] successful", stat.Task.TaskID, stepName) return nil, nil } // check turn to step if stepName != stat.Task.CurrentStep { // check if pre steps are all ok, then we can set sthi step running ok := true for _, name := range stat.Task.StepSequence { step, found := stat.Task.Steps[name] if !found { return nil, fmt.Errorf("task %s fatal, lost step %s in definition", stat.Task.TaskID, name) } // found current step if name == stepName && ok { if step.Status == TaskStatusSuccess { return nil, fmt.Errorf("task %s step %s already success", stat.Task.TaskID, stepName) } stat.Task.CurrentStep = stepName step.Status = TaskStatusRunning step.Message = "step ready to run" step.LastUpdate = time.Now().Format(time.RFC3339) stat.Task.Steps[name] = step GetStorageModel().UpdateTask(context.Background(), stat.Task) return step, nil } //check this step is ok if step.Status != TaskStatusSuccess { ok = false break } } return nil, fmt.Errorf("step %s don't turn to run, task already failed", stepName) } // refresh step status & task status if curStep.Status == TaskStatusFailure { curStep.Retry++ } curStep.Status = TaskStatusRunning curStep.Message = "step ready to run" curStep.LastUpdate = time.Now().Format(time.RFC3339) stat.Task.Status = TaskStatusRunning stat.Task.Message = fmt.Sprintf("step %s is running", stepName) stat.Task.LastUpdate = curStep.LastUpdate //update state in storage if err := GetStorageModel().UpdateTask(context.Background(), stat.Task); err != nil { blog.Errorf("task %s fatal, update task status failed, %s. required admin intervetion", stat.Task.TaskID, err.Error()) return nil, err } blog.Infof("task %s step %s turn to running", stat.Task.TaskID, stepName) return curStep, nil } //UpdateStepSucc update step to success func (stat *TaskState) UpdateStepSucc(start time.Time, stepName string) error { step := stat.Task.Steps[stepName] end := time.Now() step.ExecutionTime = uint32(end.Unix() - start.Unix()) step.Start = start.Format(time.RFC3339) step.End = end.Format(time.RFC3339) step.Status = TaskStatusSuccess step.LastUpdate = step.End step.Message = "running successfully" stat.Task.Status = TaskStatusRunning stat.Task.Message = fmt.Sprintf("step %s running successfully", step.Name) stat.Task.LastUpdate = step.End if stepName == stat.Task.StepSequence[len(stat.Task.StepSequence)-1] { // last step in task, just make whole task success taskStart, _ := time.Parse(time.RFC3339, stat.Task.Start) stat.Task.End = end.Format(time.RFC3339) stat.Task.ExecutionTime = uint32(end.Unix() - taskStart.Unix()) stat.Task.Status = TaskStatusSuccess stat.Task.Message = fmt.Sprintf("whole task running successfully") if stat.JobResult != nil { err := stat.JobResult.UpdateJobResultStatus(true) if err != nil { blog.Errorf("task[%s] stepName[%s] UpdateJobResultStatus failed: %v", stat.Task.TaskID, stepName, err) } else { blog.Infof("task[%s] stepName[%s] UpdateJobResultStatus successful", stat.Task.TaskID, stepName) } } } if err := GetStorageModel().UpdateTask(context.Background(), stat.Task); err != nil { blog.Errorf("task %s fatal, update task success status failed, %s. required admin intervetion", stat.Task.TaskID, err.Error()) return err } blog.Infof("task %s step %s running successfully", stat.Task.TaskID, stepName) return nil } // UpdateStepFailure update step failure func (stat *TaskState) UpdateStepFailure(start time.Time, stepName string, err error) error { step := stat.Task.Steps[stepName] end := time.Now() step.ExecutionTime = uint32(end.Unix() - start.Unix()) step.Start = start.Format(time.RFC3339) step.End = end.Format(time.RFC3339) step.Status = TaskStatusFailure step.LastUpdate = step.End step.Message = fmt.Sprintf("running fialed, %s", err.Error()) taskStart, _ := time.Parse(time.RFC3339, stat.Task.Start) stat.Task.End = end.Format(time.RFC3339) stat.Task.ExecutionTime = uint32(end.Unix() - taskStart.Unix()) stat.Task.Status = TaskStatusFailure stat.Task.Message = fmt.Sprintf("step %s running failed, %s", step.Name, err.Error()) stat.Task.LastUpdate = step.End if err := GetStorageModel().UpdateTask(context.Background(), stat.Task); err != nil { blog.Errorf("task %s fatal, update task step %s failure status failed, %s. required admin intervetion", stat.Task.TaskID, stepName, err.Error()) return err } if stat.JobResult != nil { err = stat.JobResult.UpdateJobResultStatus(false) if err != nil { blog.Errorf("task[%s] stepName[%s] UpdateJobResultStatus failed: %v", stat.Task.TaskID, stepName, err) } else { blog.Infof("task[%s] stepName[%s] UpdateJobResultStatus successful", stat.Task.TaskID, stepName) } } blog.Infof("task %s step %s running failure", stat.Task.TaskID, stepName) return nil }
sajalguptajft/cobbzilla-wizard
wizard-server/src/main/java/org/cobbzilla/wizard/server/RestServerLifecycleListenerBase.java
<reponame>sajalguptajft/cobbzilla-wizard<filename>wizard-server/src/main/java/org/cobbzilla/wizard/server/RestServerLifecycleListenerBase.java package org.cobbzilla.wizard.server; import org.cobbzilla.wizard.server.config.RestServerConfiguration; public class RestServerLifecycleListenerBase<C extends RestServerConfiguration> implements RestServerLifecycleListener<C> { @Override public void beforeStart(RestServer server) {} @Override public void onStart(RestServer server) {} @Override public void beforeStop(RestServer server) {} @Override public void onStop(RestServer server) {} }
pacoolin/octopus
1.utils/core/src/main/java/com/octopus/utils/balance/qps/QPSManager.java
package com.octopus.utils.balance.qps; import com.octopus.isp.tools.IDataGet; import com.octopus.utils.alone.ArrayUtils; import com.octopus.utils.alone.ObjectUtils; import com.octopus.utils.alone.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.master.SplitLogManager; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; /** 1.最快通道可以空任务,等待快速任务过来 2.最慢通道可以处理快速的任务 3.n是奇数 3.获取的一批task按cost 从小到大排序。小的优先进入assign。同时优先的放在前面,排除是重要task。 4.没有名次类型时,取0-n最短等待队列,放入。 4.处理慢的后几名,且n队列数量最少,放入n队列。否则从1-n-1找一个最短等待队列 5.中等task找从1-n找最小等待队列,放入任务。 6.快速的task从0-n找最短等待队列,放入。 7.几名=任务种类/Q数 8. 如果任务种类数=1,直接0-n取最小等待Q。种类数〉1 and < Q, 最慢的为慢类型,最快的为快类型,其他中等。 10.Queue组有自动调整的功能,保证快速task优先处理。找到最短的队列,找其中最大的task,如果不是优先任务,且属于慢任务,把这个任务移入n队列。有个定时任务,当get不到数据时,把n的任务安处理最短时间重新分配,防止有些Q空闲。nQ过多task。 11。如果一个平时正常的任务,执行超过2倍时间,需要把相同的任务还在其它队列中的task移入慢队列。 * Created by Administrator on 2018/11/6. */ public class QPSManager { transient static Log log = LogFactory.getLog(QPSManager.class); List<Queue> queues = new LinkedList<Queue>(); int quickQueueIndex=0; int slowQueueIndex=-1; Stat stat = null; String[] taskKindKeyPaths; String[] importants; String importantTaskKeyPath; static long cacheMaxSize=5000; //max doing with order in member long receiveTime=0; String iDPath; Timer t = new Timer(); Map processingDataCaches = new HashMap(); boolean isAssigned; boolean isStopReceiver=false; IDataGetter dataGetter =null; public QPSManager(String iDPath,int queueCount,int queueSize,String[] taskKindKeyPaths,String importantTaskKeyPath,String[] importantValues, IProcess process,int AfterQuickCost,int BeginSlowCost) { this(null,0,iDPath,queueCount, queueSize, taskKindKeyPaths, importantTaskKeyPath, importantValues, process,AfterQuickCost,BeginSlowCost); } /** * * @param queueCount 队列的数量,一个快队列,一个慢队列,多个normal队列 * @param queueSize 每个队列大小,可以存放排队的任务 * @param taskKindKeyPaths 任务数据中能够表明同一种处理业务的属性名称,可以有多个属性表明一种业务类型 * @param importantTaskKeyPath 任务数据中能够表明重要任务的属性名称,重要的任务不做快慢队列处理 * @param importantValues 重要任务的属性值 * @param process 任务处逻辑 */ public QPSManager(IDataGetter dataGetter,long getDataIntervalTime,String iDPath,int queueCount,int queueSize,String[] taskKindKeyPaths,String importantTaskKeyPath,String[] importantValues, IProcess process,long AfterQuickCost,long BeginSlowCost){ this.taskKindKeyPaths=taskKindKeyPaths; this.importantTaskKeyPath=importantTaskKeyPath; this.importants=importantValues; stat = new Stat(BeginSlowCost,AfterQuickCost); for(int i=0;i<queueCount;i++) { queues.add(new Queue(queueSize,process,stat,processingDataCaches)); } quickQueueIndex=0; this.iDPath = iDPath; slowQueueIndex=queueCount-1; DoSlowTimeTask sl = new DoSlowTimeTask(this); t.schedule(sl,1000,1000); this.dataGetter =dataGetter; if(null != dataGetter){ t.schedule(new GetDataTask(dataGetter),1000,getDataIntervalTime); } } public boolean stopReceiver(){ isStopReceiver=true; return true; } public boolean startReceiver(){ isStopReceiver=false; return true; } public Object receive(Object data){ if(!isStopReceiver) { isAssigned = false; receiveTime = System.currentTimeMillis(); assign(appendData(data)); isAssigned = true; } return null; } static int point=0; public void assignByRoundRobin(TaskData data){ if(null != data) { try { int n = point++ % queues.size(); queues.get(n).put(data); log.debug("queue "+n+" add task "+data.getCost()); processingDataCaches.put(data.getId(), data); }catch (Exception e){ } } } //get key by keypths String getKindKey(Object data){ StringBuffer sb = new StringBuffer(); if(null != taskKindKeyPaths){ for(String k:taskKindKeyPaths) { String p = (String)ObjectUtils.getValueByPath(data, k); if(null != p) { sb.append(p.concat("_")); } } } return sb.toString(); } String getId(Object data){ return (String)ObjectUtils.getValueByPath(data, iDPath); } boolean isImportantTask(Object data){ if(importantTaskKeyPath!=null) { String p = (String) ObjectUtils.getValueByPath(data, importantTaskKeyPath); if (null != p) { if(ArrayUtils.isArrayLikeString(importants,p)){ return true; } } } return false; } TaskData appendData(Object data){ String k = getKindKey(data); String id = getId(data); long cost = stat.getCost(k); TaskData t = new TaskData(); t.setObj(data); t.setCost(cost); t.setKindKey(k); t.setPutQueueTime(System.currentTimeMillis()); t.setImportant(isImportantTask(data)); t.setId(id); return t; } private List appendListCost(Object[] data){ if(null != data){ List ret = new LinkedList(); for(Object o:data){ if(null !=o){ ret.add(appendData(o)); } } return ret; } return null; } public Object receives(Object[] data){ if(!isStopReceiver) { isAssigned = false; receiveTime = System.currentTimeMillis(); List<TaskData> ll = appendListCost(data); List<TaskData> ret = sortByCost(ll); if (null != ret) { for (TaskData o : ret) { assign(o); } } isAssigned = true; } return null; } private void assign(TaskData o){ if(processingDataCaches.containsKey(o.getId())){ return;// it has existed, so ignore it } int slowQueueSize=-1; long quickQueueCost=0; int minCostQueueNotFastAndSlowIndex=0; //int minCostQueueIndexNotQuickIndex=0; int minSizeQueueIndex=0; int minQueueSize=-1; int quickUseIndex=quickQueueIndex; int slowUseIndex=slowQueueIndex; long l=-1; for(int i=1;i<queues.size()-1;i++){ long t = queues.get(i).getWaitingTime(); if(t==0)t=queues.get(i).size(); int s = queues.get(i).size(); if(l==-1 || l>t){ l=t; minCostQueueNotFastAndSlowIndex=i; /*if(i!=quickQueueIndex){ minCostQueueIndexNotQuickIndex=i; }*/ } if(minQueueSize==-1 || minQueueSize>s){ minQueueSize=s; minSizeQueueIndex=i; } } if(queues.get(quickQueueIndex).getWaitingTime()>queues.get(minCostQueueNotFastAndSlowIndex).getWaitingTime()||(queues.get(quickQueueIndex).getWaitingTime()==queues.get(minCostQueueNotFastAndSlowIndex).getWaitingTime() && queues.get(quickQueueIndex).size()>queues.get(minCostQueueNotFastAndSlowIndex).size())){ quickUseIndex=minCostQueueNotFastAndSlowIndex; } if(queues.get(slowQueueIndex).getWaitingTime()>queues.get(minCostQueueNotFastAndSlowIndex).getWaitingTime()||(queues.get(slowQueueIndex).getWaitingTime()==queues.get(minCostQueueNotFastAndSlowIndex).getWaitingTime() && queues.get(slowQueueIndex).size()>queues.get(minCostQueueNotFastAndSlowIndex).size())){ slowUseIndex=minCostQueueNotFastAndSlowIndex; } //if slow task and slow queue size is min then put the task to slow queue if(o.getCost()>stat.getBeginSlowCost()){ if(slowUseIndex!=slowQueueIndex) { TaskData mc = queues.get(slowUseIndex).getMaxCostTask(); if (null != mc) { if (mc.getCost() > stat.getBeginSlowCost()) { if(queues.get(slowUseIndex).remove(mc)) { log.debug(" queue "+slowUseIndex+" remove task "+mc.getCost()); try { synchronized (mc) { queues.get(slowQueueIndex).put(mc); log.debug("5 queue "+slowQueueIndex+" add task "+mc.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(mc.getId(), mc); } }catch (Exception e){ log.error("put queue error",e); } } } } } try { //System.out.println("-P:"+(minCostQueueIndex+" - "+((TaskData)o).getCost())); synchronized (o) { queues.get(slowUseIndex).put(o); log.debug("7 queue "+slowUseIndex+" add task "+o.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(o.getId(), o); } }catch (Exception e){ log.error("put queue error",e); } /*try { if (slowUseIndex != slowQueueIndex) { //System.out.println("-P:"+(slowQueueIndex+" - "+((TaskData)o).getCost())); synchronized (o) { queues.get(slowQueueIndex).put(o); log.debug("1 queue "+slowQueueIndex+" add task "+o.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(o.getId(), o); } } else { //System.out.println("-P:"+(minCostQueueIndexNotQuickIndex+" - "+((TaskData)o).getCost())); synchronized (o) { queues.get(minCostQueueNotFastAndSlowIndex).put(o); log.debug("2 queue "+minCostQueueNotFastAndSlowIndex+" add task "+o.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(o.getId(), o); } } }catch (Exception e){ log.error("put queue error",e); }*/ }else if(o.getCost()>stat.getAfterQuickCost()){ //if it is normal task //if min cost queue is not slow queue and exist slow task then move slow task to slow queue if(minCostQueueNotFastAndSlowIndex!=slowQueueIndex) { TaskData mc = queues.get(minCostQueueNotFastAndSlowIndex).getMaxCostTask(); if (null != mc) { if (mc.getCost() > stat.getBeginSlowCost()) { if(queues.get(minCostQueueNotFastAndSlowIndex).remove(mc)) { log.debug(" queue "+minCostQueueNotFastAndSlowIndex+" remove task "+mc.getCost()); try { synchronized (mc) { queues.get(slowQueueIndex).put(mc); log.debug("3 queue "+slowQueueIndex+" add task "+mc.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(mc.getId(), mc); } }catch (Exception e){ log.error("put queue error",e); } } } } } //put normal task to min cost queue exclude quick queue try { //System.out.println("-P:"+(minCostQueueIndexNotQuickIndex+" - "+((TaskData)o).getCost())); synchronized (o) { queues.get(minCostQueueNotFastAndSlowIndex).put(o); log.debug("4 queue "+minCostQueueNotFastAndSlowIndex+" add task "+o.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(o.getId(), o); } }catch(Exception e){ log.error("put queue error",e); } }else{ //if it quick task if(quickUseIndex!=slowQueueIndex) { TaskData mc = queues.get(quickUseIndex).getMaxCostTask(); if (null != mc) { if (mc.getCost() > stat.getBeginSlowCost()) { if(queues.get(quickUseIndex).remove(mc)) { log.debug(" queue "+quickUseIndex+" remove task "+mc.getCost()); try { synchronized (mc) { queues.get(slowQueueIndex).put(mc); log.debug("5 queue "+slowQueueIndex+" add task "+mc.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(mc.getId(), mc); } }catch (Exception e){ log.error("put queue error",e); } } } } } try { //System.out.println("-P:"+(minCostQueueIndex+" - "+((TaskData)o).getCost())); synchronized (o) { queues.get(quickUseIndex).put(o); log.debug("6 queue "+quickUseIndex+" add task "+o.getCost()+" slow "+stat.getBeginSlowCost()+" quick "+stat.getAfterQuickCost()); processingDataCaches.put(o.getId(), o); } }catch (Exception e){ log.error("put queue error",e); } } } //一批task按cost 从小到大排序 private List sortByCost(List<TaskData> data){ Collections.sort(data, new Comparator(){ @Override public int compare(Object o1, Object o2) { if(o1 instanceof TaskData && o2 instanceof TaskData ){ if(((TaskData) o1).isImportant || ((TaskData) o2).isImportant) return 0; return ((TaskData) o1).getCost()>((TaskData) o2).getCost()?1:-1; } return 0; } }); return data; } class GetDataTask extends TimerTask{ IDataGetter getter; AtomicBoolean can; public GetDataTask(IDataGetter dataGetter){ this.getter=dataGetter; } @Override public void run() { if(!isStopReceiver && processingDataCaches.size()<cacheMaxSize) { if (null != getter) { List dl = getter.getDataEachTime(); if(null != dl && dl.size()>0) { receives(dl.toArray()); } } } } } class DoSlowTimeTask extends TimerTask{ QPSManager qps; boolean isrun =false; public DoSlowTimeTask(QPSManager m){ qps = m; } @Override public void run() { //not receive data in 3 seconds if(!isrun && System.currentTimeMillis()-qps.receiveTime>3000){ isrun=true; int minCostQueueIndexNotQuickIndex=-1; isrun=true; while(queues.get(slowQueueIndex).size()>2 && minCostQueueIndexNotQuickIndex!=slowQueueIndex) { long l = -1; for (int i = 0; i < queues.size(); i++) { long t = queues.get(i).getWaitingTime(); if (l == -1 || l > t) { l = t; if (i != quickQueueIndex) { minCostQueueIndexNotQuickIndex = i; } } } if (minCostQueueIndexNotQuickIndex>0 && minCostQueueIndexNotQuickIndex != slowQueueIndex) { TaskData td = queues.get(slowQueueIndex).getLast(); if (null != td) { try { queues.get(minCostQueueIndexNotQuickIndex).put(td); }catch (Exception e){ log.error("put queue error",e); } } } } isrun=false; } } } public boolean shutdown(){ t.cancel(); if(null != queues){ for(Queue q :queues){ q.shutdown(); } } return true; } public boolean isAssigned() { return isAssigned; } public boolean isEmpty(){ for(Queue q:queues){ if(!q.isEmpty()){ return false; } } return true; } public boolean waitingFinished(){ if(null != dataGetter) {//停止采集任务 dataGetter.stopReceive(); } stopReceiver();//停止队列接收任务 for(Queue q:queues){ if(!q.waitingFinished()){ return false; } } return true; } }