repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ceekay1991/AliPayForDebug
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/NBDebugAppPreferManager.h
<reponame>ceekay1991/AliPayForDebug // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @class APPreferencesAccessor, NSMutableDictionary; @interface NBDebugAppPreferManager : NSObject { NSMutableDictionary *_preferlist; APPreferencesAccessor *_dataAccessor; } @property(retain, nonatomic) APPreferencesAccessor *dataAccessor; // @synthesize dataAccessor=_dataAccessor; @property(retain, nonatomic) NSMutableDictionary *preferlist; // @synthesize preferlist=_preferlist; - (void).cxx_destruct; - (void)save; - (void)removeAppId:(id)arg1; - (id)preferModelForApp:(id)arg1; - (void)addInfo:(id)arg1; - (_Bool)needUsePreferApp:(id)arg1 params:(id)arg2 preferModel:(id *)arg3; - (id)init; @end
ogii-test/ddp-study-server
pepper-apis/src/main/java/org/broadinstitute/ddp/model/event/MarkActivitiesReadOnlyEventAction.java
<gh_stars>1-10 package org.broadinstitute.ddp.model.event; import java.util.HashSet; import java.util.Set; import org.broadinstitute.ddp.db.dao.ActivityInstanceDao; import org.broadinstitute.ddp.db.dto.EventConfigurationDto; import org.broadinstitute.ddp.pex.PexInterpreter; import org.jdbi.v3.core.Handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An action that marks all of a participant's activity instances for specified target activities as read-only. */ public class MarkActivitiesReadOnlyEventAction extends EventAction { private static final Logger LOG = LoggerFactory.getLogger(MarkActivitiesReadOnlyEventAction.class); private Set<Long> targetActivityIds = new HashSet<>(); public MarkActivitiesReadOnlyEventAction(EventConfiguration eventConfiguration, EventConfigurationDto dto) { this(eventConfiguration, dto.getTargetActivityIds()); } public MarkActivitiesReadOnlyEventAction(EventConfiguration eventConfiguration, Set<Long> targetActivityIds) { super(eventConfiguration, null); if (targetActivityIds != null) { this.targetActivityIds.addAll(targetActivityIds); } } @Override public void doAction(PexInterpreter interpreter, Handle handle, EventSignal signal) { int numUpdated = handle.attach(ActivityInstanceDao.class) .bulkUpdateReadOnlyByActivityIds(signal.getParticipantId(), true, targetActivityIds); LOG.info("Marked {} activity instances read-only for participant {} and target activities {}", numUpdated, signal.getParticipantGuid(), targetActivityIds); } }
Athrunen/xpresso
src/main/java/com/wantedtech/common/xpresso/sentence/pos/en/stanford/MaxentPosTagger.java
package com.wantedtech.common.xpresso.sentence.pos.en.stanford; import java.util.ArrayList; import java.util.List; import com.wantedtech.common.xpresso.x; import com.wantedtech.common.xpresso.sentence.PosTagger; import com.wantedtech.common.xpresso.sentence.Sentence; import com.wantedtech.common.xpresso.text.Tokenizer; import com.wantedtech.common.xpresso.text.tokenizer.en.stanford.RuleBasedTokenizer; import com.wantedtech.common.xpresso.token.Token; import com.wantedtech.common.xpresso.types.list; import com.wantedtech.common.xpresso.types.tuples.tuple2; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.tagger.maxent.MaxentTagger; import edu.stanford.nlp.tagger.maxent.TaggerConfig; import edu.stanford.nlp.util.StringUtils; public class MaxentPosTagger implements PosTagger { public enum Model { ENGLISH_LEFT_3_WORDS("pos/english-left3words-distsim.tagger"), ENGLISH_BIDIRECTIONAL_DISTSIM("pos/english-bidirectional-distsim.tagger"); public String fileName; Model(String fileName) { this.fileName = fileName; } } MaxentTagger tagger; public MaxentPosTagger(Model model) { tagger = new MaxentTagger(model.fileName, StringUtils.argsToProperties("-model", model.fileName)); } public MaxentPosTagger() { tagger = new MaxentTagger(MaxentPosTagger.Model.ENGLISH_LEFT_3_WORDS.fileName, StringUtils.argsToProperties("-model", MaxentPosTagger.Model.ENGLISH_LEFT_3_WORDS.fileName)); } public Sentence tag(Sentence sent) { List<HasWord> ss = new ArrayList<HasWord>(); for (Token t : sent) { HasWord hw = new Word(); hw.setWord(t.toString()); ss.add(hw); } List<TaggedWord> sst = tagger.tagSentence(ss); for (tuple2<Integer,TaggedWord> item : x.enumerate(sst)) { Token tk = sent.get(item.key); tk.annotate("pos", item.value.tag()); sent.setAt(item.key).value(tk); } return sent; } @Override public list<Sentence> tag(String text) { Tokenizer tokenizer = new RuleBasedTokenizer(); list<Sentence> result = x.list(); for (Sentence s : tokenizer.tokenize(text)) { tag(s); result.append(s); } return result; } }
jrmie/math
test/unit/math/rev/mat/fun/accumulator_test.cpp
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/util.hpp> #include <vector> // test sum of first n numbers for sum of a void test_sum(stan::math::accumulator<stan::math::var>& a, int n) { EXPECT_FLOAT_EQ((n * (n + 1)) / 2, a.sum().val()); } TEST(AgradRevMatrix, accumulateDouble) { using stan::math::accumulator; using stan::math::var; accumulator<var> a; test_sum(a, 0); a.add(var(1.0)); test_sum(a, 1); for (int i = 2; i <= 1000; ++i) a.add(var(i)); test_sum(a, 1000); } TEST(AgradRevMathMatrix, accumulateCollection) { // tests int, double, vector<double>, vector<int>, // Matrix<double, ...>, // var, vector<var>, Matrix<var, ...>, // and recursions of vector<T> using Eigen::Dynamic; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::VectorXd; using stan::math::accumulator; using stan::math::var; using std::vector; accumulator<var> a; int pos = 0; test_sum(a, 0); vector<var> v(10); for (size_t i = 0; i < 10; ++i) v[i] = var(pos++); a.add(v); test_sum(a, pos - 1); vector<double> d(10); for (size_t i = 0; i < 10; ++i) d[i] = pos++; a.add(d); test_sum(a, pos - 1); var x = pos++; a.add(x); test_sum(a, pos - 1); int nnn = pos++; a.add(nnn); test_sum(a, pos - 1); double xxx = pos++; a.add(xxx); test_sum(a, pos - 1); vector<int> u(10); for (size_t i = 0; i < 10; ++i) a.add(pos++); test_sum(a, pos - 1); vector<vector<int> > ww(10); for (size_t i = 0; i < 10; ++i) { vector<int> w(5); for (size_t n = 0; n < 5; ++n) w[n] = pos++; ww[i] = w; } a.add(ww); test_sum(a, pos - 1); MatrixXd m(5, 6); for (int i = 0; i < 5; ++i) for (int j = 0; j < 6; ++j) m(i, j) = pos++; a.add(m); test_sum(a, pos - 1); VectorXd mv(7); for (int i = 0; i < 7; ++i) mv(i) = pos++; a.add(mv); test_sum(a, pos - 1); vector<VectorXd> vvx(8); for (size_t i = 0; i < 8; ++i) { VectorXd vx(3); for (int j = 0; j < 3; ++j) vx(j) = pos++; vvx[i] = vx; } a.add(vvx); test_sum(a, pos - 1); Matrix<var, Dynamic, Dynamic> mvar(5, 6); for (int i = 0; i < 5; ++i) for (int j = 0; j < 6; ++j) mvar(i, j) = pos++; a.add(mvar); test_sum(a, pos - 1); Matrix<var, 1, Dynamic> mvvar(7); for (int i = 0; i < 7; ++i) mvvar(i) = pos++; a.add(mvvar); test_sum(a, pos - 1); vector<Matrix<var, Dynamic, 1> > vvx_var(8); for (size_t i = 0; i < 8; ++i) { Matrix<var, Dynamic, 1> vx_var(3); for (int j = 0; j < 3; ++j) vx_var(j) = pos++; vvx_var[i] = vx_var; } a.add(vvx_var); test_sum(a, pos - 1); } TEST(AgradRevMatrix, check_varis_on_stack) { stan::math::accumulator<stan::math::var> a; test::check_varis_on_stack(a.sum()); a.add(1); test::check_varis_on_stack(a.sum()); }
TanmayChaturvedi1/Low_Power_Embedded_Design_Techniques_2019
platform/radio/rail_lib/common/rail_assert_error_codes.h
/***************************************************************************//** * @file rail_assert_error_codes.h * @brief Definition of error codes that occur in rail for use in * RAILCb_AssertFailed. This file is purely informational and optional - * it need not be included even if rail_assert libraries are included. * @copyright Copyright 2017 Silicon Laboratories, Inc. www.silabs.com ******************************************************************************/ #ifndef __RAIL_ASSERT_ERROR_CODES_H__ #define __RAIL_ASSERT_ERROR_CODES_H__ #include "rail_types.h" /** * @addtogroup Assertions * @{ */ /** * Enumeration of all possible error codes from RAIL_ASSERT */ RAIL_ENUM_GENERIC(RAIL_AssertErrorCodes_t, uint32_t) { RAIL_ASSERT_FAILED_APPENDED_INFO_MISSING = 0, RAIL_ASSERT_FAILED_RX_FIFO_BYTES = 1, RAIL_ASSERT_FAILED_RX_FIFO_ZERO_BYTES_READ = 2, RAIL_ASSERT_FAILED_ILLEGAL_RXLEN_ENTRY_STATUS = 3, RAIL_ASSERT_FAILED_BAD_PACKET_LENGTH = 4, RAIL_ASSERT_FAILED_SYNTH_DIVCTRL_ENUM_CONVERSION_ERROR = 5, RAIL_ASSERT_FAILED_UNEXPECTED_STATE_RX_FIFO = 6, RAIL_ASSERT_FAILED_UNEXPECTED_STATE_RXLEN_FIFO = 7, RAIL_ASSERT_FAILED_UNEXPECTED_STATE_TX_FIFO = 8, RAIL_ASSERT_FAILED_UNEXPECTED_STATE_TXACK_FIFO = 9, RAIL_ASSERT_FAILED_PBUFFER_NOT_DEFINED = 10, RAIL_ASSERT_FAILED_INSUFFICIENT_BYTES_IN_RX_PACKET = 11, RAIL_ASSERT_FAILED_CLOCK_PRESCALER = 12, RAIL_ASSERT_FAILED_RTCC_POST_WAKEUP = 13, RAIL_ASSERT_FAILED_SYNTH_VCO_FREQUENCY = 14, RAIL_ASSERT_FAILED_RAC_STATE = 15, RAIL_ASSERT_FAILED_RETIME_LIMIT = 16, RAIL_ASSERT_FAILED_NESTED_SEQUENCER_LOCK = 17, RAIL_ASSERT_FAILED_RSSI_AVERAGE_DONE = 18, RAIL_ASSERT_FAILED_DFL_BITS_SIZE = 19, RAIL_ASSERT_FAILED_PROTIMER_RANDOM_SEED = 20, RAIL_ASSERT_FAILED_EFR32XG1_REGISTER_SIZE = 21, RAIL_ASSERT_FAILED_PROTIMER_CHANNEL = 22, RAIL_ASSERT_FAILED_TIMER_REQUIRES_WRAP = 23, RAIL_ASSERT_FAILED_BASECNTTOP = 24, RAIL_ASSERT_FAILED_DEPRECATED_LBTRETRY = 25, RAIL_ASSERT_FAILED_RTCC_SYNC_MISSED = 26, RAIL_ASSERT_FAILED_CLOCK_SOURCE_NOT_READY = 27, RAIL_ASSERT_FAILED_TIMINGS_INVALID = 28, RAIL_ASSERT_NULL_HANDLE = 29, RAIL_ASSERT_FAILED_SCHED_TIMER_NOT_RUNNING = 30, RAIL_ASSERT_FAILED_NO_ACTIVE_CONFIG = 31, RAIL_ASSERT_FAILED_NO_ACTIVE_HANDLE_SWITCH = 32, RAIL_ASSERT_FAILED_RFINIT = 33, RAIL_ASSERT_FAILED_NO_ACTIVE_HANDLE_SCHEDRX = 34, RAIL_ASSERT_FAILED_INVALID_HANDLE_SCHEDTX = 35, RAIL_ASSERT_FAILED_INACTIVE_HANDLE_SCHEDTX = 36, RAIL_ASSERT_FAILED_CONFIG_INDEX_INVALID = 37, RAIL_ASSERT_FAILED_NO_ACTIVE_HANDLE_SINGLEPROTOCOL = 38, RAIL_ASSERT_DEPRECATED_FUNCTION = 39, RAIL_ASSERT_MULTIPROTOCOL_NO_EVENT = 40, RAIL_ASSERT_FAILED_INVALID_INTERRUPT_ENABLED = 41, RAIL_ASSERT_CONVERSION_CURVES_NOT_INITIALIZED = 42, RAIL_ASSERT_DIVISION_BY_ZERO = 43, RAIL_ASSERT_CANT_USE_HARDWARE = 44, RAIL_ASSERT_NULL_PARAMETER = 45, RAIL_ASSERT_INVALID_TASK_TYPE = 46, RAIL_ASSERT_SMALL_SYNTH_RADIO_CONFIG_BUFFER = 47, RAIL_ASSERT_CHANNEL_HOPPING_BUFFER_TOO_SHORT = 48, RAIL_ASSERT_INVALID_MODULE_ACTION = 49, }; /// Use this define to create an array of error messages that map to the codes /// in \ref RAIL_AssertErrorCodes_t. You can use these to print slightly more /// detailed error strings related to a particular assert error code if desired. /// For example, you could implement your assert failed callback as follows to /// make use of this. /// /// @code{.c} /// void RAILCb_AssertFailed(RAIL_Handle_t railHandle, uint32_t errorCode) /// { /// static const char* railErrorMessages[] = RAIL_ASSERT_ERROR_MESSAGES; /// const char *errorMessage = "Unknown"; /// /// // If this error code is within the range of known error messages then use /// // the appropriate error message. /// if (errorCode < (sizeof(railErrorMessages) / sizeof(char*))) { /// errorMessage = railErrorMessages[errorCode]; /// } /// printf(errorMessage); /// /// // Reset the chip since an assert is a fatal error /// NVIC_SystemReset(); /// } /// @endcode /// #define RAIL_ASSERT_ERROR_MESSAGES { \ /* 0*/ "Appended info missing from Rx packet", \ /* 1*/ "Payload bytes missing from Rx packet", \ /* 2*/ "Error reading back packet payload", \ /* 3*/ "Receive fifo entry has invalid status", \ /* 4*/ "Receive fifo entry bad packet length", \ /* 5*/ "Unable to configure radio for IR calibration", \ /* 6*/ "Reached unexpected state while handling Rx fifo events", \ /* 7*/ "Reached unexpected state while handling RXLEN fifo events", \ /* 8*/ "Reached unexpected state while handling Tx fifo events", \ /* 9*/ "Reached unexpected state while handling Tx ACK fifo events", \ /*10*/ "No memory to store receive packet", \ /*11*/ "Packet length longer than the receive FIFO size", \ /*12*/ "Invalid radio clock prescaler", \ /*13*/ "Error synchronizing the RAIL timebase after sleep", \ /*14*/ "VCO frequency outside supported range", \ /*15*/ "Radio active while changing channels", \ /*16*/ "Unable to configure DCDC retiming", \ /*17*/ "Nested attempt to lock the sequencer", \ /*18*/ "RSSI averaging enabled without a valid callback", \ /*19*/ "Invalid dynamic frame length setting provided (dflBits)", \ /*20*/ "Unable to seed radio pseudo random number generator", \ /*21*/ "Timeout exceeds EFR32XG1 register size", \ /*22*/ "Invalid timer channel specified", \ /*23*/ "Timer value larger than RAIL timebase", \ /*24*/ "LBT config exceeds EFR32XG1 register size", \ /*25*/ "Deprecated CSMA/LBT retry callback unexpectedly called", \ /*26*/ "Could not synchronize RAIL timebase with the RTC", \ /*27*/ "Clock source not ready", \ /*28*/ "Attempted to set RAIL timings to invalid value", \ /*29*/ "NULL was supplied as a RAIL_Handle_t argument", \ /*30*/ "Scheduled timer not running", \ /*31*/ "No active config to switch from", \ /*32*/ "No active handle after switch", \ /*33*/ "RfInit failed to configure active state", \ /*34*/ "No active handle for scheduled rx", \ /*35*/ "Invalid handle for scheduled tx", \ /*36*/ "Inactive handle for scheduled tx", \ /*37*/ "Invalid config index to switch to", \ /*38*/ "No active handle for single protocol", \ /*39*/ "This function is deprecated and must not be called", \ /*40*/ "Multiprotocol task started with no event to run", \ /*41*/ "Invalid interrupt enabled", \ /*42*/ "Power conversion functions called before curves were initialized", \ /*43*/ "Division by zero", \ /*44*/ "Function cannot be called without access to the hardware", \ /*45*/ "Pointer parameter was passed as NULL", \ /*46*/ "Invalid task type passed to RAIL_SetTaskPriority", \ /*47*/ "Synth radio config buffer for channel hopping too small", \ /*48*/ "Buffer provided for RX Channel Hopping is too small.", \ /*49*/ "Invalid action was attempted on a module", \ } /** * @} */ #endif // __RAIL_ASSERT_ERROR_CODES_H__
rozzac90/new_nba
nba/utils.py
import datetime from nba.exceptions import ApiError def clean_time(col): """ Parse a UTC time column to datetime. :param col: column to be parsed. :returns: datetime column :rtype: series """ return col.apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%fZ")) def filter_dicts(d): """ Filter dict to remove None values. :param d: data to filter :type d: dict :returns: filtered data :rtype: dict """ return dict((k, v) for k, v in d.items() if v is not None) def clean_locals(params): """ Clean up locals dict, remove empty and self params. :params params: locals dicts from a function. :type params: dict :returns: cleaned locals dict to use as params for functions :rtype: dict """ return HDict( dict( (clean_param_key(k), HDict(v)) if isinstance(v, dict) else (clean_param_key(k), tuple(v)) if isinstance(v, list) else (clean_param_key(k), v) for k, v in params.items() if v is not None and k not in ["self", "session", "idx_data"] ) ) def clean_param_key(key): return "".join( [k.upper() if k in ["id", "po"] else k.title() for k in key.split("_")] ) def check_status_code(response, codes=None): """Checks response.status_code is in codes :param response: Requests response :param codes: List of accepted codes or callable :raises: StatusCodeError if code invalid """ codes = codes or [200] if response.status_code not in codes: raise ApiError(response) class HDict(dict): def __hash__(self): return hash(frozenset(self.items()))
rajshruti18/biolinkml
tests/test_issues/test_issue_3.py
import unittest from rdflib import Graph, XSD from biolinkml.generators.rdfgen import RDFGenerator from biolinkml.meta import META from includes.types import METATYPE from tests.test_issues.environment import env class DateTestCase(unittest.TestCase): def test_date_time(self): """ date datatype should be rdf:date and datetime rdf:datetime """ rdf = RDFGenerator(env.types_yaml).serialize() g = Graph() g.parse(data=rdf, format="turtle") self.assertEqual(XSD.date, g.value(METATYPE.date, META.uri)) self.assertEqual(XSD.dateTime, g.value(METATYPE.datetime, META.uri)) if __name__ == '__main__': unittest.main()
dawar-s/algo-ds-sol-python
algoexpert/medium/BreathFirstSearch.py
<filename>algoexpert/medium/BreathFirstSearch.py class Node: def __init__(self, name): self.children = [] self.name = name def addChild(self, name): self.children.append(Node(name)) return self def breadthFirstSearch(self, array): queue = [self] while len(queue) > 0: node = queue.pop(0) array.append(node.name) for child in node.children: queue.append(child) return array class TestProgram: def test_case_1(self): graph = Node("A") graph.addChild("B").addChild("C").addChild("D") graph.children[0].addChild("E").addChild("F") graph.children[2].addChild("G").addChild("H") graph.children[0].children[1].addChild("I").addChild("J") graph.children[2].children[0].addChild("K") print(graph.breadthFirstSearch([])) TestProgram().test_case_1()
zenglongGH/spresense
sdk/system/netutils/chat/chat.h
<filename>sdk/system/netutils/chat/chat.h /**************************************************************************** * system/netutils/chat/chat.h * * Copyright (C) 2016 <NAME>. All rights reserved. * Author: <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 NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __APPS_NETUTILS_CHAT_CHAT_H #define __APPS_NETUTILS_CHAT_CHAT_H /**************************************************************************** * Included Files ****************************************************************************/ #include "netutils/chat.h" /**************************************************************************** * Public Types ****************************************************************************/ enum chat_line_type { CHAT_LINE_TYPE_COMMAND = 0, CHAT_LINE_TYPE_EXPECT_SEND, }; enum chat_command { CHAT_COMMAND_ABORT = 0, CHAT_COMMAND_ECHO, CHAT_COMMAND_PAUSE, CHAT_COMMAND_SAY, CHAT_COMMAND_TIMEOUT, }; /* Type of chat script: singly-linked list of chat lines. */ struct chat_line { enum chat_line_type type; union { /* type-0 chat line command */ enum chat_command command; /* type-1 chat line expected string */ FAR char* expect; } lhs; /* type 0: command argument * type 1: string to be sent */ FAR char* rhs; FAR struct chat_line* next; /* pointer to the next line in the script */ }; /* Chat private state. */ struct chat { struct chat_ctl ctl; /* Embedded 'chat_ctl' type. */ FAR struct chat_line* script; /* first line of the script */ }; #endif /* __APPS_NETUTILS_CHAT_CHAT_H */
MobinHajizadeh/lottery
frontend/src/styles/GlobalStyle.js
import { createGlobalStyle } from 'styled-components' const GlobalStyle = createGlobalStyle` body { background-color: ${({ theme }) => theme.colors.background}; font-family: sans-serif; } ` export default GlobalStyle
Kyri123/KAdmin-ArkWIN
Panel/public/js/arkadmin2/pages/servercontrolcenter.js
/* * ******************************************************************************************* * @author: <NAME> (Kyri123) * @copyright Copyright (c) 2019-2020, <NAME> * @license MIT License (LICENSE or https://github.com/Kyri123/KAdmin-ArkWIN/blob/master/LICENSE) * Github: https://github.com/Kyri123/KAdmin-ArkWIN * ******************************************************************************************* */ const toEnd = ` <a class="col-lg-6 col-xl-6" data-toggle="modal" data-target="#addserver" href="#"> <div class="border border-success text-success align-content-center justify-content-center align-items-center d-flex card" style="font-size: 75px; width:100%; height:278px; border: 2px solid!important; cursor: pointer"> <i class="fas fa-plus" aria-hidden="true"></i> </div> </a>`; setInterval(() => { $.get('/ajax/serverCenterAny?getglobalinfos', (datas) => { serverList = JSON.parse(datas).servers_arr; if(serverList.length > 0) { let list = ``; serverList.forEach((val) => { let stateColor = val[1].is_installed ? ( val[1].is_free ? ( val[1].pid !== 0 && val[1].online ? "success" : (val[1].pid !== 0 ? "info" : "danger") ) : "info" ) : (val[1].is_free ? "warning" : "info"); if(val[1].server === undefined && hasPermissions(globalvars.perm, "show", val[0])) list += ` <div class="col-lg-6 col-xl-6" id="${val[0]}"> <div class="card card-widget widget-user item-box"> <div class="card bg-dark card-widget widget-user mb-0"> <div class="row p-2" title="${val[1].sessionName}"> <div class="col-12 text-center"> <h5 class="text-center left d-inline pt-3 pl-0 m-0"> ${val[1].sessionName} </h5> </div> </div> </div> <div class="widget-user-header text-white" style="background: url('/img/backgrounds/TheIsland.jpg') center center;"> <!--<h5 title="" class="widget-user-desc text-bold text-center border" style="background-color: rgb(66 66 66 / 58%)!important;"> <a href="/cluster#4c51f09bf0330d03047f8bc634290fc8" class="text-light"></a> </h5>--> </div> <div class="widget-user-image" id="serv_img" style="top: 124px;z-index: 1000"><img src="/img/igmap/TheIsland.jpg" style="border-top-width: 3px!important;height: 90px;width: 90px;background-color: #001f3f" class="border-secondary"></div> <div class="card card-widget widget-user mb-0"> <div class="text-left left d-inline" style="width:50%;padding-right: 45px;"> <a href="/servercenter/${val[0]}" target="_blank" style="width: 100%" class="btn btn-dark"><i class="fas fa-server" aria-hidden="true"></i></a> </div> <div class="right-no-top ml-auto d-inline" style="width:50%;padding-left: 45px;"> <a style="width: 100%" class="text-white btn btn-danger${hasPermissions(globalvars.perm, "servercontrolcenter/delete", val[0]) ? `" data-toggle="modal" data-target="#remove${val[0]}"` : ' disabled"'}><i class="fa fa-trash-o" aria-hidden="true"></i></a> </div> </div> <div class="card-footer p-0"> <div class="row"> <div class="col-sm-4 border-right border-sm-right"> <div class="description-block"> <h5 class="description-header"><b><a href="steam://connect/${vars.ip}:${val[1].query}">${vars.ip}:${val[1].query}</a></b></h5> <span class="description-text">${globalvars.lang_arr.servercontrolcenter.ip}</span> </div> </div> <div class="col-sm-4 border-right border-sm-right"> <div class="description-block"> <h5 class="description-header"><b class="text-${stateColor}">${globalvars.lang_arr.state[stateColor]}</b></h5> <span class="description-text">${globalvars.lang_arr.servercontrolcenter.state}</span> </div> </div> <div class="col-sm-4"> <div class="description-block"> <h5 class="description-header"><b>${val[1].serverMap}</b></h5> <span class="description-text">${globalvars.lang_arr.servercontrolcenter.map}</span> </div> </div> </div> </div> </div> </div> `; if($(`#remove${val[0]}`).html() === undefined) $('#modallist').append(`<form class="modal fade" method="post" action="#" id="remove${val[0]}" tabindex="-1" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-xl" role="document" style="max-width: 700px"> <div class="modal-content border-0"> <div class="modal-header bg-danger"> <h5 class="modal-title">${globalvars.lang_arr.servercontrolcenter.modalDelete.title}</h5> </div> <div class="modal-body"> <p>${globalvars.lang_arr.servercontrolcenter.modalDelete.text.replace("{servername}", val[1].sessionName)}</p> <input name="cfg" value="${val[0]}" type="hidden"> <input name="deleteserver" value="true" type="hidden"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">${globalvars.lang_arr.servercontrolcenter.modalDelete.cancel}</button> <button type="button" class="btn btn-danger" name="del" onclick="submitform('#remove${val[0]}')">${globalvars.lang_arr.servercontrolcenter.modalDelete.remove}</button> </div> </div> </div> </form>`); }); if(hasPermissions(globalvars.perm, "servercontrolcenter/create")) list += toEnd if($('#serverlist').html() !== list) $('#serverlist').html(list); } }); }, 2000); function submitform(id) { $.post(`/ajax/servercontrolcenter`, $(id).serialize()) .done(function(data) { try { data = JSON.parse(data); if(data.alert !== undefined) $('#global_resp').append(data.alert); if (data.remove !== undefined) { $(id).modal('hide'); $(`#remove${data.removed}`).modal('hide').remove(); $(`#${data.removed}`).remove(); $('.modal-backdrop').remove(); } if(data.added !== undefined) { $(`#addserver`).modal('hide'); } } catch (e) { $(id).modal('hide'); } }); }
AndrewLebowski/Project_One
testing/PageObjects/ConfirmWindow.js
<filename>testing/PageObjects/ConfirmWindow.js /* eslint-disable no-undef */ class ConfirmWindow { get content() { return $('#confirm-window'); } get cancelButton() { return $('#cancel-button'); } get confirmButton() { return $('#confirm-button'); } } export default new ConfirmWindow();
er1c/intellij-scala
src/org/jetbrains/plugins/scala/findUsages/factory/ScalaFindUsagesHandler.scala
package org.jetbrains.plugins.scala package findUsages.factory import java.util import com.intellij.find.findUsages.{AbstractFindUsagesDialog, FindUsagesHandler, FindUsagesOptions} import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.util.text.StringUtil import com.intellij.psi._ import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.usageView.UsageInfo import com.intellij.util.Processor import org.jetbrains.plugins.scala.extensions._ import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil import org.jetbrains.plugins.scala.lang.psi.api.base.ScPrimaryConstructor import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameter import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScTypeAlias, ScValue, ScVariable} import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypedDefinition import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef._ import org.jetbrains.plugins.scala.lang.psi.impl.search.ScalaOverridingMemberSearcher import org.jetbrains.plugins.scala.lang.psi.light.PsiTypedDefinitionWrapper.DefinitionRole._ import org.jetbrains.plugins.scala.lang.psi.light._ import _root_.scala.collection.mutable /** * User: <NAME> * Date: 17.08.2009 */ class ScalaFindUsagesHandler(element: PsiElement, factory: ScalaFindUsagesHandlerFactory) extends FindUsagesHandler(element) { override def getPrimaryElements: Array[PsiElement] = Array(element) override def getStringsToSearch(element: PsiElement): util.Collection[String] = { val result: util.Set[String] = new util.HashSet[String]() element match { case t: ScTrait => result.add(t.name) result.add(t.getName) result.add(t.fakeCompanionClass.getName) case o: ScObject => result.add(o.name) result.add(o.getName) case c: ScClass if c.isCase => result.add(c.name) c.fakeCompanionModule match { case Some(o) => result.add(o.getName) case _ => } case named: PsiNamedElement => val name = named.name result.add(name) ScalaPsiUtil.nameContext(named) match { case v: ScValue if ScalaPsiUtil.isBeanProperty(v) => result.add("get" + StringUtil.capitalize(name)) case v: ScVariable if ScalaPsiUtil.isBeanProperty(v) => result.add("get" + StringUtil.capitalize(name)) result.add("set" + StringUtil.capitalize(name)) case v: ScValue if ScalaPsiUtil.isBooleanBeanProperty(v) => result.add("is" + StringUtil.capitalize(name)) case v: ScVariable if ScalaPsiUtil.isBooleanBeanProperty(v) => result.add("is" + StringUtil.capitalize(name)) result.add("set" + StringUtil.capitalize(name)) case _ => } case _ => result.add(element.getText) } result } override def getFindUsagesOptions(dataContext: DataContext): FindUsagesOptions = { element match { case t: ScTypeDefinition => factory.typeDefinitionOptions case ScalaPsiUtil.inNameContext(m: ScMember) => factory.memberOptions case p: ScParameter => factory.paramOptions case _ => super.getFindUsagesOptions(dataContext) } } override def getSecondaryElements: Array[PsiElement] = { element match { case t: ScObject => t.fakeCompanionClass match { case Some(clazz) => Array(clazz) case _ => Array.empty } case t: ScTrait => Array(t.fakeCompanionClass) case f: ScFunction if Seq("apply", "unapply", "unapplySeq").contains(f.name) => f.containingClass match { case obj: ScObject if obj.isSyntheticObject => Array(obj) case _ => Array.empty } case t: ScTypedDefinition => t.getBeanMethods.toArray ++ { val a: Array[DefinitionRole] = t.nameContext match { case v: ScValue if ScalaPsiUtil.isBeanProperty(v) => Array(GETTER) case v: ScVariable if ScalaPsiUtil.isBeanProperty(v) => Array(GETTER, SETTER) case v: ScValue if ScalaPsiUtil.isBooleanBeanProperty(v) => Array(IS_GETTER) case v: ScVariable if ScalaPsiUtil.isBooleanBeanProperty(v) => Array(IS_GETTER, SETTER) case _ => Array.empty } a.map(role => t.getTypedDefinitionWrapper(isStatic = false, isInterface = false, role = role, cClass = None)) } case _ => Array.empty } } override def getFindUsagesDialog(isSingleFile: Boolean, toShowInNewTab: Boolean, mustOpenInNewTab: Boolean): AbstractFindUsagesDialog = { element match { case t: ScTypeDefinition => new ScalaTypeDefinitionUsagesDialog(t, getProject, getFindUsagesOptions, toShowInNewTab, mustOpenInNewTab, isSingleFile, this) case _ => super.getFindUsagesDialog(isSingleFile, toShowInNewTab, mustOpenInNewTab) } } override def processUsagesInText(element: PsiElement, processor: Processor[UsageInfo], searchScope: GlobalSearchScope): Boolean = { val nonScalaTextProcessor = new Processor[UsageInfo] { override def process(t: UsageInfo): Boolean = { if (t.getFile.getFileType == ScalaFileType.SCALA_FILE_TYPE) true else processor.process(t) } } super.processUsagesInText(element, nonScalaTextProcessor, searchScope) } override def processElementUsages(element: PsiElement, processor: Processor[UsageInfo], options: FindUsagesOptions): Boolean = { if (!super.processElementUsages(element, processor, options)) return false options match { case s: ScalaTypeDefinitionFindUsagesOptions if element.isInstanceOf[ScTypeDefinition] => val clazz = element.asInstanceOf[ScTypeDefinition] if (s.isMembersUsages) { clazz.members.foreach { case fun: ScFunction => if (!super.processElementUsages(fun, processor, options)) return false case v: ScValue => v.declaredElements.foreach { d => if (!super.processElementUsages(d, processor, options)) return false } case v: ScVariable => v.declaredElements.foreach { d => if (!super.processElementUsages(d, processor, options)) return false } case ta: ScTypeAlias => if (!super.processElementUsages(ta, processor, options)) return false case c: ScTypeDefinition => if (!super.processElementUsages(c, processor, options)) return false case c: ScPrimaryConstructor => if (!super.processElementUsages(c, processor, options)) return false } clazz match { case c: ScClass => c.constructor match { case Some(constr) => constr.effectiveParameterClauses.foreach {clause => clause.effectiveParameters.foreach {param => if (!super.processElementUsages(c, processor, options)) return false } } case _ => } case _ => } } if (s.isSearchCompanionModule) { ScalaPsiUtil.getBaseCompanionModule(clazz) match { case Some(companion) => if (!super.processElementUsages(companion, processor, options)) return false case _ => } } if (s.isImplementingTypeDefinitions) { val res = new mutable.HashSet[PsiClass]() ClassInheritorsSearch.search(clazz, true).forEach(new Processor[PsiClass] { def process(t: PsiClass): Boolean = { t match { case p: PsiClassWrapper => case _ => res += t } true } }) res.foreach { c => val processed = inReadAction(processor.process(new UsageInfo(c))) if (!processed) return false } } case _ => } element match { case function: ScFunction if !function.isLocal => for (elem <- ScalaOverridingMemberSearcher.search(function, deep = true)) { val processed = inReadAction(super.processElementUsages(elem, processor, options)) if (!processed) return false } case _ => } true } override def isSearchForTextOccurencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean = !isSingleFile }
FGtatsuro/myatcoder
beginner_contest/060/B.py
a, b, c = [int(i) for i in input().split()] def cond(a, b, c): if a == 1: return True candidate = [] i = 1 while True: r = (a * i) % b if r in candidate: break i += 1 candidate.append(r) if c in candidate: return True return False if cond(a, b, c): print('YES') else: print('NO')
trailsjs/generator-trails-old
test/integration/api.test.js
<filename>test/integration/api.test.js<gh_stars>0 'use strict' const path = require('path') const assert = require('yeoman-assert') const test = require('yeoman-test') describe('trails:api', () => { describe('Should properly generate api interface', () => { describe('Should properly generate model interface', () => { before(done => { /* test .run(path.join(__dirname, '../../generators/api')) .withArguments(['apiTest']) .on('end', done) */ //FIXME: really test api call, currently not working cause api run model and controller test .run(path.join(__dirname, '../../generators/model')) .withArguments(['apiTest']) .on('end', done) }) it('Should properly create model files', () => { assert.file([ 'api/models/ApiTest.js' ]) }) it('Should properly create test files', () => { assert.file([ 'test/unit/models/ApiTest.test.js' ]) }) }) describe('Should properly generate controller interface', () => { before(() => { return test .run(path.join(__dirname, '../../generators/controller')) .withArguments(['apiTest']) .toPromise() }) it('Should properly create controller files', () => { assert.file([ 'api/controllers/ApiTestController.js' ]) }) it('Should properly create test files', () => { assert.file([ 'test/integration/controllers/ApiTestController.test.js' ]) }) }) }) })
berkansasmaz/runtime
src/coreclr/debug/di/loongarch64/cordbregisterset.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //***************************************************************************** // File: CordbRegisterSet.cpp // // //***************************************************************************** #include "primitives.h" HRESULT CordbRegisterSet::GetRegistersAvailable(ULONG64* pAvailable) { FAIL_IF_NEUTERED(this); VALIDATE_POINTER_TO_OBJECT(pAvailable, ULONG64 *); *pAvailable = SETBITULONG64(REGISTER_LOONGARCH64_PC) | SETBITULONG64(REGISTER_LOONGARCH64_SP) | SETBITULONG64(REGISTER_LOONGARCH64_FP) | SETBITULONG64(REGISTER_LOONGARCH64_RA) | SETBITULONG64(REGISTER_LOONGARCH64_TP) | SETBITULONG64(REGISTER_LOONGARCH64_A0) | SETBITULONG64(REGISTER_LOONGARCH64_A1) | SETBITULONG64(REGISTER_LOONGARCH64_A2) | SETBITULONG64(REGISTER_LOONGARCH64_A3) | SETBITULONG64(REGISTER_LOONGARCH64_A4) | SETBITULONG64(REGISTER_LOONGARCH64_A5) | SETBITULONG64(REGISTER_LOONGARCH64_A6) | SETBITULONG64(REGISTER_LOONGARCH64_A7) | SETBITULONG64(REGISTER_LOONGARCH64_T0) | SETBITULONG64(REGISTER_LOONGARCH64_T1) | SETBITULONG64(REGISTER_LOONGARCH64_T2) | SETBITULONG64(REGISTER_LOONGARCH64_T3) | SETBITULONG64(REGISTER_LOONGARCH64_T4) | SETBITULONG64(REGISTER_LOONGARCH64_T5) | SETBITULONG64(REGISTER_LOONGARCH64_T6) | SETBITULONG64(REGISTER_LOONGARCH64_T7) | SETBITULONG64(REGISTER_LOONGARCH64_T8) | SETBITULONG64(REGISTER_LOONGARCH64_X0) | SETBITULONG64(REGISTER_LOONGARCH64_S0) | SETBITULONG64(REGISTER_LOONGARCH64_S1) | SETBITULONG64(REGISTER_LOONGARCH64_S2) | SETBITULONG64(REGISTER_LOONGARCH64_S3) | SETBITULONG64(REGISTER_LOONGARCH64_S4) | SETBITULONG64(REGISTER_LOONGARCH64_S5) | SETBITULONG64(REGISTER_LOONGARCH64_S6) | SETBITULONG64(REGISTER_LOONGARCH64_S7) | SETBITULONG64(REGISTER_LOONGARCH64_S8) | SETBITULONG64(REGISTER_LOONGARCH64_F0) | SETBITULONG64(REGISTER_LOONGARCH64_F1) | SETBITULONG64(REGISTER_LOONGARCH64_F2) | SETBITULONG64(REGISTER_LOONGARCH64_F3) | SETBITULONG64(REGISTER_LOONGARCH64_F4) | SETBITULONG64(REGISTER_LOONGARCH64_F5) | SETBITULONG64(REGISTER_LOONGARCH64_F6) | SETBITULONG64(REGISTER_LOONGARCH64_F7) | SETBITULONG64(REGISTER_LOONGARCH64_F8) | SETBITULONG64(REGISTER_LOONGARCH64_F9) | SETBITULONG64(REGISTER_LOONGARCH64_F10) | SETBITULONG64(REGISTER_LOONGARCH64_F11) | SETBITULONG64(REGISTER_LOONGARCH64_F12) | SETBITULONG64(REGISTER_LOONGARCH64_F13) | SETBITULONG64(REGISTER_LOONGARCH64_F14) | SETBITULONG64(REGISTER_LOONGARCH64_F15) | SETBITULONG64(REGISTER_LOONGARCH64_F16) | SETBITULONG64(REGISTER_LOONGARCH64_F17) | SETBITULONG64(REGISTER_LOONGARCH64_F18) | SETBITULONG64(REGISTER_LOONGARCH64_F19) | SETBITULONG64(REGISTER_LOONGARCH64_F20) | SETBITULONG64(REGISTER_LOONGARCH64_F21) | SETBITULONG64(REGISTER_LOONGARCH64_F22) | SETBITULONG64(REGISTER_LOONGARCH64_F23) | SETBITULONG64(REGISTER_LOONGARCH64_F24) | SETBITULONG64(REGISTER_LOONGARCH64_F25) | SETBITULONG64(REGISTER_LOONGARCH64_F26) | SETBITULONG64(REGISTER_LOONGARCH64_F27) | SETBITULONG64(REGISTER_LOONGARCH64_F28) | SETBITULONG64(REGISTER_LOONGARCH64_F29) | SETBITULONG64(REGISTER_LOONGARCH64_F30) | SETBITULONG64(REGISTER_LOONGARCH64_F31); return S_OK; } HRESULT CordbRegisterSet::GetRegisters(ULONG64 mask, ULONG32 regCount, CORDB_REGISTER regBuffer[]) { PUBLIC_REENTRANT_API_ENTRY(this); FAIL_IF_NEUTERED(this); ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess()); UINT iRegister = 0; VALIDATE_POINTER_TO_OBJECT_ARRAY(regBuffer, CORDB_REGISTER, regCount, true, true); for (int i = REGISTER_LOONGARCH64_PC; i <= REGISTER_LOONGARCH64_F31 && iRegister < regCount; i++) { if (mask & SETBITULONG64(i)) { _ASSERTE (iRegister < regCount); if ((i >= REGISTER_LOONGARCH64_A0) && (i <= REGISTER_LOONGARCH64_X0)) { regBuffer[iRegister++] = *(ULONG64*)((char*)(&m_rd->A0) + ((i - REGISTER_LOONGARCH64_A0) << 3)); continue; } if ((i >= REGISTER_LOONGARCH64_S0) && (i <= REGISTER_LOONGARCH64_S8)) { regBuffer[iRegister++] = *(ULONG64*)((char*)(&m_rd->S0) + ((i - REGISTER_LOONGARCH64_S0) << 3)); continue; } if ((i >= REGISTER_LOONGARCH64_F0) && (i <= REGISTER_LOONGARCH64_F31)) { if (!m_thread->m_fFloatStateValid) { HRESULT hr = S_OK; EX_TRY { m_thread->LoadFloatState(); } EX_CATCH_HRESULT(hr); if ( !SUCCEEDED(hr) ) { return hr; } LOG( ( LF_CORDB, LL_INFO1000, "CRS::GR: Loaded float state\n" ) ); } regBuffer[iRegister++] = *(CORDB_REGISTER*) &(m_thread->m_floatValues[(i - REGISTER_LOONGARCH64_F0)]); continue; } switch (i) { case REGISTER_LOONGARCH64_PC: regBuffer[iRegister++] = m_rd->PC; break; case REGISTER_LOONGARCH64_SP: regBuffer[iRegister++] = m_rd->SP; break; case REGISTER_LOONGARCH64_FP: regBuffer[iRegister++] = m_rd->FP; break; case REGISTER_LOONGARCH64_RA: regBuffer[iRegister++] = m_rd->RA; break; case REGISTER_LOONGARCH64_TP: regBuffer[iRegister++] = m_rd->TP; break; default: _ASSERTE(false); break; } } } _ASSERTE (iRegister <= regCount); return S_OK; } HRESULT CordbRegisterSet::GetRegistersAvailable(ULONG32 regCount, BYTE pAvailable[]) { FAIL_IF_NEUTERED(this); VALIDATE_POINTER_TO_OBJECT_ARRAY(pAvailable, CORDB_REGISTER, regCount, true, true); for (int i = 0 ; i < (int)regCount ; ++i) { if (i * 8 <= REGISTER_LOONGARCH64_F31) { pAvailable[i] = (i * 8 == REGISTER_LOONGARCH64_F31) ? BYTE(0x1) : BYTE(0xff); } else { pAvailable[i] = 0; } } return S_OK; } HRESULT CordbRegisterSet::GetRegisters(ULONG32 maskCount, BYTE mask[], ULONG32 regCount, CORDB_REGISTER regBuffer[]) { FAIL_IF_NEUTERED(this); VALIDATE_POINTER_TO_OBJECT_ARRAY(regBuffer, CORDB_REGISTER, regCount, true, true); UINT iRegister = 0; for (int m = 0 ; m < (int)maskCount ; ++m) { for (int bit = 0 ; bit < 8 ; ++bit) { if (mask[m] & SETBITULONG64(bit)) { _ASSERTE (iRegister < regCount); int i = m * 8 + bit; if ((i >= REGISTER_LOONGARCH64_A0) && (i <= REGISTER_LOONGARCH64_X0)) { regBuffer[iRegister++] = *(ULONG64*)((char*)(&m_rd->A0) + ((i - REGISTER_LOONGARCH64_A0) << 3)); continue; } if ((i >= REGISTER_LOONGARCH64_S0) && (i <= REGISTER_LOONGARCH64_S8)) { regBuffer[iRegister++] = *(ULONG64*)((char*)(&m_rd->S0) + ((i - REGISTER_LOONGARCH64_S0) << 3)); continue; } if ((i >= REGISTER_LOONGARCH64_F0) && (i <= REGISTER_LOONGARCH64_F31)) { if (!m_thread->m_fFloatStateValid) { HRESULT hr = S_OK; EX_TRY { m_thread->LoadFloatState(); } EX_CATCH_HRESULT(hr); if ( !SUCCEEDED(hr) ) { return hr; } LOG( ( LF_CORDB, LL_INFO1000, "CRS::GR: Loaded float state\n" ) ); } regBuffer[iRegister++] = *(CORDB_REGISTER*) &(m_thread->m_floatValues[(i - REGISTER_LOONGARCH64_F0)]); continue; } switch (i) { case REGISTER_LOONGARCH64_PC: regBuffer[iRegister++] = m_rd->PC; break; case REGISTER_LOONGARCH64_SP: regBuffer[iRegister++] = m_rd->SP; break; case REGISTER_LOONGARCH64_FP: regBuffer[iRegister++] = m_rd->FP; break; case REGISTER_LOONGARCH64_RA: regBuffer[iRegister++] = m_rd->RA; break; case REGISTER_LOONGARCH64_TP: regBuffer[iRegister++] = m_rd->TP; break; default: _ASSERTE(false); break; } } } } return S_OK; } // This is just a convenience function to convert a regdisplay into a Context. // Since a context has more info than a regdisplay, the conversion isn't perfect // and the context can't be fully accurate. void CordbRegisterSet::InternalCopyRDToContext(DT_CONTEXT *pInputContext) { INTERNAL_SYNC_API_ENTRY(GetProcess()); _ASSERTE(pInputContext); if ((pInputContext->ContextFlags & DT_CONTEXT_INTEGER) == DT_CONTEXT_INTEGER) { ULONG64* pDest = &pInputContext->A0; ULONG64* pSrc = &m_rd->A0; for (int i = REGISTER_LOONGARCH64_A0; i < REGISTER_LOONGARCH64_X0; ++i) { *pDest++ = *pSrc++; } pDest = &pInputContext->S0; pSrc = &m_rd->S0; for (int i = REGISTER_LOONGARCH64_S0; i <= REGISTER_LOONGARCH64_S8; ++i) { *pDest++ = *pSrc++; } pInputContext->TP = m_rd->TP; pInputContext->RA = m_rd->RA; } if ((pInputContext->ContextFlags & DT_CONTEXT_CONTROL) == DT_CONTEXT_CONTROL) { pInputContext->SP = m_rd->SP; pInputContext->PC = m_rd->PC; pInputContext->FP = m_rd->FP; } }
zhangkn/iOS14Header
System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/TSCalculationEngine.framework/TSCEFormulaRewrite_Uids.h
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 12:31:21 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/TSCalculationEngine.framework/TSCalculationEngine * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <TSCalculationEngine/TSCalculationEngine-Structs.h> @class NSIndexSet; @interface TSCEFormulaRewrite_Uids : NSObject { vector<TSU::UUIDData<TSP::UUIDData>, std::__1::allocator<TSU::UUIDData<TSP::UUIDData> > >* _uids; NSIndexSet* _indexes; unordered_map<TSU::UUIDData<TSP::UUIDData>, unsigned int, std::__1::hash<TSUUUID>, std::__1::equal_to<TSU::UUIDData<TSP::UUIDData> >, std::__1::allocator<std::__1::pair<const TSU::UUIDData<TSP::UUIDData>, unsigned int> > >* _indexesForUids; unordered_map<unsigned int, TSU::UUIDData<TSP::UUIDData>, std::__1::hash<unsigned int>, std::__1::equal_to<unsigned int>, std::__1::allocator<std::__1::pair<const unsigned int, TSU::UUIDData<TSP::UUIDData> > > >* _uidsForIndexes; vector<TSU::UUIDData<TSP::UUIDData>, std::__1::allocator<TSU::UUIDData<TSP::UUIDData> > >* _viewOrderUids; } @property (readonly) const vector<TSU::UUIDData<TSP::UUIDData>* uids; //@synthesize uids=_uids - In the implementation block @property (readonly) const vector<TSU::UUIDData<TSP::UUIDData>* viewOrderUids; //@synthesize viewOrderUids=_viewOrderUids - In the implementation block @property (readonly) NSIndexSet * indexes; //@synthesize indexes=_indexes - In the implementation block -(NSIndexSet *)indexes; -(const vector<TSU::UUIDData<TSP::UUIDData>*)uids; -(BOOL)containsIndex:(unsigned)arg1 ; -(id)description; -(void)saveToMessage:(IndexedUidsArchive*)arg1 ; -(vector<TSU::UUIDData<TSP::UUIDData>, std::__1::allocator<TSU::UUIDData<TSP::UUIDData> > >*)uidsForIndexes:(id)arg1 ; -(id)initFromMessage:(const IndexedUidsArchive*)arg1 ; -(UUIDData<TSP::UUIDData>)uidForIndex:(unsigned)arg1 ; -(unsigned short)columnIndexForUid:(const UUIDData<TSP::UUIDData>*)arg1 ; -(unsigned)rowIndexForUid:(const UUIDData<TSP::UUIDData>*)arg1 ; -(id)indexSetBySubtractingOurIndexesFromIndexSet:(id)arg1 ; -(void)unloadIndexes; -(id)initWithUids:(const vector<TSU::UUIDData<TSP::UUIDData>, std::__1::allocator<TSU::UUIDData<TSP::UUIDData> > >*)arg1 ; -(id)initWithUids:(const vector<TSU::UUIDData<TSP::UUIDData>, std::__1::allocator<TSU::UUIDData<TSP::UUIDData> > >*)arg1 atIndexes:(const vector<unsigned int, std::__1::allocator<unsigned int> >*)arg2 ; -(void)loadIndexesForTable:(id)arg1 isRows:(BOOL)arg2 shuffleMap:(id)arg3 ; -(const vector<TSU::UUIDData<TSP::UUIDData>*)viewOrderUids; @end
brokes6/D-BiliBili
app/src/main/java/com/example/dildil/home_page/model/HomeModel.java
package com.example.dildil.home_page.model; import com.example.dildil.api.ApiEngine; import com.example.dildil.home_page.bean.DynamicNumBean; import com.example.dildil.home_page.bean.VersionBean; import com.example.dildil.home_page.contract.HomeContract; import io.reactivex.Observable; public class HomeModel implements HomeContract.Model { @Override public Observable<DynamicNumBean> getDynamicNum(int uid) { return ApiEngine.getInstance().getApiService().getDynamicNum(uid); } @Override public Observable<VersionBean> getVersion(String url) { return ApiEngine.getInstance().getApiService().getVersion(url); } }
fontaine618/MTSGL
MTSGL/solvers/proxgd.py
<reponame>fontaine618/MTSGL<filename>MTSGL/solvers/proxgd.py from typing import Dict, Tuple, Optional import numpy as np from losses import MTLoss from regularizations import Regularization def proxgd( loss: MTLoss, reg: Regularization, beta0: np.ndarray, lam: float, rho: float, ls: Optional[bool] = False, v: Optional[Dict[str, np.ndarray]] = None, **kwargs ) -> Tuple[np.ndarray, int]: """Optimizes a loss for some regularization. Parameters ---------- ls : loss : MTLoss The loss function, only needs access to x, w and cov_upper_bound. reg : Regularization The regularization used, which must implement proximal. beta0 : ndarray The initial value (p, K). v : dict of ndarray The dictionary of working responses in the squared loss (task: n_obs[task]). lam : float The regularization multiplier. rho : float The loss multiplier. kwargs : dict Further options to control the optimization. Notes ----- The objective function is as follows: .. math:: \frac{\rho}{2} \sum_{k=1}^{L} \left\Vert X^{(k)} \beta^{(k)} - V^{(k)}\right\Vert + \lambda P_(\beta) Returns ------- betat : ndarray The solution. t : int The number of iterations. """ if lam < 0.: raise ValueError("lam must be non-negative") if rho < 0.: raise ValueError("rho must be non-negative") if ls and v is None: raise ValueError("when ls=True, v must be specified") # options threshold = 1.0e-6 if "threshold" not in kwargs else kwargs["threshold"] max_iter = 1000 if "max_iter" not in kwargs else kwargs["max_iter"] # initialize step size to hessian upper bound if ls: step_size = 1. / (loss.hessian_ls_upper_bound() * rho) else: step_size = 1. / (loss.hessian_upper_bound() * rho) # first iteration t = 0 betat = beta0 betatm1 = betat bt = betat thetat = 1. # loop until convergence while True: t += 1 # store previous beta value beta_prev = betat # compute gradient grad = compute_grad(bt, loss, ls, rho, v) # adaptive restarts if np.sum(grad * (betat - betatm1)) > 0.: # regular GD step grad = compute_grad(betat, loss, ls, rho, v) betat = betat - step_size * grad else: # momentum step betat = bt - step_size * grad # proximal betat = reg.proximal(betat, lam * step_size) # compute momentum step thetatm1 = thetat thetat = 0.5 * (1. + np.sqrt(1. + 4. * thetat ** 2)) bt = betat + (thetatm1 - 1.) * (betat - beta_prev) / thetat # check convergence step = np.linalg.norm(betat - beta_prev, 2) # update previous beta betatm1 = beta_prev if t >= max_iter: break # raise RuntimeError("proxgd did not converge in {} iterations".format(t)) if step < threshold: break return betat, t def compute_grad(bt, loss, ls, rho, v): if ls: grad = np.zeros_like(bt) for k, (task, l) in enumerate(loss.items()): grad[:, [k]] = rho * np.matmul(l.x.T, l.w * (l.lin_predictor(bt[:, [k]]) - v[task])) else: grad = loss.gradient(bt) return grad
mikevo/uibk_acc
libmc/include/string_utils.h
<filename>libmc/include/string_utils.h #pragma once #include <string> #include <vector> std::vector<std::string> split(const std::string &s, char delim); void replace_all(std::string &str, const std::string &substr, const std::string &replacement); bool starts_with(const std::string &s, const std::string &prefix); bool ends_with(const std::string &s, const std::string &suffix);
SaschaKersken/Daten-Prozessanalyse
listings/chapter03/guess.py
<reponame>SaschaKersken/Daten-Prozessanalyse print("Denk dir eine Zahl zwischen 1 und 100, die ich erraten werde.") # Anfangs-Ratewert: 50 guess = 50 # Endlosschleife, bis erraten oder Fehler while True: print(f"{guess}. 1) korrekt, 2) zu groß, 3) zu klein, 4) Ende?") # Endlosschleife, bis 1-3 eingeben. while True: choice = input('> ') if choice in ['1', '2', '3', '4']: break if choice == '4': break if choice == '1': print("Hurra!") break if choice == '2': guess -= guess // 2 else: guess += (100 - guess) // 2
ScalablyTyped/SlinkyTyped
p/pulumi__aws/src/main/scala/typingsSlinky/pulumiAws/inputMod/kinesis/AnalyticsApplicationInputsKinesisStream.scala
package typingsSlinky.pulumiAws.inputMod.kinesis import typingsSlinky.pulumiPulumi.outputMod.Input import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait AnalyticsApplicationInputsKinesisStream extends StObject { /** * The ARN of the Kinesis Stream. */ var resourceArn: Input[String] = js.native /** * The ARN of the IAM Role used to access the stream. */ var roleArn: Input[String] = js.native } object AnalyticsApplicationInputsKinesisStream { @scala.inline def apply(resourceArn: Input[String], roleArn: Input[String]): AnalyticsApplicationInputsKinesisStream = { val __obj = js.Dynamic.literal(resourceArn = resourceArn.asInstanceOf[js.Any], roleArn = roleArn.asInstanceOf[js.Any]) __obj.asInstanceOf[AnalyticsApplicationInputsKinesisStream] } @scala.inline implicit class AnalyticsApplicationInputsKinesisStreamMutableBuilder[Self <: AnalyticsApplicationInputsKinesisStream] (val x: Self) extends AnyVal { @scala.inline def setResourceArn(value: Input[String]): Self = StObject.set(x, "resourceArn", value.asInstanceOf[js.Any]) @scala.inline def setRoleArn(value: Input[String]): Self = StObject.set(x, "roleArn", value.asInstanceOf[js.Any]) } }
snazzyfox/discord-party-dingomata
dingomata/cogs/game_code/models.py
<filename>dingomata/cogs/game_code/models.py<gh_stars>1-10 from enum import Enum from sqlalchemy import Column, BigInteger, String, Boolean, Integer from sqlalchemy.orm import declarative_base GamecodeModel = declarative_base() class EntryStatus(Enum): ELIGIBLE = 1 SELECTED = 2 PLAYED = 3 class GameMode(Enum): NEW_PLAYERS_ONLY = 1 ANYONE = 2 class GamePool(GamecodeModel): __tablename__ = "game_pool" guild_id = Column(BigInteger, primary_key=True) is_open = Column(Boolean, nullable=False, default=False) title = Column(String, nullable=False) mode = Column(Integer, nullable=False) channel_id = Column(BigInteger, nullable=True) message_id = Column(BigInteger, nullable=True) class GamePoolEntry(GamecodeModel): __tablename__ = "game_pool_entry" guild_id = Column(BigInteger, primary_key=True) user_id = Column(BigInteger, primary_key=True) status = Column(Integer, nullable=False) weight = Column(Integer)
cheshtaaagarrwal/DS-Algos
misc challenges/studentcourses.py
<gh_stars>0 # You are a developer for a university. Your current project is to develop a system for students to find # courses they share with friends. The university has a system for querying courses students are enrolled # in, returned as a list of (ID, course) pairs. # Write a function that takes in a list of (student ID number, course name) pairs and returns, for every # pair of students, a list of all courses they share. # Sample Input: # student_course_pairs = [ # ["58", "Software Design"], # ["58", "Linear Algebra"], # ["94", "Art History"], # ["94", "Operating Systems"], # ["17", "Software Design"], # ["58", "Mechanics"], # ["58", "Economics"], # ["17", "Linear Algebra"], # ["17", "Political Science"], # ["94", "Economics"] # ] # Sample Output (pseudocode, in any order) # find_pairs(student_course_pairs) => # { # [58, 17]: ["Software Design", "Linear Algebra"] # [58, 94]: ["Economics"] # [17, 94]: [] # } def find_pairs(student_course_pairs): students = [] studentCourses, res = {}, {} for cur in student_course_pairs: if cur[0] not in studentCourses: studentCourses[cur[0]] = [cur[1]] students.append(cur[0]) else: studentCourses[cur[0]].append(cur[1]) # print(students) # print(studentCourses) for i in range(len(students) - 1): for j in range(i + 1, len(students)): first, second = students[i], students[j] seen = set(studentCourses[first]) res[(first, second)] = [] for cur in studentCourses[second]: if cur in seen: res[(first, second)].append(cur) return res student_course_pairs = [ ["58", "Software Design"], ["58", "Linear Algebra"], ["94", "Art History"], ["94", "Operating Systems"], ["17", "Software Design"], ["58", "Mechanics"], ["58", "Economics"], ["17", "Linear Algebra"], ["17", "Political Science"], ["94", "Economics"] ] print(find_pairs(student_course_pairs))
typicalMoves/dava.engine
Programs/ResourceEditor1/Classes/Qt/Scene/System/EditorVegetationSystem.h
#pragma once #include "Base/BaseTypes.h" #include "Entity/SceneSystem.h" namespace DAVA { class Entity; class VegetationRenderObject; } class SceneEditor2; class EditorVegetationSystem : public DAVA::SceneSystem { public: EditorVegetationSystem(DAVA::Scene* scene); void AddEntity(DAVA::Entity* entity) override; void RemoveEntity(DAVA::Entity* entity) override; void PrepareForRemove() override; void GetActiveVegetation(DAVA::Vector<DAVA::VegetationRenderObject*>& activeVegetationObjects); void ReloadVegetation(); private: DAVA::Vector<DAVA::VegetationRenderObject*> vegetationObjects; };
MartinGeisse/public
codegen-test/src/name/martingeisse/codegen/template/test/EulerAnglesTemplate.java
<reponame>MartinGeisse/public<gh_stars>1-10 /** * Copyright (c) 2011 <NAME> * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.codegen.template.test; import name.martingeisse.codegen.dataclass.DataClassTemplate; import name.martingeisse.codegen.dataclass.DataClassType; /** * A template for the various 2d/3d vector types. */ public class EulerAnglesTemplate extends DataClassTemplate { /** * Constructor. * @param dataClassType selects mutability and similar properties */ public EulerAnglesTemplate(DataClassType dataClassType) { super("EulerAngles", dataClassType); setPackageName("name.martingeisse.stackd.common.geometry"); } }
Masha/hashcat
OpenCL/inc_hash_md5.h
/** * Author......: See docs/credits.txt * License.....: MIT */ #ifndef _INC_HASH_MD5_H #define _INC_HASH_MD5_H #define MD5_F_S(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define MD5_G_S(x,y,z) ((y) ^ ((z) & ((x) ^ (y)))) #define MD5_H_S(x,y,z) ((x) ^ (y) ^ (z)) #define MD5_I_S(x,y,z) ((y) ^ ((x) | ~(z))) #define MD5_F(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define MD5_G(x,y,z) ((y) ^ ((z) & ((x) ^ (y)))) #define MD5_H(x,y,z) ((x) ^ (y) ^ (z)) #define MD5_H1(x,y,z) ((t = (x) ^ (y)) ^ (z)) #define MD5_H2(x,y,z) ((x) ^ t) #define MD5_I(x,y,z) ((y) ^ ((x) | ~(z))) #ifdef USE_BITSELECT #define MD5_Fo(x,y,z) (bitselect ((z), (y), (x))) #define MD5_Go(x,y,z) (bitselect ((y), (x), (z))) #else #define MD5_Fo(x,y,z) (MD5_F((x), (y), (z))) #define MD5_Go(x,y,z) (MD5_G((x), (y), (z))) #endif #define MD5_STEP_S(f,a,b,c,d,x,K,s) \ { \ a += K; \ a = hc_add3_S (a, x, f (b, c, d)); \ a = hc_rotl32_S (a, s); \ a += b; \ } #define MD5_STEP(f,a,b,c,d,x,K,s) \ { \ a += K; \ a = hc_add3 (a, x, f (b, c, d)); \ a = hc_rotl32 (a, s); \ a += b; \ } #define MD5_STEP0(f,a,b,c,d,K,s) \ { \ a = hc_add3 (a, K, f (b, c, d)); \ a = hc_rotl32 (a, s); \ a += b; \ } typedef struct md5_ctx { u32 h[4]; u32 w0[4]; u32 w1[4]; u32 w2[4]; u32 w3[4]; int len; } md5_ctx_t; typedef struct md5_hmac_ctx { md5_ctx_t ipad; md5_ctx_t opad; } md5_hmac_ctx_t; typedef struct md5_ctx_vector { u32x h[4]; u32x w0[4]; u32x w1[4]; u32x w2[4]; u32x w3[4]; int len; } md5_ctx_vector_t; typedef struct md5_hmac_ctx_vector { md5_ctx_vector_t ipad; md5_ctx_vector_t opad; } md5_hmac_ctx_vector_t; DECLSPEC void md5_transform (const u32 *w0, const u32 *w1, const u32 *w2, const u32 *w3, u32 *digest); DECLSPEC void md5_init (md5_ctx_t *ctx); DECLSPEC void md5_update_64 (md5_ctx_t *ctx, u32 *w0, u32 *w1, u32 *w2, u32 *w3, const int len); DECLSPEC void md5_update (md5_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_update_swap (md5_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_update_utf16le (md5_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_update_utf16le_swap (md5_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_update_global (md5_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_update_global_swap (md5_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_update_global_utf16le (md5_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_update_global_utf16le_swap (md5_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_final (md5_ctx_t *ctx); DECLSPEC void md5_hmac_init_64 (md5_hmac_ctx_t *ctx, const u32 *w0, const u32 *w1, const u32 *w2, const u32 *w3); DECLSPEC void md5_hmac_init (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_init_swap (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_init_global (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_init_global_swap (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_update_64 (md5_hmac_ctx_t *ctx, u32 *w0, u32 *w1, u32 *w2, u32 *w3, const int len); DECLSPEC void md5_hmac_update (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_update_swap (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_update_utf16le (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_update_utf16le_swap (md5_hmac_ctx_t *ctx, const u32 *w, const int len); DECLSPEC void md5_hmac_update_global (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_update_global_swap (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_update_global_utf16le (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_update_global_utf16le_swap (md5_hmac_ctx_t *ctx, GLOBAL_AS const u32 *w, const int len); DECLSPEC void md5_hmac_final (md5_hmac_ctx_t *ctx); DECLSPEC void md5_transform_vector (const u32x *w0, const u32x *w1, const u32x *w2, const u32x *w3, u32x *digest); DECLSPEC void md5_init_vector (md5_ctx_vector_t *ctx); DECLSPEC void md5_init_vector_from_scalar (md5_ctx_vector_t *ctx, md5_ctx_t *ctx0); DECLSPEC void md5_update_vector_64 (md5_ctx_vector_t *ctx, u32x *w0, u32x *w1, u32x *w2, u32x *w3, const int len); DECLSPEC void md5_update_vector (md5_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_update_vector_swap (md5_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_update_vector_utf16le (md5_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_update_vector_utf16le_swap (md5_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_final_vector (md5_ctx_vector_t *ctx); DECLSPEC void md5_hmac_init_vector_64 (md5_hmac_ctx_vector_t *ctx, const u32x *w0, const u32x *w1, const u32x *w2, const u32x *w3); DECLSPEC void md5_hmac_init_vector (md5_hmac_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_hmac_update_vector_64 (md5_hmac_ctx_vector_t *ctx, u32x *w0, u32x *w1, u32x *w2, u32x *w3, const int len); DECLSPEC void md5_hmac_update_vector (md5_hmac_ctx_vector_t *ctx, const u32x *w, const int len); DECLSPEC void md5_hmac_final_vector (md5_hmac_ctx_vector_t *ctx); #endif
BearerPipelineTest/daml
navigator/backend/src/main/scala/com/digitalasset/navigator/dotnot/package.scala
// Copyright (c) 2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.navigator /** dotnot(ation) is a simple library to implement a string-based dot-notation system * to access properties. A property is something in dot notation `branch1.branch2.leaf` * similar to the dot-notation in scala to reference a field. * * The idea is to represent all the possible paths from the root of the model down * to the leafs with a nice DSL. * * Naming: * - `Tree`: the model is seen as a `Tree` where each portion can either be a `Leaf` or a `Branch` * - `Leaf`: a node of the Tree that contains only one value (e.g. a primitive field, like `Int`) * - `Branch`: a non-leaf part of the model (e.g. an object with fields) * - `root`: the entry point and root of the Tree * - `path` or `property`: the list of all the pieces of the `Tree` from the `root` to a `leaf` * - `dotnot handler for k`: the set of all the paths and actions to be performed on an instance of `k` */ package dotnot { sealed trait DotNotFailure { def cursor: PropertyCursor def value: String } final case class CannotBeEmpty(target: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class MustBeLastPart(target: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class MustNotBeLastPart(target: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class TypeCoercionFailure( target: String, expectedType: String, cursor: PropertyCursor, value: String, ) extends DotNotFailure final case class UnknownProperty(target: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class MatchNotFoundForValue(target: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class UnknownType(name: String, cursor: PropertyCursor, value: String) extends DotNotFailure final case class NameMatcherToAction[T, R, C](matcher: NameMatcher, action: Action[T, R, C]) final case class ValueMatcherToAction[T, R, C](matcher: ValueMatcher, action: Action[T, R, C]) /** Utility for debugging purposes, implements an equalsTo function with a toString defined */ final case class equalsTo[T](t: T) extends Function[T, Boolean] { def apply(t2: T): Boolean = t == t2 override def toString: String = s"""_ == $t""" } final case object constTrue extends Function[String, Boolean] { def apply(s: String): Boolean = true override def toString: String = s"""_ => true""" } sealed trait OnTreeBase[T, R, C] { def target: String def onTree: OnTreeReady[T, R, C] def onLeafP(nameMatcher: NameMatcher): OnLeaf[T, R, C] = OnLeaf[T, R, C](onTree, nameMatcher) def onLeaf(name: String): OnLeaf[T, R, C] = onLeafP(equalsTo(name)) /** Match a branch by predicate on the name and delegate handling the subtree from that branch * * @param nameMatcher matcher of the branch name * @param project the projection from the parent model of type `T` to the child model * `P` where `P` is the type of the field of an instance of `T` * @param delegate the dotnot handler for the subtree */ def onBranchP[P]( nameMatcher: NameMatcher, project: T => P, delegate: OnTreeReady[P, R, C], ): OnTreeReady[T, R, C] = { val action: (T, PropertyCursor, String, C) => Either[DotNotFailure, R] = (t: T, cursor: PropertyCursor, value: String, context: C) => { cursor.next match { case None => Left(MustNotBeLastPart(target, cursor, value)) case Some(nextCursor) => val p = project(t) delegate.run(p, nextCursor, value, context) } } val nameMatcherToAction = NameMatcherToAction[T, R, C](nameMatcher, action) onTree.copy(nameMatcherToActions = onTree.nameMatcherToActions :+ nameMatcherToAction) } /** Same as [[onBranchP]] but match the branch by name */ def onBranch[P]( name: String, project: T => P, delegate: OnTreeReady[P, R, C], ): OnTreeReady[T, R, C] = if (name == "*") { onBranchP[P](constTrue, project, delegate) } else { onBranchP[P](equalsTo(name), project, delegate) } /** Given a collection, match one the first element `e` with `getName(e)` equal to * the value currently pointed by the cursor and then delegate handling that element * to `delegate` * * @param getName a function to read the name of `E` * @param delegate the dotnot handler for `e` */ def onElements[E](getName: E => String, delegate: OnTreeReady[E, R, C])(implicit ev: T <:< Iterable[E] ): OnTreeReady[T, R, C] = { val action: (T, PropertyCursor, String, C) => Either[DotNotFailure, R] = (t: T, cursor: PropertyCursor, value: String, context: C) => { cursor.next match { case None => Left(MustNotBeLastPart(target, cursor, value)) case Some(nextCursor) => t.find(getName(_).toLowerCase == cursor.current.toLowerCase) match { case None => Left(UnknownProperty(target, cursor, value)) case Some(e) => delegate.run(e, nextCursor, value, context) } } } val nameMatcherToAction = NameMatcherToAction[T, R, C](constTrue, action) onTree.copy(nameMatcherToActions = onTree.nameMatcherToActions :+ nameMatcherToAction) } def run(t: T, cursor: PropertyCursor, value: String, context: C): Either[DotNotFailure, R] = { onTree.nameMatcherToActions .find(_.matcher(cursor.current)) .map(_.action) .orElse(onTree.default) match { case None => Left(UnknownProperty(target, cursor, value)) case Some(action) => action(t, cursor, value, context) } } } final case class OnTree[T, R, C](target: String) extends OnTreeBase[T, R, C] { def onTree: OnTreeReady[T, R, C] = OnTreeReady[T, R, C](target, Vector(), None) } final case class OnTreeReady[T, R, C]( target: String, nameMatcherToActions: Vector[NameMatcherToAction[T, R, C]], default: Option[Action[T, R, C]], ) extends OnTreeBase[T, R, C] { override def onTree: OnTreeReady[T, R, C] = this } sealed trait OnLeafBase[T, R, C] { def onTreeOld: OnTreeReady[T, R, C] def leafMatcher: NameMatcher def valueMatcherToActions: Vector[ValueMatcherToAction[T, R, C]] def default: Option[Action[T, R, C]] def onValueP(valueMatcher: ValueMatcher): OnValue[T, R, C] = OnValue[T, R, C]( OnLeafReady(onTreeOld, leafMatcher, valueMatcherToActions, default), valueMatcher, ) def onValue(value: String): OnValue[T, R, C] = onValueP(equalsTo(value)) def onAnyValue: OnValue[T, R, C] = onValueP(constTrue) } final case class OnLeaf[T, R, C](onTreeOld: OnTreeReady[T, R, C], leafMatcher: NameMatcher) extends OnLeafBase[T, R, C] { override def valueMatcherToActions: Vector[ValueMatcherToAction[T, R, C]] = Vector() override def default: Option[Action[T, R, C]] = None } final case class OnLeafReady[T, R, C]( onTreeOld: OnTreeReady[T, R, C], leafMatcher: NameMatcher, valueMatcherToActions: Vector[ValueMatcherToAction[T, R, C]], default: Option[Action[T, R, C]], ) extends OnLeafBase[T, R, C] with OnTreeBase[T, R, C] { override def target: String = onTreeOld.target private def nameAction: NameMatcherToAction[T, R, C] = { val action: Action[T, R, C] = (t: T, cursor: PropertyCursor, value: String, context: C) => { valueMatcherToActions.find(_.matcher(value)).map(_.action).orElse(default) match { case None => Left(MatchNotFoundForValue(onTreeOld.target, cursor, value)) case Some(action) => action(t, cursor, value, context) } } NameMatcherToAction[T, R, C](leafMatcher, action) } private def onTreeUpdated: OnTreeReady[T, R, C] = onTreeOld.copy(nameMatcherToActions = onTreeOld.nameMatcherToActions :+ nameAction) override def onTree: OnTreeReady[T, R, C] = onTreeUpdated } final case class OnValue[T, R, C](onLeaf: OnLeafReady[T, R, C], valueMatcher: ValueMatcher) { def perform[K](f: (T, K) => R)(implicit readK: Read[K]): OnLeafReady[T, R, C] = { val action: Action[T, R, C] = (t: T, cursor: PropertyCursor, value: String, _: C) => { if (cursor.isLast) { Right(f(t, readK.from(value).toOption.get)) } else { Left(MustBeLastPart(onLeaf.onTreeOld.target, cursor, value)) } } val valueMatcherToAction = ValueMatcherToAction(valueMatcher, action) onLeaf.copy(valueMatcherToActions = onLeaf.valueMatcherToActions :+ valueMatcherToAction) } def const(r: R): OnLeafReady[T, R, C] = perform[String]((_: T, _: String) => r) } } package object dotnot { type NameMatcher = String => Boolean type ValueMatcher = String => Boolean type Action[T, R, C] = (T, PropertyCursor, String, C) => Either[DotNotFailure, R] /** Create a dot-notation handler for a type `T` with name `name` and with return * type from the leafs of type `R` */ def root[T, R, C](name: String): OnTree[T, R, C] = OnTree[T, R, C](name) /** Utility method that creates a "opaque" dot-notation handler, which is * a handler that bypass the library and uses the given function `f` to * access the underlying structure of type `T` and to produce a result of * type `R`. * * Useful for when dotnot is not useful */ def opaque[T, R, C](name: String)(f: Action[T, R, C]): OnTreeReady[T, R, C] = OnTreeReady[T, R, C](name, Vector(), Some(f)) }
anshika581/competitive-programming-1
src/contest/ioi/IOI_2015_Boxes.cc
#include <bits/stdc++.h> using namespace std; #define SIZE 10000002 typedef long long ll; ll dp1[SIZE], dp2[SIZE]; ll delivery(int N, int K, int L, int positions[]) { for (int i = 1; i <= N; i++) { if (i >= K) dp1[i] = dp1[i - K] + min(2 * positions[i - 1], L); else dp1[i] = min(2 * positions[i - 1], L); } for (int i = N; i >= 1; i--) { if (i + K <= N) dp2[i] = dp2[i + K] + min(2 * (L - positions[i - 1]), L); else dp2[i] = min(2 * (L - positions[i - 1]), L); } ll ans = 1ll << 60; for (int i = 0; i <= N; i++) ans = min(ans, dp1[i] + dp2[i + 1]); return ans; } int main() { int N, K, L; scanf("%d%d%d", &N, &K, &L); int positions[N]; for (int i = 0; i < N; i++) scanf("%d", &positions[i]); printf("%lld\n", delivery(N, K, L, positions)); return 0; }
congscallion/geekbang-lessons
training-camp/xiaomage-java/stage-0/user-platform/user-web/src/main/java/slydm/geektimes/training/projects/user/web/controller/validator/groups/user/LoginGroup.java
package slydm.geektimes.training.projects.user.web.controller.validator.groups.user; /** * @author <EMAIL>(wangcong) 2021/3/13 11:47 */ public interface LoginGroup { }
tsavola/tap
tap/core/long.cpp
#include "core.hpp" #include "portable.hpp" namespace tap { static int long_traverse(PyObject *object, visitproc visit, void *arg) noexcept { return 0; } static Py_ssize_t long_marshaled_size(PyObject *object) noexcept { return sizeof (int64_t); } static int long_marshal(PyObject *object, void *buf, Py_ssize_t size, PeerObject &peer) noexcept { int overflow; int64_t value = PyLong_AsLongLongAndOverflow(object, &overflow); if (overflow != 0) return -1; *reinterpret_cast<int64_t *> (buf) = port(value); return 0; } static PyObject *long_unmarshal_alloc(const void *data, Py_ssize_t size, PeerObject &peer) noexcept { if (size != sizeof (int64_t)) return nullptr; return PyLong_FromLongLong(port(*reinterpret_cast<const int64_t *> (data))); } static int long_unmarshal_init(PyObject *object, const void *data, Py_ssize_t size, PeerObject &peer) noexcept { return 0; } const TypeHandler long_type_handler = { LONG_TYPE_ID, long_traverse, long_marshaled_size, long_marshal, long_unmarshal_alloc, long_unmarshal_init, }; } // namespace tap
v0idp/virtuoso-codegen
include/System/Xml/Serialization/XmlArrayItemAttributes.hpp
<reponame>v0idp/virtuoso-codegen<filename>include/System/Xml/Serialization/XmlArrayItemAttributes.hpp // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Collections.CollectionBase #include "System/Collections/CollectionBase.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Xml::Serialization namespace System::Xml::Serialization { // Forward declaring type: XmlArrayItemAttribute class XmlArrayItemAttribute; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Forward declaring type: XmlArrayItemAttributes class XmlArrayItemAttributes; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Xml::Serialization::XmlArrayItemAttributes); DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Serialization::XmlArrayItemAttributes*, "System.Xml.Serialization", "XmlArrayItemAttributes"); // Type namespace: System.Xml.Serialization namespace System::Xml::Serialization { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: System.Xml.Serialization.XmlArrayItemAttributes // [TokenAttribute] Offset: FFFFFFFF // [DefaultMemberAttribute] Offset: 6A44CC class XmlArrayItemAttributes : public ::System::Collections::CollectionBase { public: // public System.Xml.Serialization.XmlArrayItemAttribute get_Item(System.Int32 index) // Offset: 0x11B3C8C ::System::Xml::Serialization::XmlArrayItemAttribute* get_Item(int index); // public System.Void .ctor() // Offset: 0x11B3F48 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static XmlArrayItemAttributes* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Serialization::XmlArrayItemAttributes::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<XmlArrayItemAttributes*, creationType>())); } // public System.Int32 Add(System.Xml.Serialization.XmlArrayItemAttribute attribute) // Offset: 0x11B3DA0 int Add(::System::Xml::Serialization::XmlArrayItemAttribute* attribute); // System.Void AddKeyHash(System.Text.StringBuilder sb) // Offset: 0x11B3E6C void AddKeyHash(::System::Text::StringBuilder* sb); }; // System.Xml.Serialization.XmlArrayItemAttributes #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Xml::Serialization::XmlArrayItemAttributes::get_Item // Il2CppName: get_Item template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Xml::Serialization::XmlArrayItemAttribute* (System::Xml::Serialization::XmlArrayItemAttributes::*)(int)>(&System::Xml::Serialization::XmlArrayItemAttributes::get_Item)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Serialization::XmlArrayItemAttributes*), "get_Item", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } }; // Writing MetadataGetter for method: System::Xml::Serialization::XmlArrayItemAttributes::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Xml::Serialization::XmlArrayItemAttributes::Add // Il2CppName: Add template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Xml::Serialization::XmlArrayItemAttributes::*)(::System::Xml::Serialization::XmlArrayItemAttribute*)>(&System::Xml::Serialization::XmlArrayItemAttributes::Add)> { static const MethodInfo* get() { static auto* attribute = &::il2cpp_utils::GetClassFromName("System.Xml.Serialization", "XmlArrayItemAttribute")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Serialization::XmlArrayItemAttributes*), "Add", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{attribute}); } }; // Writing MetadataGetter for method: System::Xml::Serialization::XmlArrayItemAttributes::AddKeyHash // Il2CppName: AddKeyHash template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::Serialization::XmlArrayItemAttributes::*)(::System::Text::StringBuilder*)>(&System::Xml::Serialization::XmlArrayItemAttributes::AddKeyHash)> { static const MethodInfo* get() { static auto* sb = &::il2cpp_utils::GetClassFromName("System.Text", "StringBuilder")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Serialization::XmlArrayItemAttributes*), "AddKeyHash", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sb}); } };
before30/homesandbox
algorithm-ex/src/main/java/cc/before30/algex/array/SquaresOfSortedArray.java
package cc.before30.algex.array; import java.util.Arrays; public class SquaresOfSortedArray { public int[] sortedSquares(int[] A) { return Arrays.stream(A).map(x -> x*x).sorted().toArray(); } }
Akarin-project/AkarinModEdition
src/main/java/net/minecraft/server/DebugLoggingPrintStream.java
<gh_stars>1-10 package net.minecraft.server; import java.io.OutputStream; import net.minecraft.util.LoggingPrintStream; public class DebugLoggingPrintStream extends LoggingPrintStream { public DebugLoggingPrintStream(String s, OutputStream outputstream) { super(s, outputstream); } protected void func_179882_a(String s) { StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); StackTraceElement stacktraceelement = astacktraceelement[Math.min(3, astacktraceelement.length)]; DebugLoggingPrintStream.field_179884_a.info("[{}]@.({}:{}): {}", this.field_179883_b, stacktraceelement.getFileName(), Integer.valueOf(stacktraceelement.getLineNumber()), s); } }
ravindraranwala/JavaGenericsAndCollections
GenericsAndCollections/src/main/java/org/oreilly/books/chapter8/NaiveBroker.java
package org.oreilly.books.chapter8; import java.util.ArrayList; import java.util.List; public class NaiveBroker { public void connect(OrderSupplier supplier, OrderProcessor processor) { List<AuthenticatedOrder> orders = new ArrayList<AuthenticatedOrder>(); supplier.addOrders(orders); processor.processOrders(orders); } }
smallspark/dealview
src/components/EditLoan.js
<filename>src/components/EditLoan.js import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { withRouter } from 'react-router' import LoanForm from './LoanForm.js' import Breadcrumbs from './Breadcrumbs.js' import NotFound from './NotFound.js' import LoanActions from '../actions/loans.js' import './styles/EditLoan.css' export class EditLoan extends React.Component { static propTypes = { id: PropTypes.string.isRequired, loan: PropTypes.shape({ status: PropTypes.oneOf([ 'uninitialised', 'loading', 'loaded', 'error' ]), object: PropTypes.object, }), } constructor(props) { super(props) if (this.props.loan.status === 'uninitialised') { this.props.dispatch(LoanActions.loadLoans()) } this.handleSubmit = this.handleSubmit.bind(this) } breadcrumbs() { const { id, loan: { object: loan } } = this.props const loanName = typeof loan === 'undefined' ? id : loan.name return [ { display: 'Portfolio', path: '/portfolio' }, { display: 'Liabilities', path: '/portfolio/liabilities' }, { display: loanName, path: `/portfolio/liabilities/loans/${id}` }, ] } handleSubmit(loan) { this.props.dispatch(LoanActions.putLoan(loan)) this.props.history.push('/portfolio/liabilities') } componentWillReceiveProps(nextProps) { if (nextProps.loan.status === 'uninitialised') { this.props.dispatch(LoanActions.loadLoans()) } } render() { return typeof this.props.loan.object === 'undefined' ? <NotFound /> : <div className='edit-loan'> <Breadcrumbs breadcrumbs={this.breadcrumbs()} /> <LoanForm loan={this.props.loan.object} onSubmit={this.handleSubmit} /> </div> } } const mapStateToProps = (state, ownProps) => ({ loan: { status: state.loans.status, object: state.loans.objects[ownProps.id], }, }) export default connect(mapStateToProps)(withRouter(EditLoan))
acaos/nwnxee-unified
Plugins/JVM/java/src/org/nwnx/nwnx2/jvm/constants/ColorChannel.java
package org.nwnx.nwnx2.jvm.constants; /** * This class contains all unique constants beginning with "COLOR_CHANNEL". * Non-distinct keys are filtered; only the LAST appearing was * kept. */ public final class ColorChannel { private ColorChannel() {} public final static int HAIR = 1; public final static int SKIN = 0; public final static int TATTOO_1 = 2; public final static int TATTOO_2 = 3; public static String nameOf(int value) { if (value == 1) return "ColorChannel.HAIR"; if (value == 0) return "ColorChannel.SKIN"; if (value == 2) return "ColorChannel.TATTOO_1"; if (value == 3) return "ColorChannel.TATTOO_2"; return "ColorChannel.(not found: " + value + ")"; } public static String nameOf(float value) { return "ColorChannel.(not found: " + value + ")"; } public static String nameOf(String value) { return "ColorChannel.(not found: " + value + ")"; } }
v0idp/virtuoso-codegen
include/Newtonsoft/Json/Utilities/ImmutableCollectionsUtils.hpp
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Newtonsoft::Json::Utilities namespace Newtonsoft::Json::Utilities { } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IList`1<T> template<typename T> class IList_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Forward declaring namespace: Newtonsoft::Json::Serialization namespace Newtonsoft::Json::Serialization { // Forward declaring type: ObjectConstructor`1<T> template<typename T> class ObjectConstructor_1; } // Completed forward declares // Type namespace: Newtonsoft.Json.Utilities namespace Newtonsoft::Json::Utilities { // Forward declaring type: ImmutableCollectionsUtils class ImmutableCollectionsUtils; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils); DEFINE_IL2CPP_ARG_TYPE(::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils*, "Newtonsoft.Json.Utilities", "ImmutableCollectionsUtils"); // Type namespace: Newtonsoft.Json.Utilities namespace Newtonsoft::Json::Utilities { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Newtonsoft.Json.Utilities.ImmutableCollectionsUtils // [TokenAttribute] Offset: FFFFFFFF // [NullableAttribute] Offset: 672D28 // [NullableContextAttribute] Offset: 672D28 class ImmutableCollectionsUtils : public ::Il2CppObject { public: // Nested type: ::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::ImmutableCollectionTypeInfo class ImmutableCollectionTypeInfo; // Nested type: ::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::$$c__DisplayClass24_0 class $$c__DisplayClass24_0; // Nested type: ::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::$$c class $$c; // Nested type: ::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::$$c__DisplayClass25_0 class $$c__DisplayClass25_0; // Get static field: static private readonly System.Collections.Generic.IList`1<Newtonsoft.Json.Utilities.ImmutableCollectionsUtils/Newtonsoft.Json.Utilities.ImmutableCollectionTypeInfo> ArrayContractImmutableCollectionDefinitions static ::System::Collections::Generic::IList_1<::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::ImmutableCollectionTypeInfo*>* _get_ArrayContractImmutableCollectionDefinitions(); // Set static field: static private readonly System.Collections.Generic.IList`1<Newtonsoft.Json.Utilities.ImmutableCollectionsUtils/Newtonsoft.Json.Utilities.ImmutableCollectionTypeInfo> ArrayContractImmutableCollectionDefinitions static void _set_ArrayContractImmutableCollectionDefinitions(::System::Collections::Generic::IList_1<::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::ImmutableCollectionTypeInfo*>* value); // Get static field: static private readonly System.Collections.Generic.IList`1<Newtonsoft.Json.Utilities.ImmutableCollectionsUtils/Newtonsoft.Json.Utilities.ImmutableCollectionTypeInfo> DictionaryContractImmutableCollectionDefinitions static ::System::Collections::Generic::IList_1<::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::ImmutableCollectionTypeInfo*>* _get_DictionaryContractImmutableCollectionDefinitions(); // Set static field: static private readonly System.Collections.Generic.IList`1<Newtonsoft.Json.Utilities.ImmutableCollectionsUtils/Newtonsoft.Json.Utilities.ImmutableCollectionTypeInfo> DictionaryContractImmutableCollectionDefinitions static void _set_DictionaryContractImmutableCollectionDefinitions(::System::Collections::Generic::IList_1<::Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::ImmutableCollectionTypeInfo*>* value); // static private System.Void .cctor() // Offset: 0xED9AC0 static void _cctor(); // static System.Boolean TryBuildImmutableForArrayContract(System.Type underlyingType, System.Type collectionItemType, out System.Type createdType, out Newtonsoft.Json.Serialization.ObjectConstructor`1<System.Object> parameterizedCreator) // Offset: 0xED912C static bool TryBuildImmutableForArrayContract(::System::Type* underlyingType, ::System::Type* collectionItemType, ByRef<::System::Type*> createdType, ByRef<::Newtonsoft::Json::Serialization::ObjectConstructor_1<::Il2CppObject*>*> parameterizedCreator); // static System.Boolean TryBuildImmutableForDictionaryContract(System.Type underlyingType, System.Type keyItemType, System.Type valueItemType, out System.Type createdType, out Newtonsoft.Json.Serialization.ObjectConstructor`1<System.Object> parameterizedCreator) // Offset: 0xED95C8 static bool TryBuildImmutableForDictionaryContract(::System::Type* underlyingType, ::System::Type* keyItemType, ::System::Type* valueItemType, ByRef<::System::Type*> createdType, ByRef<::Newtonsoft::Json::Serialization::ObjectConstructor_1<::Il2CppObject*>*> parameterizedCreator); }; // Newtonsoft.Json.Utilities.ImmutableCollectionsUtils #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::ImmutableCollectionsUtils*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::TryBuildImmutableForArrayContract // Il2CppName: TryBuildImmutableForArrayContract template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::System::Type*, ByRef<::System::Type*>, ByRef<::Newtonsoft::Json::Serialization::ObjectConstructor_1<::Il2CppObject*>*>)>(&Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::TryBuildImmutableForArrayContract)> { static const MethodInfo* get() { static auto* underlyingType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* collectionItemType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* createdType = &::il2cpp_utils::GetClassFromName("System", "Type")->this_arg; static auto* parameterizedCreator = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("Newtonsoft.Json.Serialization", "ObjectConstructor`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Object")})->this_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::ImmutableCollectionsUtils*), "TryBuildImmutableForArrayContract", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{underlyingType, collectionItemType, createdType, parameterizedCreator}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::TryBuildImmutableForDictionaryContract // Il2CppName: TryBuildImmutableForDictionaryContract template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::System::Type*, ::System::Type*, ByRef<::System::Type*>, ByRef<::Newtonsoft::Json::Serialization::ObjectConstructor_1<::Il2CppObject*>*>)>(&Newtonsoft::Json::Utilities::ImmutableCollectionsUtils::TryBuildImmutableForDictionaryContract)> { static const MethodInfo* get() { static auto* underlyingType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* keyItemType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* valueItemType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* createdType = &::il2cpp_utils::GetClassFromName("System", "Type")->this_arg; static auto* parameterizedCreator = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("Newtonsoft.Json.Serialization", "ObjectConstructor`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Object")})->this_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::ImmutableCollectionsUtils*), "TryBuildImmutableForDictionaryContract", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{underlyingType, keyItemType, valueItemType, createdType, parameterizedCreator}); } };
joshlevi/svgedit
src/editor/components/seColorPicker.js
<reponame>joshlevi/svgedit /* globals svgEditor */ /* eslint-disable max-len */ import { jGraduate, jGraduateMethod } from './jgraduate/jQuery.jGraduate.js'; import PaintBox from './PaintBox.js'; import { t } from '../locale.js'; const template = document.createElement('template'); // eslint-disable-next-line no-unsanitized/property template.innerHTML = ` <style> .jPicker .Icon { display: inline-block; height: 24px; position: relative; text-align: left; width: 25px } .jPicker .Icon span.Color, .jPicker .Icon span.Alpha { background-position: 2px 2px; display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100% } .jPicker .Icon span.Image { background-repeat: no-repeat; cursor: pointer; display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100% } .jPicker.Container { z-index: 10 } table.jPicker { background-color: #efefef; border: 1px outset #666; font-family: Arial, Helvetica, Sans-Serif; font-size: 12px!important; margin: 0; padding: 5px; width: 545px; z-index: 20 } .jPicker .Move { background-color: #ddd; border-color: #fff #666 #666 #fff; border-style: solid; border-width: 1px; cursor: move; height: 12px; padding: 0 } .jPicker .Title { font-size: 11px!important; font-weight: bold; margin: -2px 0 0 0; padding: 0; text-align: center; width: 100% } .jPicker div.Map { border-bottom: 2px solid #fff; border-left: 2px solid #9a9a9a; border-right: 2px solid #fff; border-top: 2px solid #9a9a9a; cursor: crosshair; height: 260px; margin: 0 5px 0 5px; overflow: hidden; padding: 0; position: relative; width: 260px } .jPicker div[class="Map"] { height: 256px; width: 256px } .jPicker div.Bar { border-bottom: 2px solid #fff; border-left: 2px solid #9a9a9a; border-right: 2px solid #fff; border-top: 2px solid #9a9a9a; cursor: n-resize; height: 260px; margin: 12px 10px 0 5px; overflow: hidden; padding: 0; position: relative; width: 24px } .jPicker div[class="Bar"] { height: 256px; width: 20px } .jPicker .Map .Map1, .jPicker .Map .Map2, .jPicker .Map .Map3, .jPicker .Bar .Map1, .jPicker .Bar .Map2, .jPicker .Bar .Map3, .jPicker .Bar .Map4, .jPicker .Bar .Map5, .jPicker .Bar .Map6 { background-color: transparent; background-image: none; display: block; left: 0; position: absolute; top: 0 } .jPicker .Map .Map1, .jPicker .Map .Map2, .jPicker .Map .Map3 { height: 2596px; width: 256px } .jPicker .Bar .Map1, .jPicker .Bar .Map2, .jPicker .Bar .Map3, .jPicker .Bar .Map4 { height: 3896px; width: 20px } .jPicker .Bar .Map5, .jPicker .Bar .Map6 { height: 256px; width: 20px } .jPicker .Map .Map1, .jPicker .Map .Map2, .jPicker .Bar .Map6 { background-repeat: no-repeat } .jPicker .Map .Map3, .jPicker .Bar .Map5 { background-repeat: repeat } .jPicker .Bar .Map1, .jPicker .Bar .Map2, .jPicker .Bar .Map3, .jPicker .Bar .Map4 { background-repeat: repeat-x } .jPicker .Map .Arrow { display: block; position: absolute } .jPicker .Bar .Arrow { display: block; left: 0; position: absolute } .jPicker .Preview { font-size: 9px; text-align: center } .jPicker .Preview div { border: 2px inset #eee; height: 62px; margin: 0 auto; padding: 0; width: 62px } .jPicker .Preview div span { border: 1px solid #000; display: block; height: 30px; margin: 0 auto; padding: 0; width: 60px } .jPicker .Preview .Active { border-bottom-width: 0 } .jPicker .Preview .Current { border-top-width: 0; cursor: pointer } .jPicker .Button { text-align: center; width: 115px } .jPicker .Button input { width: 100px } .jPicker .Button .Ok { margin: 12px 0 5px 0 } .jPicker td.Radio { margin: 0; padding: 0; width: 31px } .jPicker td.Radio input { margin: 0 5px 0 0; padding: 0 } .jPicker td.Text { font-size: 12px!important; height: 22px; margin: 0; padding: 0; text-align: left; width: 70px } .jPicker tr.Hex td.Text { width: 100px } .jPicker td.Text input { background-color: #fff; border: 1px inset #aaa; height: 19px; margin: 0 0 0 5px; text-align: left; width: 30px } .jPicker td[class="Text"] input { height: 15px } .jPicker tr.Hex td.Text input.Hex { width: 50px } .jPicker tr.Hex td.Text input.AHex { width: 20px } .jPicker .Grid { text-align: center; width: 114px } .jPicker .Grid span.QuickColor { border: 1px inset #aaa; cursor: pointer; display: inline-block; height: 15px; line-height: 15px; margin: 0; padding: 0; width: 19px } .jPicker .Grid span[class="QuickColor"] { width: 17px } /* * jGraduate Default CSS * * Copyright (c) 2010 <NAME> * http://blog.codedread.com/ * * Copyright (c) 2010 <NAME> * http://a.deveria.com/ * * Licensed under the MIT License */ h2.jGraduate_Title { font-family: Arial, Helvetica, Sans-Serif; font-size: 11px !important; font-weight: bold; margin: -13px 0px 0px 0px; padding: 0px; text-align: center; } .jGraduate_Picker { font-family: Arial, Helvetica, Sans-Serif; font-size: 12px; border-style: solid; border-color: lightgrey black black lightgrey; border-width: 1px; background-color: #EFEFEF; position: absolute; padding: 10px; } .jGraduate_tabs li { background-color: #ccc; display: inline; border: solid 1px grey; padding: 3px; margin: 2px; cursor: pointer; } li.jGraduate_tab_current { background-color: #EFEFEF; display: inline; padding: 3px; margin: 2px; border: solid 1px black; cursor: pointer; } .jGraduate_colPick { display: none; } .jGraduate_gradPick { display: none; border: outset 1px #666; padding: 10px 7px 5px 5px; overflow: auto; } .jGraduate_gradPick { display: none; border: outset 1px #666; padding: 10px 7px 5px 5px; overflow: auto; /* position: relative;*/ } .jGraduate_tabs { position: relative; background-color: #EFEFEF; padding: 0px; margin: 0px; margin-bottom: 5px; } div.jGraduate_Swatch { float: left; margin: 8px; } div.jGraduate_GradContainer { border: 2px inset #EEE; background-image: url(./components/jgraduate/images/map-opacity.png); background-position: 0px 0px; height: 256px; width: 256px; position: relative; } div.jGraduate_GradContainer div.grad_coord { background: #000; border: 1px solid #fff; border-radius: 5px; -moz-border-radius: 5px; width: 10px; height: 10px; position: absolute; margin: -5px -5px; top: 0; left: 0; text-align: center; font-size: xx-small; line-height: 10px; color: #fff; text-decoration: none; cursor: pointer; -moz-user-select: none; -webkit-user-select: none; } .jGraduate_AlphaArrows { position: absolute; margin-top: -10px; margin-left: 250.5px; } div.jGraduate_Opacity { border: 2px inset #eee; margin-top: 14px; background-color: black; background-image: url(../images/Maps.png); background-position: 0px -2816px; height: 20px; cursor: ew-resize; } div.jGraduate_StopSlider { /* border: 2px inset #eee;*/ margin: 0 0 0 -10px; width: 276px; overflow: visible; background: #efefef; height: 45px; cursor: pointer; } div.jGraduate_StopSection { width: 120px; text-align: center; } input.jGraduate_Ok, input.jGraduate_Cancel { display: block; width: 100px; margin-left: -4px; margin-right: -4px; } input.jGraduate_Ok { margin: 9px -4px 5px -4px; } .colorBox { float: left; height: 16px; width: 16px; border: 1px solid var(--border-color); cursor: pointer; margin: 4px 4px 4px 30px; } .colorBox + label { float: left; margin-top: 7px; } label.jGraduate_Form_Heading { position: relative; top: 10px; background-color: #EFEFEF; padding: 2px; font-weight: bold; font-size: 13px; } div.jGraduate_Form_Section { border-style: solid; border-width: 1px; border-color: grey; -moz-border-radius: 5px; -webkit-border-radius: 5px; padding: 15px 5px 5px 5px; margin: 5px 2px; width: 110px; text-align: center; overflow: auto; } div.jGraduate_Form_Section label { padding: 0 2px; } div.jGraduate_StopSection input[type=text], div.jGraduate_Slider input[type=text] { width: 33px; } div.jGraduate_LightBox { position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; background-color: #000; opacity: 0.5; display: none; } div.jGraduate_stopPicker { position: absolute; display: none; background: #E8E8E8; } .jGraduate_gradPick { width: 535px; } .jGraduate_gradPick div.jGraduate_OpacField { position: absolute; left: 0; bottom: 5px; /* width: 270px; left: 284px; width: 266px; height: 200px; top: 167px; margin: -3px 3px 0px 4px; */ } .jGraduate_gradPick .jGraduate_Form { float: left; width: 270px; position: absolute; left: 284px; width: 266px; height: 200px; top: 167px; margin: -3px 3px 0px 10px; } .jGraduate_gradPick .jGraduate_Points { position: static; width: 150px; margin-left: 0; } .jGraduate_SpreadMethod { position: absolute; right: 8px; top: 100px; } .jGraduate_Colorblocks { display: table; border-spacing: 0 5px; } .jGraduate_colorblock { display: table-row; } .jGraduate_Colorblocks .jGraduate_colorblock > * { display: table-cell; vertical-align: middle; margin: 0; float: none; } .jGraduate_gradPick div.jGraduate_StopSection { float: left; width: 133px; margin-top: -8px; } .jGraduate_gradPick .jGraduate_Form_Section { padding-top: 9px; } .jGraduate_Slider { text-align: center; float: left; width: 100%; } .jGraduate_Slider .jGraduate_Form_Section { border: none; width: 250px; padding: 0 2px; overflow: visible; } .jGraduate_Slider label { display: inline-block; float: left; line-height: 50px; padding: 0; } .jGraduate_Slider label.prelabel { width: 40px; text-align: left; } .jGraduate_SliderBar { width: 140px; float: left; margin-right: 5px; border:1px solid #BBB; height:20px; margin-top:14px; margin-left:5px; position: relative; } div.jGraduate_Slider input { margin-top: 5px; } div.jGraduate_Slider img { top: 0; left: 0; position: absolute; margin-top: -10px; cursor:ew-resize; } .jGraduate_gradPick .jGraduate_OkCancel { position: absolute; top: 39px; right: 10px; width: 113px; } .jGraduate_OpacField { position: absolute; right: -10px; bottom: 0; } #logo { height: 18px; width: 18px; } #block { height: 17px; width: 14px; float: right; background-color: darkgrey; } #picker { background: var(--input-color); height: 23px; line-height: 23px; border-radius: 3px; width: 52px; display: flex; align-items: center; margin-right: 4px; margin-top: 1px; justify-content: space-evenly; } #color_picker { z-index: 1000; top: 60%; } </style> <div id="picker"> <img src="logo.svg" alt="icon" id="logo"> <label for="color" title="" id="label"></label> <div id="block"> </div> </div> <!-- hidden div --> <div id="color_picker"></div> `; /** * @class SeColorPicker */ export class SeColorPicker extends HTMLElement { /** * @function constructor */ constructor () { super(); // create the shadowDom and insert the template this._shadowRoot = this.attachShadow({ mode: 'open' }); this._shadowRoot.append(template.content.cloneNode(true)); this.$logo = this._shadowRoot.getElementById('logo'); this.$label = this._shadowRoot.getElementById('label'); this.$block = this._shadowRoot.getElementById('block'); this.paintBox = null; this.i18next = null; this.$picker = this._shadowRoot.getElementById('picker'); this.$color_picker = this._shadowRoot.getElementById('color_picker'); this.imgPath = svgEditor.configObj.curConfig.imgPath; } /** * @function init * @param {any} name * @returns {void} */ init (i18next) { this.i18next = i18next; this.setAttribute('config-change_xxx_color', t('config.change_xxx_color')); } /** * @function observedAttributes * @returns {any} observed */ static get observedAttributes () { return [ 'label', 'src', 'type', 'config-change_xxx_color' ]; } /** * @function attributeChangedCallback * @param {string} name * @param {string} oldValue * @param {string} newValue * @returns {void} */ attributeChangedCallback (name, oldValue, newValue) { if (oldValue === newValue) return; switch (name) { case 'src': this.$logo.setAttribute('src', this.imgPath + '/' + newValue); break; case 'label': this.setAttribute('title', t(newValue)); break; case 'type': this.$label.setAttribute('title', 'config.pick_paint_opavity'); break; case 'config-change_xxx_color': this.$label.setAttribute('title', newValue); break; default: // eslint-disable-next-line no-console console.error(`unknown attribute: ${name}`); break; } } /** * @function get * @returns {any} */ get label () { return this.$label.getAttribute('title'); } /** * @function set * @returns {void} */ set label (value) { this.setAttribute('label', value); } /** * @function get * @returns {any} */ get type () { return this.getAttribute('type'); } /** * @function set * @returns {void} */ set type (value) { this.setAttribute('type', value); } /** * @function get * @returns {any} */ get src () { return this.getAttribute('src'); } /** * @function set * @returns {void} */ set src (value) { this.setAttribute('src', value); } /** * @param {PlainObject} svgCanvas * @param {PlainObject} selectedElement * @param {bool} apply * @returns {void} */ update (svgCanvas, selectedElement, apply) { const paint = this.paintBox.update(svgCanvas, selectedElement); if (paint && apply) { const changeEvent = new CustomEvent('change', { detail: { paint } }); this.dispatchEvent(changeEvent); } } /** * @param {PlainObject} paint * @returns {void} */ setPaint (paint) { this.paintBox.setPaint(paint); } /** * @function connectedCallback * @returns {void} */ connectedCallback () { this.paintBox = new PaintBox(this.$block, this.type); this.$picker.addEventListener('click', () => { let { paint } = this.paintBox; jGraduateMethod( this.$color_picker, { images: { clientPath: './components/jgraduate/images/' }, paint, window: { pickerTitle: this.label }, newstop: 'inverse' }, (p) => { paint = new jGraduate.Paint(p); this.setPaint(paint); const changeEvent = new CustomEvent('change', { detail: { paint } }); this.dispatchEvent(changeEvent); this.$color_picker.style.display = 'none'; }, () => { this.$color_picker.style.display = 'none'; }, this.i18next ); }); } } // Register customElements.define('se-colorpicker', SeColorPicker);
zealoussnow/chromium
third_party/blink/web_tests/storage/domstorage/script-tests/complex-keys.js
<filename>third_party/blink/web_tests/storage/domstorage/script-tests/complex-keys.js description("Test dom storage with many different types of keys (as opposed to values)"); function test(storageString) { storage = eval(storageString); if (!storage) { testFailed(storageString + " DOES NOT exist"); return; } debug("Testing " + storageString); evalAndLog("storage.clear()"); shouldBe("storage.length", "0"); debug(""); shouldBeNull("storage.getItem('FOO')"); evalAndLog("storage.setItem('FOO', 'BAR')"); shouldBe("storage.length", "1"); shouldBeEqualToString("storage.getItem('FOO')", "BAR"); shouldBeNull("storage.getItem('foo')"); shouldBeUndefined("storage.foo"); shouldBeUndefined("storage['foo']"); evalAndLog("storage.foo = 'x'"); shouldBeEqualToString("storage.foo", "x"); shouldBeEqualToString("storage['foo']", "x"); shouldBeEqualToString("storage.getItem('foo')", "x"); evalAndLog("storage['foo'] = 'y'"); shouldBeEqualToString("storage.foo", "y"); shouldBeEqualToString("storage['foo']", "y"); shouldBeEqualToString("storage.getItem('foo')", "y"); evalAndLog("storage.setItem('foo', 'z')"); shouldBeEqualToString("storage.foo", "z"); shouldBeEqualToString("storage['foo']", "z"); shouldBeEqualToString("storage.getItem('foo')", "z"); shouldBe("storage.length", "2"); debug(""); debug("Testing a null key"); evalAndLog("storage.setItem(null, 'asdf')"); shouldBeEqualToString("storage.getItem('null')", "asdf"); shouldBeEqualToString("storage.getItem(null)", "asdf"); shouldBeEqualToString("storage['null']", "asdf"); shouldBeEqualToString("storage[null]", "asdf"); shouldBe("storage.length", "3"); evalAndLog("storage[null] = 1"); shouldBeEqualToString("storage.getItem(null)", "1"); evalAndLog("storage['null'] = 2"); shouldBeEqualToString("storage.getItem(null)", "2"); evalAndLog("storage.setItem('null', 3)"); shouldBeEqualToString("storage.getItem(null)", "3"); shouldBe("storage.length", "3"); debug(""); debug("Testing an undefined key"); evalAndLog("storage[undefined] = 'xyz'"); shouldBeEqualToString("storage.getItem('undefined')", "xyz"); shouldBeEqualToString("storage.getItem(undefined)", "xyz"); shouldBeEqualToString("storage['undefined']", "xyz"); shouldBeEqualToString("storage[undefined]", "xyz"); shouldBe("storage.length", "4"); evalAndLog("storage['undefined'] = 4"); shouldBeEqualToString("storage.getItem(undefined)", "4"); evalAndLog("storage.setItem(undefined, 5)"); shouldBeEqualToString("storage.getItem(undefined)", "5"); evalAndLog("storage.setItem('undefined', 6)"); shouldBeEqualToString("storage.getItem(undefined)", "6"); shouldBe("storage.length", "4"); debug(""); debug("Testing a numeric key"); evalAndLog("storage['2'] = 'ppp'"); shouldBeEqualToString("storage.getItem('2')", "ppp"); shouldBeEqualToString("storage.getItem(2)", "ppp"); shouldBeEqualToString("storage['2']", "ppp"); shouldBeEqualToString("storage[2]", "ppp"); shouldBe("storage.length", "5"); evalAndLog("storage[2] = 7"); shouldBeEqualToString("storage.getItem(2)", "7"); evalAndLog("storage.setItem(2, 8)"); shouldBeEqualToString("storage.getItem(2)", "8"); evalAndLog("storage.setItem('2', 9)"); shouldBeEqualToString("storage.getItem(2)", "9"); shouldBe("storage.length", "5"); debug(""); debug("Setting a non-ascii string to foo"); k = String.fromCharCode(255425) + String.fromCharCode(255) + String.fromCharCode(2554252321) + String.fromCharCode(0) + 'hello'; evalAndLog("storage[k] = 'hello'"); shouldBeEqualToString("storage.getItem(k)", "hello"); shouldBeEqualToString("storage[k]", "hello"); shouldBe("storage.length", "6"); debug(""); debug("Testing case differences"); evalAndLog("storage.foo1 = 'lower1'"); evalAndLog("storage.FOO1 = 'UPPER1'"); evalAndLog("storage['foo2'] = 'lower2'"); evalAndLog("storage['FOO2'] = 'UPPER2'"); evalAndLog("storage.setItem('foo3', 'lower3')"); evalAndLog("storage.setItem('FOO3', 'UPPER3')"); shouldBeEqualToString("storage.foo1", "lower1"); shouldBeEqualToString("storage.FOO1", "UPPER1"); shouldBeEqualToString("storage['foo2']", "lower2"); shouldBeEqualToString("storage['FOO2']", "UPPER2"); shouldBeEqualToString("storage.getItem('foo3')", "lower3"); shouldBeEqualToString("storage.getItem('FOO3')", "UPPER3"); shouldBe("storage.length", "12"); debug(""); debug("Testing overriding length"); shouldBe("storage.length", "12"); shouldBe("storage['length']", "12"); shouldBeNull("storage.getItem('length')"); evalAndLog("storage.length = 0"); shouldBe("storage.length", "12"); shouldBe("storage['length']", "12"); shouldBeNull("storage.getItem('length')"); evalAndLog("storage['length'] = 0"); shouldBe("storage.length", "12"); shouldBe("storage['length']", "12"); shouldBeNull("storage.getItem('length')"); evalAndLog("storage.setItem('length', 0)"); shouldBe("storage.length", "13"); shouldBe("storage['length']", "13"); shouldBeEqualToString("storage.getItem('length')", "0"); evalAndLog("storage.removeItem('length')"); shouldBe("storage.length", "12"); shouldBe("storage['length']", "12"); shouldBeNull("storage.getItem('length')"); evalAndLog("storage.setItem('length', 0)"); shouldBe("storage.length", "13"); } test("sessionStorage"); debug(""); debug(""); test("localStorage"); window.successfullyParsed = true; isSuccessfullyParsed();
kenpeter/mangarack.js
lib/shared/provider/mangafox/index.js
// What is a series, basically, you pass the managa url 'use strict'; var Series = require('./series'); /** * Retrieves a series. * @param {string} address * @returns {ISeries} */ module.exports = function(address) { //test //debugger; /* Flow: * Queue.prototype.push task in queues in queue.js * that._handler(that._queue.shift(), function(err) in queue.js, run one by one * _taskSeries(emitter, queue, task, done); in nodejs index.js * task.series = shared.provider(task.address); in nodejs index.js * shared/provider/index.js * providers.every(function(provider) in provider index.js, loop through each * now it meets mangafox, here */ return /^http:\/\/mangafox\.(com|me)\/manga\//i.test(address) ? new Series(address) : undefined; }; // http://mangafox.com/manga
FajraKatviro/FKFramework2
FKCore/FKPackageManager.cpp
#include "FKPackageManager.h" #include "FKLogger.h" #include <QSharedPointer> /*! \class FKPackageManager \brief Incapsulates set of FKPackages */ FKPackageManager::FKPackageManager(QObject* parent):QObject(parent),_packagesInitialized(false){ FK_CBEGIN FK_CEND } FKPackageManager::~FKPackageManager(){ FK_DBEGIN FK_DEND } void FKPackageManager::initializeManager(){ if(!_packagesInitialized){ initializePackages(); _packagesInitialized=true; } } FKPackage FKPackageManager::getPackage(const QString& packageName) const{ auto i=_packages.constFind(packageName); if(i!=_packages.constEnd()){ return i.value(); }else{ FK_MLOGV("Package not found",packageName) return FKPackage(); } } FKPackage FKPackageManager::addPackage(const QString& packageName, const QString& sourceFile){ auto i=_packages.constFind(packageName); if(i==_packages.constEnd()){ FKPackage newPackage=FKPackage(new FKPackageObject(sourceFile)); _packages.insert(packageName,newPackage); return newPackage; }else{ FK_MLOGV("Package already exists",packageName) return i.value(); } }
littleBoBoy/SUDOKU
app/src/main/java/com/example/sudoku/MainActivity.java
<gh_stars>1-10 package com.example.sudoku; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.sudoku.base.BaseActivity; import com.example.sudoku.common.ActivityController; import com.example.sudoku.module.Rank.RankActivity; import com.example.sudoku.module.game.GameActivity; import com.example.sudoku.module.login.LoginActivity; import com.example.sudoku.util.AppUtil; public class MainActivity extends BaseActivity implements View.OnClickListener { private static final String TAG = "MainActivity"; AlertDialog levelSelector; private Button gameLevel; private Button startGame; private Button continueGame; private Button login; private Button logout; private Button rank; private String[] levelName = new String[]{"入门", "初级", "中级", "高级"}; private int level = 0; @Override protected int getContentLayoutId() { return R.layout.activity_main; } @Override public void initView(Bundle savedInstanceState) { startGame = findViewById(R.id.start_game); gameLevel = findViewById(R.id.level_game); continueGame = findViewById(R.id.continue_game); logout = findViewById(R.id.logout); login = findViewById(R.id.login); rank = findViewById(R.id.btn_rank); startGame.setOnClickListener(this); gameLevel.setOnClickListener(this); continueGame.setOnClickListener(this); login.setOnClickListener(this); logout.setOnClickListener(this); rank.setOnClickListener(this); levelSelector = new AlertDialog.Builder(MainActivity.this) .setTitle("选择难度") .setItems(levelName, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { level = which; gameLevel.setText("游戏难度:" + levelName[which]); } }).create(); } @Override public void initData() { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_game: Bundle bundleNew = new Bundle(); bundleNew.putString("game", "new"); bundleNew.putInt("level", level); ActivityController.skipActivity(MainActivity.this, GameActivity.class, bundleNew); break; case R.id.continue_game: Bundle bundleContinue = new Bundle(); bundleContinue.putString("game", "continue"); ActivityController.skipActivity(MainActivity.this, GameActivity.class, bundleContinue); break; case R.id.level_game: levelSelector.show(); break; case R.id.logout: AppUtil.saveId(""); AppUtil.ToastShort("您已退出登录"); break; case R.id.login: if (AppUtil.readId().length() == 13) AppUtil.ToastShort("您已登录"); else ActivityController.skipActivity(MainActivity.this, LoginActivity.class); break; case R.id.btn_rank: if (AppUtil.readId() == "") { AppUtil.ToastShort("您还未登录。"); } else { ActivityController.skipActivity(MainActivity.this, RankActivity.class); } break; } } }
LukeLT255/aima-python
grading/kMeansSubmissions.py
import importlib import traceback from grading.util import roster, print_table import os from sklearn.cluster import KMeans from sklearn import metrics from numpy import unique # import matplotlib.pyplot as plt # from mpl_toolkits.mplot3d import Axes3D # # def plot(title, X3D): # fig = plt.figure(title) # ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) # pass def indent(howMuch = 1): space = ' ' for i in range(1, howMuch): space += ' ' return space def tryOne(label, kDict): data = kDict['data'] kValues = kDict['k'] if 'main' in kDict: main = kDict['main'] try: main() except: traceback.print_exc() for nc in kValues: print('%s[%d]:' % (label, nc)) kmeans = KMeans(n_clusters=nc) try: kmeans.fit(data) except: traceback.print_exc() continue print(kmeans.cluster_centers_) labels = kmeans.labels_ # https://sklearn.org/modules/clustering.html#silhouette-coefficient sscore = metrics.silhouette_score(data, labels) print('Silhouette Coefficient: %f' % sscore) # https://sklearn.org/modules/clustering.html#calinski-harabaz-index chindex = metrics.calinski_harabaz_score(data, labels) print('Calinski-Harabaz Index: %f' % chindex) # print(kmeans.get_params()) # score = metrics.adjusted_rand_score(frame.target, fit.labels_) # print('Adjusted Rand index: ', score) def tryExamples(examples): for label in examples: example = examples[label] tryOne(label, example) submissions = {} scores = {} message1 = 'Submissions that compile:' root = os.getcwd() for student in roster: try: directory = root + '/../submissions/' + student os.chdir(directory) except: print('missing directory: ' + directory) continue try: # http://stackoverflow.com/a/17136796/2619926 mod = importlib.import_module('submissions.' + student + '.myKMeans') submissions[student] = mod.Examples message1 += ' ' + student except ImportError: pass except: traceback.print_exc() os.chdir(root) print(message1) print('----------------------------------------') for student in roster: if not student in submissions.keys(): continue scores[student] = [] try: examples = submissions[student] print('K Means Samples from:', student) tryExamples(examples) except: traceback.print_exc() print(student + ' scores ' + str(scores[student]) + ' = ' + str(sum(scores[student]))) print('----------------------------------------')
bmhan12/axom
src/axom/sidre/tests/spio/spio_serial.hpp
<reponame>bmhan12/axom // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "gtest/gtest.h" #include "axom/config.hpp" // for AXOM_USE_HDF5 #include "axom/core/Types.hpp" // for common::int64 #include "axom/sidre/core/sidre.hpp" #include "axom/sidre/spio/IOManager.hpp" #include <list> #include "mpi.h" using axom::sidre::DataStore; using axom::sidre::Group; using axom::sidre::IOManager; using axom::int64; //------------------------------------------------------------------------------ TEST(spio_serial, basic_writeread) { DataStore* ds1 = new DataStore(); Group* root1 = ds1->getRoot(); Group* flds1 = root1->createGroup("fields"); Group* flds2 = root1->createGroup("fields2"); Group* ga = flds1->createGroup("a"); Group* gb = flds2->createGroup("b"); // Note: use 64-bit integers since that is the native type for json ga->createViewScalar<int64>("i0", 101); gb->createViewScalar<int64>("i1", 404); int num_files = 1; IOManager writer(MPI_COMM_WORLD); const std::string file_name = "out_spio_basic_write_read"; writer.write(root1, num_files, file_name, PROTOCOL); DataStore* ds2 = new DataStore(); IOManager reader(MPI_COMM_WORLD); reader.read(ds2->getRoot(), file_name + ROOT_EXT); EXPECT_TRUE(ds2->getRoot()->isEquivalentTo(root1)); int64 testvalue1 = ds1->getRoot()->getGroup("fields")->getGroup("a")->getView("i0")->getData(); int64 testvalue2 = ds2->getRoot()->getGroup("fields")->getGroup("a")->getView("i0")->getData(); EXPECT_EQ(testvalue1, testvalue2); testvalue1 = ds1->getRoot()->getGroup("fields2")->getGroup("b")->getView("i1")->getData(); testvalue2 = ds2->getRoot()->getGroup("fields2")->getGroup("b")->getView("i1")->getData(); EXPECT_EQ(testvalue1, testvalue2); delete ds1; delete ds2; } //------------------------------------------------------------------------------ TEST(spio_serial, basic_writeread_protocols) { std::list<std::string> protocols; #ifdef AXOM_USE_HDF5 protocols.push_back("conduit_hdf5"); #endif protocols.push_back("conduit_bin"); protocols.push_back("conduit_json"); protocols.push_back("json"); protocols.push_back("sidre_conduit_json"); protocols.push_back("sidre_json"); for(std::list<std::string>::const_iterator itr = protocols.begin(); itr != protocols.end(); ++itr) { const std::string& protocol = *itr; DataStore* ds1 = new DataStore(); Group* root1 = ds1->getRoot(); Group* flds1 = root1->createGroup("fields"); Group* flds2 = root1->createGroup("fields2"); Group* ga = flds1->createGroup("a"); Group* gb = flds2->createGroup("b"); // Note: use 64-bit integers since that is the native type for json ga->createViewScalar<int64>("i0", 101); gb->createViewScalar<int64>("i1", 404); int num_files = 1; IOManager writer(MPI_COMM_WORLD); const std::string file_name = "out_spio_basic_write_read" + protocol; writer.write(root1, num_files, file_name, protocol); DataStore* ds2 = new DataStore(); IOManager reader(MPI_COMM_WORLD); reader.read(ds2->getRoot(), file_name + ROOT_EXT); EXPECT_TRUE(ds2->getRoot()->isEquivalentTo(root1)); int64 testvalue1 = ds1->getRoot()->getGroup("fields")->getGroup("a")->getView("i0")->getData(); int64 testvalue2 = ds2->getRoot()->getGroup("fields")->getGroup("a")->getView("i0")->getData(); EXPECT_EQ(testvalue1, testvalue2); testvalue1 = ds1->getRoot()->getGroup("fields2")->getGroup("b")->getView("i1")->getData(); testvalue2 = ds2->getRoot()->getGroup("fields2")->getGroup("b")->getView("i1")->getData(); EXPECT_EQ(testvalue1, testvalue2); delete ds1; delete ds2; } } //------------------------------------------------------------------------------ TEST(spio_serial, write_read_write) { int my_rank, num_ranks; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int num_files = std::max(num_ranks / 2, 1); std::stringstream sstr; sstr << "out_spio_WRW_" << num_ranks; std::string filename = sstr.str(); // Initialize a datastore and dump to disk DataStore* ds = new DataStore(); ds->getRoot()->createViewScalar("grp/i", 2); ds->getRoot()->createViewScalar("grp/f", 3.0); IOManager writer_a(MPI_COMM_WORLD); writer_a.write(ds->getRoot(), num_files, filename, PROTOCOL); // Create another DataStore to read into. DataStore ds_r; IOManager reader(MPI_COMM_WORLD); reader.read(ds_r.getRoot(), filename + ROOT_EXT); // Dump this datastore to disk. // Regression for sidre_hdf5 protocol: // This used to produce the following HDF5 error: // HDF5-DIAG: Error detected in HDF5 (1.8.16) thread 0: // #000: H5F.c line 522 in H5Fcreate(): unable to create file // major: File accessibility // minor: Unable to open file // #001: H5Fint.c line 1024 in H5F_open(): unable to truncate a file which // is already open // major: File accessibility // minor: Unable to open file IOManager writer_b(MPI_COMM_WORLD); writer_b.write(ds_r.getRoot(), num_files, filename, PROTOCOL); }
henryco/blinck-server
src/main/java/net/henryco/blinckserver/mvc/model/dao/relation/core/imp/SubPartyQueueDaoImp.java
package net.henryco.blinckserver.mvc.model.dao.relation.core.imp; import net.henryco.blinckserver.mvc.model.dao.relation.core.SubPartyQueueDao; import net.henryco.blinckserver.mvc.model.entity.relation.core.SubPartyQueue; import net.henryco.blinckserver.mvc.model.repository.relation.core.SubPartyQueueRepository; import net.henryco.blinckserver.util.dao.repo.BlinckRepositoryProvider; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Henry on 15/09/17. */ @Repository @Transactional public class SubPartyQueueDaoImp extends BlinckRepositoryProvider<SubPartyQueue, Long> implements SubPartyQueueDao { public SubPartyQueueDaoImp(SubPartyQueueRepository repository) { super(repository); } private SubPartyQueueRepository getRepository() { return provideRepository(); } @Override @Transactional public void deleteAllByOwnerId(Long id) { getRepository().removeAllByOwner(id); } @Override @Transactional public List<SubPartyQueue> getAllWithUser(Long user) { return getRepository().getAllByUsersIsContainingOrOwner(user, user); } }
sknjpn/SyLife
GUIIcon.h
<reponame>sknjpn/SyLife #pragma once #include "EasyViewer.h" class GUIIcon : public EasyViewer { Color m_color; uint32 m_code; Texture m_texture; double m_scale; public: GUIIcon(uint32 code, double scale = 0.75, Color color = Palette::Black) : m_color(color) , m_scale(scale) , m_code(code) { } // Get Color getColor() const { return m_color; } // Set void setColor(const Color& color) { m_color = color; } void setScale(double scale) { m_scale = scale; } void setIcon(uint32 code) { m_code = code; m_texture = Texture { Icon { m_code }, int(m_scale * Min(getViewerSize().x, getViewerSize().y)) }; } void init() override { setIcon(m_code); setIsPenetrated(true); } void update() override { // Icon描画 m_texture.drawAt(getViewerSize() / 2.0, m_color); } };
wwww520240/framework-java
code/anguo-core/src/main/java/com/anguo/web/controller/FileUploadController.java
<gh_stars>1-10 package com.anguo.web.controller; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.anguo.util.AnguoFileUtils; /** * 上传文件 * @author Andrew.Wen * */ @Controller @RequestMapping(value = "/toFileUpload") public class FileUploadController { private Logger logger = LoggerFactory.getLogger(FileUploadController.class); /** * 文件批量上传 */ @RequestMapping(value={"/{projectPath}/toMultiUpload.htm"}) @ResponseBody public void FileUploadify(@PathVariable("projectPath") String projectPath,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientName =""; String serverName =""; /** * 返回json字符串 */ String returnJson="["; // 设置接收的编码格式 request.setCharacterEncoding("UTF-8"); //设置文件保存路径 String path = request.getSession().getServletContext().getRealPath("")+File.separator+"resources/images/"; //判断项目路径,如果不存在则新建 if(!StringUtils.isEmpty(projectPath)) { path=path+projectPath+"/"; File pathFile=new File(path); if(!pathFile.exists()) { pathFile.mkdirs(); } } try { if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); //System.out.println("==========================================="); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile multiparfile = entity.getValue(); //String fileName = mf.getOriginalFilename(); clientName = multiparfile.getOriginalFilename(); // 获得文件: if (!clientName.equals("")) { serverName = AnguoFileUtils.getRandomFileName() + "."+AnguoFileUtils.getFileExt(clientName); AnguoFileUtils.SaveFileFromInputStream(multiparfile.getInputStream(),serverName, path); } returnJson+="{\"client\":\"" + clientName + "\",\"server\":\""+ projectPath+"/"+serverName + "\"},"; //System.out.println(fileName); } //System.out.println("==========================================="); //List<MultipartFile> files = multipartRequest.getFiles("file"); //遍历文件 // for(MultipartFile multiparfile:files) // { // // // // // } if(returnJson.length()>1)returnJson=returnJson.substring(0, returnJson.length()-1); returnJson+="]"; } } catch (Exception e) { logger.error("上传文件失败,因为:" + e.getMessage()); e.printStackTrace(); } //response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=gb2312"); response.setCharacterEncoding("gb2312"); response.getWriter().write(returnJson); } }
terrameijar/bluebottle
bluebottle/funding_vitepay/views.py
<gh_stars>1-10 import logging from rest_framework_json_api.views import AutoPrefetchMixin from bluebottle.funding.exception import PaymentException from django.http import HttpResponse from django.views.generic.base import View from bluebottle.funding.views import PaymentList from bluebottle.funding_vitepay.models import VitepayPayment, VitepayBankAccount from bluebottle.funding_vitepay.serializers import VitepayPaymentSerializer, VitepayBankAccountSerializer from bluebottle.funding_vitepay.utils import update_payment_status from bluebottle.utils.permissions import IsOwner from bluebottle.utils.views import JsonApiViewMixin, ListCreateAPIView, RetrieveUpdateAPIView logger = logging.getLogger(__name__) class VitepayPaymentList(PaymentList): queryset = VitepayPayment.objects.all() serializer_class = VitepayPaymentSerializer class VitepayWebhookView(View): def post(self, request, *args, **kwargs): success = 'success' in request.POST failure = 'failure' in request.POST authenticity = request.POST.get('authenticity') unique_id = request.POST.get('order_id') try: payment = VitepayPayment.objects.get(unique_id=unique_id) except VitepayPayment.DoesNotExist: return HttpResponse('{"status": "0", "message": "Order not found."}') try: update_payment_status(payment, authenticity, success, failure) return HttpResponse('{"status": "1"}') except PaymentException as e: return HttpResponse('{"status": "0", "message": "%s"}' % e) class VitepayBankAccountAccountList(JsonApiViewMixin, AutoPrefetchMixin, ListCreateAPIView): queryset = VitepayBankAccount.objects.all() serializer_class = VitepayBankAccountSerializer permission_classes = [] related_permission_classes = { 'connect_account': [IsOwner] } class VitepayBankAccountAccountDetail(JsonApiViewMixin, AutoPrefetchMixin, RetrieveUpdateAPIView): queryset = VitepayBankAccount.objects.all() serializer_class = VitepayBankAccountSerializer permission_classes = [] related_permission_classes = { 'connect_account': [IsOwner] }
nicolasessisbreton/pyzehe
b_basic/syntax_list.py
# creating a list x = [1, 3] print('creation', x) # adding element x.append(4) x += [5] x.insert(1, 2) # insert(position, element) print('adding element', x) # picking element print('picking', x[0], x[1]) print('picking a lot', x[:3], x[1:], x[2:5], x[-3:-1]) # copying over all element from another list x = [1, 2] y = [3, 4] x.extend(y) z = [1,2] z.append(y) print('copying over for x', x) print('copying over for z', z) # iterating through all element x = [1, 2, 3, 4] for i in x: print('iteration says', i) # list comprehension x = [1, 2, 3] y = [i+1 for i in x] print('list comprehension says', y) # modifying element x = [1, 2, 3] for i in range(len(x)): x[i] *= 2 print('modifying says', x)
f-dangel/hbp
exp/exp09_cifar10_deepobs_3c3d_cvp.py
<filename>exp/exp09_cifar10_deepobs_3c3d_cvp.py """Training of c3d3 with sigmoids on CIFAR-10 with CGNewton.""" from os import path import torch from torch.nn import CrossEntropyLoss, ReLU, Sigmoid, Tanh from bpexts.cvp.sequential import convert_torch_to_cvp from bpexts.optim.cg_newton import CGNewton from exp.loading.load_cifar10 import CIFAR10Loader from exp.models.convolution import deepobs_cifar10_c3d3 from exp.training.second_order import CVPSecondOrderTraining from exp.utils import ( directory_in_data, dirname_from_params, merge_runs_return_files, run_training, ) # directories dirname = "exp09_c3d3_optimization/cvp" data_dir = directory_in_data(dirname) # global hyperparameters epochs = 20 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") logs_per_epoch = 4 test_batch = 100 # mapping from strings to activation functions activation_dict = {"relu": ReLU, "sigmoid": Sigmoid, "tanh": Tanh} def cifar10_cgnewton_train_fn( batch, modify_2nd_order_terms, activation, lr, alpha, cg_maxiter, cg_tol, cg_atol ): """Create training instance for CIFAR10 CG experiment. Parameters: ----------- batch : int Batch size modify_2nd_order_terms : str Strategy for treating 2nd-order effects of module functions: * `'zero'`: Yields the Generalizes Gauss Newton matrix * `'abs'`: BDA-PCH approximation * `'clip'`: Different BDA-PCH approximation activation : str, 'relu' or 'sigmoid' or 'tanh' Activation function lr : float Learning rate alpha : float, between 0 and 1 Regularization in HVP, see Chen paper for more details cg_maxiter : int Maximum number of iterations for CG cg_tol : float Relative tolerance for convergence of CG cg_atol : float Absolute tolerance for convergence of CG """ # logging directory # ----------------- # directory of run run_name = dirname_from_params( act=activation, opt="cgn", batch=batch, lr=lr, alpha=alpha, maxiter=cg_maxiter, tol=cg_tol, atol=cg_atol, mod2nd=modify_2nd_order_terms, ) logdir = path.join(data_dir, run_name) # training procedure # ------------------ def training_fn(): """Training function setting up the train instance.""" # set up training and run act = activation_dict[activation] model = deepobs_cifar10_c3d3(conv_activation=act, dense_activation=act) model = convert_torch_to_cvp(model) loss_function = convert_torch_to_cvp(CrossEntropyLoss()) data_loader = CIFAR10Loader(train_batch_size=batch, test_batch_size=test_batch) optimizer = CGNewton( model.parameters(), lr=lr, alpha=alpha, cg_atol=cg_atol, cg_tol=cg_tol, cg_maxiter=cg_maxiter, ) # initialize training train = CVPSecondOrderTraining( model, loss_function, optimizer, data_loader, logdir, epochs, modify_2nd_order_terms, logs_per_epoch=logs_per_epoch, device=device, ) return train return training_fn def cgn_grid_search(): """Define the grid search over the hyperparameters of SGD.""" # grid search: [100, 200, 500] batch_sizes = [500] # grid search: ['zero', 'abs', 'clip'] mod2nds = ["zero", "abs", "clip"] activations = ["sigmoid"] # grid search: [0.05, 0.1, 0.2,] lrs = [0.05, 0.1, 0.1] # grid search: [0.0001, 0.001, 0.01, 0.1] alphas = [0.001, 0.001, 0.01] cg_atol = 0.0 cg_maxiter = 200 cg_tols = [1e-1] return [ cifar10_cgnewton_train_fn( batch=batch, modify_2nd_order_terms=mod2nd, activation=activation, lr=lr, alpha=alpha, cg_maxiter=cg_maxiter, cg_tol=cg_tol, cg_atol=cg_atol, ) for cg_tol in cg_tols for activation in activations for batch in batch_sizes for mod2nd, lr, alpha in zip(mod2nds, lrs, alphas) ] SEEDS = list(range(10)) def main(): labels = [ r"GGN", r"PCH-abs", r"PCH-clip", ] experiments = cgn_grid_search() run_training(labels, experiments, SEEDS) return merge_runs_return_files(labels, experiments, SEEDS) def filenames(): return main() if __name__ == "__main__": main()
WellingtonSouzaAbreu/PataAmiga
Application/src/components/AnimalCard/styles.js
<filename>Application/src/components/AnimalCard/styles.js import { StyleSheet} from 'react-native' const styles = StyleSheet.create({ dogCard: { width: '98%', backgroundColor: '#ffffff', borderRadius: 2, justifyContent: 'center', alignItems: 'center', alignSelf: 'center', height: 130, paddingHorizontal: 5, marginVertical: 10, shadowColor: "#000", shadowOffset: { width: 0, height: 3, }, shadowOpacity: 0.29, shadowRadius: 4.65, elevation: 5, }, dogInfo: { flex: 1, width: '100%', flexDirection: 'row', alignItems: 'center', }, imageContainer: { flex: 1, }, dogImage: { width: '100%', height: '96%', resizeMode: 'cover' }, infoDogContainer: { height: '100%', width: '50%', flexDirection: 'column', justifyContent: 'space-between', padding: 10, }, previewInfos: { width: '100%', height: '70%', flexDirection: 'column', justifyContent: 'space-around', }, txtPreviewInfo: { color: '#68788C' }, groupInfoIcon: { flexDirection: 'row', alignItems: 'center', marginBottom: 2 }, buttonDetail: { width : '100%', height: 30, borderRadius: 2, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F28749', } }) export default styles
CodeLikeCXK/AngieEngine
Source/Engine/World/Private/Resource/Animation.cpp
/* Angie Engine Source Code MIT License Copyright (C) 2017-2021 <NAME>. This file is part of the Angie Engine Source Code. 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. */ #include <World/Public/Resource/Animation.h> #include <World/Public/Resource/Skeleton.h> #include <World/Public/Resource/IndexedMesh.h> #include <World/Public/Resource/Asset.h> #include <Core/Public/Logger.h> AN_CLASS_META( ASkeletalAnimation ) ASkeletalAnimation::ASkeletalAnimation() { } ASkeletalAnimation::~ASkeletalAnimation() { } void ASkeletalAnimation::Purge() { Channels.Clear(); Transforms.Clear(); Bounds.Clear(); MinNodeIndex = 0; MaxNodeIndex = 0; ChannelsMap.Clear(); FrameCount = 0; FrameDelta = 0; FrameRate = 0; DurationInSeconds = 0; DurationNormalizer = 1.0f; } void ASkeletalAnimation::Initialize( int _FrameCount, float _FrameDelta, STransform const * _Transforms, int _TransformsCount, SAnimationChannel const * _AnimatedJoints, int _NumAnimatedJoints, BvAxisAlignedBox const * _Bounds ) { AN_ASSERT( _TransformsCount == _FrameCount * _NumAnimatedJoints ); Channels.ResizeInvalidate( _NumAnimatedJoints ); Core::Memcpy( Channels.ToPtr(), _AnimatedJoints, sizeof( Channels[0] ) * _NumAnimatedJoints ); Transforms.ResizeInvalidate( _TransformsCount ); Core::Memcpy( Transforms.ToPtr(), _Transforms, sizeof( Transforms[0] ) * _TransformsCount ); Bounds.ResizeInvalidate( _FrameCount ); Core::Memcpy( Bounds.ToPtr(), _Bounds, sizeof( Bounds[0] ) * _FrameCount ); if ( !Channels.IsEmpty() ) { MinNodeIndex = Math::MaxValue< int32_t >(); MaxNodeIndex = 0; for ( int i = 0; i < Channels.Size(); i++ ) { MinNodeIndex = Math::Min( MinNodeIndex, Channels[ i ].JointIndex ); MaxNodeIndex = Math::Max( MaxNodeIndex, Channels[ i ].JointIndex ); } int mapSize = MaxNodeIndex - MinNodeIndex + 1; ChannelsMap.ResizeInvalidate( mapSize ); for ( int i = 0; i < mapSize; i++ ) { ChannelsMap[ i ] = ( unsigned short )-1; } for ( int i = 0; i < Channels.Size(); i++ ) { ChannelsMap[ Channels[ i ].JointIndex - MinNodeIndex ] = i; } } else { MinNodeIndex = 0; MaxNodeIndex = 0; ChannelsMap.Clear(); } FrameCount = _FrameCount; FrameDelta = _FrameDelta; FrameRate = 1.0f / _FrameDelta; DurationInSeconds = ( FrameCount - 1 ) * FrameDelta; DurationNormalizer = 1.0f / DurationInSeconds; bIsAnimationValid = _FrameCount > 0 && !Channels.IsEmpty(); } void ASkeletalAnimation::LoadInternalResource( const char * _Path ) { Purge(); } bool ASkeletalAnimation::LoadResource( IBinaryStream & Stream ) { AString guid; TPodVector< SAnimationChannel > channels; TPodVector< STransform > transforms; TPodVector< BvAxisAlignedBox > bounds; uint32_t fileFormat = Stream.ReadUInt32(); if ( fileFormat != FMT_FILE_TYPE_ANIMATION ) { GLogger.Printf( "Expected file format %d\n", FMT_FILE_TYPE_ANIMATION ); return false; } uint32_t fileVersion = Stream.ReadUInt32(); if ( fileVersion != FMT_VERSION_ANIMATION ) { GLogger.Printf( "Expected file version %d\n", FMT_VERSION_ANIMATION ); return false; } Stream.ReadObject( guid ); float frameDelta = Stream.ReadFloat(); uint32_t frameCount = Stream.ReadUInt32(); Stream.ReadArrayOfStructs( channels ); Stream.ReadArrayOfStructs( transforms ); Stream.ReadArrayOfStructs( bounds ); Initialize( frameCount, frameDelta, transforms.ToPtr(), transforms.Size(), channels.ToPtr(), channels.Size(), bounds.ToPtr() ); return true; }
gcxtx/zappy
src/com/sittinglittleduck/DirBuster/gui/JTableTree/TreeTableExample0.java
/* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.sittinglittleduck.DirBuster.gui.JTableTree; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JScrollPane; /** * A TreeTable example, showing a JTreeTable, operating on the local file * system. * * @version %I% %G% * * @author <NAME> */ public class TreeTableExample0 { public static void main(String[] args) { new TreeTableExample0(); } public TreeTableExample0() { JFrame frame = new JFrame("TreeTable"); JTreeTable treeTable = new JTreeTable(new FileSystemModel()); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); frame.getContentPane().add(new JScrollPane(treeTable)); frame.pack(); frame.show(); } }
nayanrajani/PYTHON
Introduction/PythonBooleans.py
# Booleans represent one of two values: True or False. # Boolean Values # In programming you often need to know if an expression is True or False. # You can evaluate any expression in Python, and get one of two answers, True or False. # When you compare two values, the expression is evaluated and Python returns the Boolean answer: print(10>9) print(10==9) print(10<9) # When you run a condition in an if statement, Python returns True or False: # Print a message based on whether the condition is True or False: a = 500 b = 250 if b>a: print("b is greater than a") else: print("b is not greater than a") # Evaluate Values and Variables # The bool() function allows you to evaluate any value, and give you True or False in return, print(bool("hello")) print(bool(15)) x = "Hello" y = 15 print(bool(x)) print(bool(y)) # Most Values are True # Almost any value is evaluated to True if it has some sort of content. # Any string is True, except empty strings. # Any number is True, except 0. # Any list, tuple, set, and dictionary are True, except empty ones. # Example # The following will return True: print(bool("abc")) print(bool(123)) print(bool(["apple", "cherry", "banana"])) # Some Values are False # In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False. # Example # The following will return False: print(bool(False)) print(bool(None)) print(bool(0)) print(bool("")) print(bool(())) print(bool([])) print(bool({})) # One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False: class myclass(): def __len__(self): return 0 myobj = myclass() print(bool(myobj)) # Functions can Return a Boolean # You can create functions that returns a Boolean Value: def myFunction() : return True print(myFunction()) # You can execute code based on the Boolean answer of a function: # Print "YES!" if the function returns True, otherwise print "NO!": def myFunction() : return False if myFunction(): print("YES!") else: print("NO!") # Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type: # Example # Check if an object is an integer or not: x = 200 print(isinstance(x,str))
Solotov/deoptfuscator
android/art/benchmark/const-class/src/ConstClassBenchmark.java
<gh_stars>100-1000 /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ConstClassBenchmark { // Define 1025 classes with consecutive type indexes in the dex file. // The tests below rely on the knowledge that ART uses the low 10 bits // of the type index as the hash into DexCache types array. // Note: n == n + 1024 (mod 2^10), n + 1 != n + 1023 (mod 2^10). public static class TestClass_0000 {} public static class TestClass_0001 {} public static class TestClass_0002 {} public static class TestClass_0003 {} public static class TestClass_0004 {} public static class TestClass_0005 {} public static class TestClass_0006 {} public static class TestClass_0007 {} public static class TestClass_0008 {} public static class TestClass_0009 {} public static class TestClass_0010 {} public static class TestClass_0011 {} public static class TestClass_0012 {} public static class TestClass_0013 {} public static class TestClass_0014 {} public static class TestClass_0015 {} public static class TestClass_0016 {} public static class TestClass_0017 {} public static class TestClass_0018 {} public static class TestClass_0019 {} public static class TestClass_0020 {} public static class TestClass_0021 {} public static class TestClass_0022 {} public static class TestClass_0023 {} public static class TestClass_0024 {} public static class TestClass_0025 {} public static class TestClass_0026 {} public static class TestClass_0027 {} public static class TestClass_0028 {} public static class TestClass_0029 {} public static class TestClass_0030 {} public static class TestClass_0031 {} public static class TestClass_0032 {} public static class TestClass_0033 {} public static class TestClass_0034 {} public static class TestClass_0035 {} public static class TestClass_0036 {} public static class TestClass_0037 {} public static class TestClass_0038 {} public static class TestClass_0039 {} public static class TestClass_0040 {} public static class TestClass_0041 {} public static class TestClass_0042 {} public static class TestClass_0043 {} public static class TestClass_0044 {} public static class TestClass_0045 {} public static class TestClass_0046 {} public static class TestClass_0047 {} public static class TestClass_0048 {} public static class TestClass_0049 {} public static class TestClass_0050 {} public static class TestClass_0051 {} public static class TestClass_0052 {} public static class TestClass_0053 {} public static class TestClass_0054 {} public static class TestClass_0055 {} public static class TestClass_0056 {} public static class TestClass_0057 {} public static class TestClass_0058 {} public static class TestClass_0059 {} public static class TestClass_0060 {} public static class TestClass_0061 {} public static class TestClass_0062 {} public static class TestClass_0063 {} public static class TestClass_0064 {} public static class TestClass_0065 {} public static class TestClass_0066 {} public static class TestClass_0067 {} public static class TestClass_0068 {} public static class TestClass_0069 {} public static class TestClass_0070 {} public static class TestClass_0071 {} public static class TestClass_0072 {} public static class TestClass_0073 {} public static class TestClass_0074 {} public static class TestClass_0075 {} public static class TestClass_0076 {} public static class TestClass_0077 {} public static class TestClass_0078 {} public static class TestClass_0079 {} public static class TestClass_0080 {} public static class TestClass_0081 {} public static class TestClass_0082 {} public static class TestClass_0083 {} public static class TestClass_0084 {} public static class TestClass_0085 {} public static class TestClass_0086 {} public static class TestClass_0087 {} public static class TestClass_0088 {} public static class TestClass_0089 {} public static class TestClass_0090 {} public static class TestClass_0091 {} public static class TestClass_0092 {} public static class TestClass_0093 {} public static class TestClass_0094 {} public static class TestClass_0095 {} public static class TestClass_0096 {} public static class TestClass_0097 {} public static class TestClass_0098 {} public static class TestClass_0099 {} public static class TestClass_0100 {} public static class TestClass_0101 {} public static class TestClass_0102 {} public static class TestClass_0103 {} public static class TestClass_0104 {} public static class TestClass_0105 {} public static class TestClass_0106 {} public static class TestClass_0107 {} public static class TestClass_0108 {} public static class TestClass_0109 {} public static class TestClass_0110 {} public static class TestClass_0111 {} public static class TestClass_0112 {} public static class TestClass_0113 {} public static class TestClass_0114 {} public static class TestClass_0115 {} public static class TestClass_0116 {} public static class TestClass_0117 {} public static class TestClass_0118 {} public static class TestClass_0119 {} public static class TestClass_0120 {} public static class TestClass_0121 {} public static class TestClass_0122 {} public static class TestClass_0123 {} public static class TestClass_0124 {} public static class TestClass_0125 {} public static class TestClass_0126 {} public static class TestClass_0127 {} public static class TestClass_0128 {} public static class TestClass_0129 {} public static class TestClass_0130 {} public static class TestClass_0131 {} public static class TestClass_0132 {} public static class TestClass_0133 {} public static class TestClass_0134 {} public static class TestClass_0135 {} public static class TestClass_0136 {} public static class TestClass_0137 {} public static class TestClass_0138 {} public static class TestClass_0139 {} public static class TestClass_0140 {} public static class TestClass_0141 {} public static class TestClass_0142 {} public static class TestClass_0143 {} public static class TestClass_0144 {} public static class TestClass_0145 {} public static class TestClass_0146 {} public static class TestClass_0147 {} public static class TestClass_0148 {} public static class TestClass_0149 {} public static class TestClass_0150 {} public static class TestClass_0151 {} public static class TestClass_0152 {} public static class TestClass_0153 {} public static class TestClass_0154 {} public static class TestClass_0155 {} public static class TestClass_0156 {} public static class TestClass_0157 {} public static class TestClass_0158 {} public static class TestClass_0159 {} public static class TestClass_0160 {} public static class TestClass_0161 {} public static class TestClass_0162 {} public static class TestClass_0163 {} public static class TestClass_0164 {} public static class TestClass_0165 {} public static class TestClass_0166 {} public static class TestClass_0167 {} public static class TestClass_0168 {} public static class TestClass_0169 {} public static class TestClass_0170 {} public static class TestClass_0171 {} public static class TestClass_0172 {} public static class TestClass_0173 {} public static class TestClass_0174 {} public static class TestClass_0175 {} public static class TestClass_0176 {} public static class TestClass_0177 {} public static class TestClass_0178 {} public static class TestClass_0179 {} public static class TestClass_0180 {} public static class TestClass_0181 {} public static class TestClass_0182 {} public static class TestClass_0183 {} public static class TestClass_0184 {} public static class TestClass_0185 {} public static class TestClass_0186 {} public static class TestClass_0187 {} public static class TestClass_0188 {} public static class TestClass_0189 {} public static class TestClass_0190 {} public static class TestClass_0191 {} public static class TestClass_0192 {} public static class TestClass_0193 {} public static class TestClass_0194 {} public static class TestClass_0195 {} public static class TestClass_0196 {} public static class TestClass_0197 {} public static class TestClass_0198 {} public static class TestClass_0199 {} public static class TestClass_0200 {} public static class TestClass_0201 {} public static class TestClass_0202 {} public static class TestClass_0203 {} public static class TestClass_0204 {} public static class TestClass_0205 {} public static class TestClass_0206 {} public static class TestClass_0207 {} public static class TestClass_0208 {} public static class TestClass_0209 {} public static class TestClass_0210 {} public static class TestClass_0211 {} public static class TestClass_0212 {} public static class TestClass_0213 {} public static class TestClass_0214 {} public static class TestClass_0215 {} public static class TestClass_0216 {} public static class TestClass_0217 {} public static class TestClass_0218 {} public static class TestClass_0219 {} public static class TestClass_0220 {} public static class TestClass_0221 {} public static class TestClass_0222 {} public static class TestClass_0223 {} public static class TestClass_0224 {} public static class TestClass_0225 {} public static class TestClass_0226 {} public static class TestClass_0227 {} public static class TestClass_0228 {} public static class TestClass_0229 {} public static class TestClass_0230 {} public static class TestClass_0231 {} public static class TestClass_0232 {} public static class TestClass_0233 {} public static class TestClass_0234 {} public static class TestClass_0235 {} public static class TestClass_0236 {} public static class TestClass_0237 {} public static class TestClass_0238 {} public static class TestClass_0239 {} public static class TestClass_0240 {} public static class TestClass_0241 {} public static class TestClass_0242 {} public static class TestClass_0243 {} public static class TestClass_0244 {} public static class TestClass_0245 {} public static class TestClass_0246 {} public static class TestClass_0247 {} public static class TestClass_0248 {} public static class TestClass_0249 {} public static class TestClass_0250 {} public static class TestClass_0251 {} public static class TestClass_0252 {} public static class TestClass_0253 {} public static class TestClass_0254 {} public static class TestClass_0255 {} public static class TestClass_0256 {} public static class TestClass_0257 {} public static class TestClass_0258 {} public static class TestClass_0259 {} public static class TestClass_0260 {} public static class TestClass_0261 {} public static class TestClass_0262 {} public static class TestClass_0263 {} public static class TestClass_0264 {} public static class TestClass_0265 {} public static class TestClass_0266 {} public static class TestClass_0267 {} public static class TestClass_0268 {} public static class TestClass_0269 {} public static class TestClass_0270 {} public static class TestClass_0271 {} public static class TestClass_0272 {} public static class TestClass_0273 {} public static class TestClass_0274 {} public static class TestClass_0275 {} public static class TestClass_0276 {} public static class TestClass_0277 {} public static class TestClass_0278 {} public static class TestClass_0279 {} public static class TestClass_0280 {} public static class TestClass_0281 {} public static class TestClass_0282 {} public static class TestClass_0283 {} public static class TestClass_0284 {} public static class TestClass_0285 {} public static class TestClass_0286 {} public static class TestClass_0287 {} public static class TestClass_0288 {} public static class TestClass_0289 {} public static class TestClass_0290 {} public static class TestClass_0291 {} public static class TestClass_0292 {} public static class TestClass_0293 {} public static class TestClass_0294 {} public static class TestClass_0295 {} public static class TestClass_0296 {} public static class TestClass_0297 {} public static class TestClass_0298 {} public static class TestClass_0299 {} public static class TestClass_0300 {} public static class TestClass_0301 {} public static class TestClass_0302 {} public static class TestClass_0303 {} public static class TestClass_0304 {} public static class TestClass_0305 {} public static class TestClass_0306 {} public static class TestClass_0307 {} public static class TestClass_0308 {} public static class TestClass_0309 {} public static class TestClass_0310 {} public static class TestClass_0311 {} public static class TestClass_0312 {} public static class TestClass_0313 {} public static class TestClass_0314 {} public static class TestClass_0315 {} public static class TestClass_0316 {} public static class TestClass_0317 {} public static class TestClass_0318 {} public static class TestClass_0319 {} public static class TestClass_0320 {} public static class TestClass_0321 {} public static class TestClass_0322 {} public static class TestClass_0323 {} public static class TestClass_0324 {} public static class TestClass_0325 {} public static class TestClass_0326 {} public static class TestClass_0327 {} public static class TestClass_0328 {} public static class TestClass_0329 {} public static class TestClass_0330 {} public static class TestClass_0331 {} public static class TestClass_0332 {} public static class TestClass_0333 {} public static class TestClass_0334 {} public static class TestClass_0335 {} public static class TestClass_0336 {} public static class TestClass_0337 {} public static class TestClass_0338 {} public static class TestClass_0339 {} public static class TestClass_0340 {} public static class TestClass_0341 {} public static class TestClass_0342 {} public static class TestClass_0343 {} public static class TestClass_0344 {} public static class TestClass_0345 {} public static class TestClass_0346 {} public static class TestClass_0347 {} public static class TestClass_0348 {} public static class TestClass_0349 {} public static class TestClass_0350 {} public static class TestClass_0351 {} public static class TestClass_0352 {} public static class TestClass_0353 {} public static class TestClass_0354 {} public static class TestClass_0355 {} public static class TestClass_0356 {} public static class TestClass_0357 {} public static class TestClass_0358 {} public static class TestClass_0359 {} public static class TestClass_0360 {} public static class TestClass_0361 {} public static class TestClass_0362 {} public static class TestClass_0363 {} public static class TestClass_0364 {} public static class TestClass_0365 {} public static class TestClass_0366 {} public static class TestClass_0367 {} public static class TestClass_0368 {} public static class TestClass_0369 {} public static class TestClass_0370 {} public static class TestClass_0371 {} public static class TestClass_0372 {} public static class TestClass_0373 {} public static class TestClass_0374 {} public static class TestClass_0375 {} public static class TestClass_0376 {} public static class TestClass_0377 {} public static class TestClass_0378 {} public static class TestClass_0379 {} public static class TestClass_0380 {} public static class TestClass_0381 {} public static class TestClass_0382 {} public static class TestClass_0383 {} public static class TestClass_0384 {} public static class TestClass_0385 {} public static class TestClass_0386 {} public static class TestClass_0387 {} public static class TestClass_0388 {} public static class TestClass_0389 {} public static class TestClass_0390 {} public static class TestClass_0391 {} public static class TestClass_0392 {} public static class TestClass_0393 {} public static class TestClass_0394 {} public static class TestClass_0395 {} public static class TestClass_0396 {} public static class TestClass_0397 {} public static class TestClass_0398 {} public static class TestClass_0399 {} public static class TestClass_0400 {} public static class TestClass_0401 {} public static class TestClass_0402 {} public static class TestClass_0403 {} public static class TestClass_0404 {} public static class TestClass_0405 {} public static class TestClass_0406 {} public static class TestClass_0407 {} public static class TestClass_0408 {} public static class TestClass_0409 {} public static class TestClass_0410 {} public static class TestClass_0411 {} public static class TestClass_0412 {} public static class TestClass_0413 {} public static class TestClass_0414 {} public static class TestClass_0415 {} public static class TestClass_0416 {} public static class TestClass_0417 {} public static class TestClass_0418 {} public static class TestClass_0419 {} public static class TestClass_0420 {} public static class TestClass_0421 {} public static class TestClass_0422 {} public static class TestClass_0423 {} public static class TestClass_0424 {} public static class TestClass_0425 {} public static class TestClass_0426 {} public static class TestClass_0427 {} public static class TestClass_0428 {} public static class TestClass_0429 {} public static class TestClass_0430 {} public static class TestClass_0431 {} public static class TestClass_0432 {} public static class TestClass_0433 {} public static class TestClass_0434 {} public static class TestClass_0435 {} public static class TestClass_0436 {} public static class TestClass_0437 {} public static class TestClass_0438 {} public static class TestClass_0439 {} public static class TestClass_0440 {} public static class TestClass_0441 {} public static class TestClass_0442 {} public static class TestClass_0443 {} public static class TestClass_0444 {} public static class TestClass_0445 {} public static class TestClass_0446 {} public static class TestClass_0447 {} public static class TestClass_0448 {} public static class TestClass_0449 {} public static class TestClass_0450 {} public static class TestClass_0451 {} public static class TestClass_0452 {} public static class TestClass_0453 {} public static class TestClass_0454 {} public static class TestClass_0455 {} public static class TestClass_0456 {} public static class TestClass_0457 {} public static class TestClass_0458 {} public static class TestClass_0459 {} public static class TestClass_0460 {} public static class TestClass_0461 {} public static class TestClass_0462 {} public static class TestClass_0463 {} public static class TestClass_0464 {} public static class TestClass_0465 {} public static class TestClass_0466 {} public static class TestClass_0467 {} public static class TestClass_0468 {} public static class TestClass_0469 {} public static class TestClass_0470 {} public static class TestClass_0471 {} public static class TestClass_0472 {} public static class TestClass_0473 {} public static class TestClass_0474 {} public static class TestClass_0475 {} public static class TestClass_0476 {} public static class TestClass_0477 {} public static class TestClass_0478 {} public static class TestClass_0479 {} public static class TestClass_0480 {} public static class TestClass_0481 {} public static class TestClass_0482 {} public static class TestClass_0483 {} public static class TestClass_0484 {} public static class TestClass_0485 {} public static class TestClass_0486 {} public static class TestClass_0487 {} public static class TestClass_0488 {} public static class TestClass_0489 {} public static class TestClass_0490 {} public static class TestClass_0491 {} public static class TestClass_0492 {} public static class TestClass_0493 {} public static class TestClass_0494 {} public static class TestClass_0495 {} public static class TestClass_0496 {} public static class TestClass_0497 {} public static class TestClass_0498 {} public static class TestClass_0499 {} public static class TestClass_0500 {} public static class TestClass_0501 {} public static class TestClass_0502 {} public static class TestClass_0503 {} public static class TestClass_0504 {} public static class TestClass_0505 {} public static class TestClass_0506 {} public static class TestClass_0507 {} public static class TestClass_0508 {} public static class TestClass_0509 {} public static class TestClass_0510 {} public static class TestClass_0511 {} public static class TestClass_0512 {} public static class TestClass_0513 {} public static class TestClass_0514 {} public static class TestClass_0515 {} public static class TestClass_0516 {} public static class TestClass_0517 {} public static class TestClass_0518 {} public static class TestClass_0519 {} public static class TestClass_0520 {} public static class TestClass_0521 {} public static class TestClass_0522 {} public static class TestClass_0523 {} public static class TestClass_0524 {} public static class TestClass_0525 {} public static class TestClass_0526 {} public static class TestClass_0527 {} public static class TestClass_0528 {} public static class TestClass_0529 {} public static class TestClass_0530 {} public static class TestClass_0531 {} public static class TestClass_0532 {} public static class TestClass_0533 {} public static class TestClass_0534 {} public static class TestClass_0535 {} public static class TestClass_0536 {} public static class TestClass_0537 {} public static class TestClass_0538 {} public static class TestClass_0539 {} public static class TestClass_0540 {} public static class TestClass_0541 {} public static class TestClass_0542 {} public static class TestClass_0543 {} public static class TestClass_0544 {} public static class TestClass_0545 {} public static class TestClass_0546 {} public static class TestClass_0547 {} public static class TestClass_0548 {} public static class TestClass_0549 {} public static class TestClass_0550 {} public static class TestClass_0551 {} public static class TestClass_0552 {} public static class TestClass_0553 {} public static class TestClass_0554 {} public static class TestClass_0555 {} public static class TestClass_0556 {} public static class TestClass_0557 {} public static class TestClass_0558 {} public static class TestClass_0559 {} public static class TestClass_0560 {} public static class TestClass_0561 {} public static class TestClass_0562 {} public static class TestClass_0563 {} public static class TestClass_0564 {} public static class TestClass_0565 {} public static class TestClass_0566 {} public static class TestClass_0567 {} public static class TestClass_0568 {} public static class TestClass_0569 {} public static class TestClass_0570 {} public static class TestClass_0571 {} public static class TestClass_0572 {} public static class TestClass_0573 {} public static class TestClass_0574 {} public static class TestClass_0575 {} public static class TestClass_0576 {} public static class TestClass_0577 {} public static class TestClass_0578 {} public static class TestClass_0579 {} public static class TestClass_0580 {} public static class TestClass_0581 {} public static class TestClass_0582 {} public static class TestClass_0583 {} public static class TestClass_0584 {} public static class TestClass_0585 {} public static class TestClass_0586 {} public static class TestClass_0587 {} public static class TestClass_0588 {} public static class TestClass_0589 {} public static class TestClass_0590 {} public static class TestClass_0591 {} public static class TestClass_0592 {} public static class TestClass_0593 {} public static class TestClass_0594 {} public static class TestClass_0595 {} public static class TestClass_0596 {} public static class TestClass_0597 {} public static class TestClass_0598 {} public static class TestClass_0599 {} public static class TestClass_0600 {} public static class TestClass_0601 {} public static class TestClass_0602 {} public static class TestClass_0603 {} public static class TestClass_0604 {} public static class TestClass_0605 {} public static class TestClass_0606 {} public static class TestClass_0607 {} public static class TestClass_0608 {} public static class TestClass_0609 {} public static class TestClass_0610 {} public static class TestClass_0611 {} public static class TestClass_0612 {} public static class TestClass_0613 {} public static class TestClass_0614 {} public static class TestClass_0615 {} public static class TestClass_0616 {} public static class TestClass_0617 {} public static class TestClass_0618 {} public static class TestClass_0619 {} public static class TestClass_0620 {} public static class TestClass_0621 {} public static class TestClass_0622 {} public static class TestClass_0623 {} public static class TestClass_0624 {} public static class TestClass_0625 {} public static class TestClass_0626 {} public static class TestClass_0627 {} public static class TestClass_0628 {} public static class TestClass_0629 {} public static class TestClass_0630 {} public static class TestClass_0631 {} public static class TestClass_0632 {} public static class TestClass_0633 {} public static class TestClass_0634 {} public static class TestClass_0635 {} public static class TestClass_0636 {} public static class TestClass_0637 {} public static class TestClass_0638 {} public static class TestClass_0639 {} public static class TestClass_0640 {} public static class TestClass_0641 {} public static class TestClass_0642 {} public static class TestClass_0643 {} public static class TestClass_0644 {} public static class TestClass_0645 {} public static class TestClass_0646 {} public static class TestClass_0647 {} public static class TestClass_0648 {} public static class TestClass_0649 {} public static class TestClass_0650 {} public static class TestClass_0651 {} public static class TestClass_0652 {} public static class TestClass_0653 {} public static class TestClass_0654 {} public static class TestClass_0655 {} public static class TestClass_0656 {} public static class TestClass_0657 {} public static class TestClass_0658 {} public static class TestClass_0659 {} public static class TestClass_0660 {} public static class TestClass_0661 {} public static class TestClass_0662 {} public static class TestClass_0663 {} public static class TestClass_0664 {} public static class TestClass_0665 {} public static class TestClass_0666 {} public static class TestClass_0667 {} public static class TestClass_0668 {} public static class TestClass_0669 {} public static class TestClass_0670 {} public static class TestClass_0671 {} public static class TestClass_0672 {} public static class TestClass_0673 {} public static class TestClass_0674 {} public static class TestClass_0675 {} public static class TestClass_0676 {} public static class TestClass_0677 {} public static class TestClass_0678 {} public static class TestClass_0679 {} public static class TestClass_0680 {} public static class TestClass_0681 {} public static class TestClass_0682 {} public static class TestClass_0683 {} public static class TestClass_0684 {} public static class TestClass_0685 {} public static class TestClass_0686 {} public static class TestClass_0687 {} public static class TestClass_0688 {} public static class TestClass_0689 {} public static class TestClass_0690 {} public static class TestClass_0691 {} public static class TestClass_0692 {} public static class TestClass_0693 {} public static class TestClass_0694 {} public static class TestClass_0695 {} public static class TestClass_0696 {} public static class TestClass_0697 {} public static class TestClass_0698 {} public static class TestClass_0699 {} public static class TestClass_0700 {} public static class TestClass_0701 {} public static class TestClass_0702 {} public static class TestClass_0703 {} public static class TestClass_0704 {} public static class TestClass_0705 {} public static class TestClass_0706 {} public static class TestClass_0707 {} public static class TestClass_0708 {} public static class TestClass_0709 {} public static class TestClass_0710 {} public static class TestClass_0711 {} public static class TestClass_0712 {} public static class TestClass_0713 {} public static class TestClass_0714 {} public static class TestClass_0715 {} public static class TestClass_0716 {} public static class TestClass_0717 {} public static class TestClass_0718 {} public static class TestClass_0719 {} public static class TestClass_0720 {} public static class TestClass_0721 {} public static class TestClass_0722 {} public static class TestClass_0723 {} public static class TestClass_0724 {} public static class TestClass_0725 {} public static class TestClass_0726 {} public static class TestClass_0727 {} public static class TestClass_0728 {} public static class TestClass_0729 {} public static class TestClass_0730 {} public static class TestClass_0731 {} public static class TestClass_0732 {} public static class TestClass_0733 {} public static class TestClass_0734 {} public static class TestClass_0735 {} public static class TestClass_0736 {} public static class TestClass_0737 {} public static class TestClass_0738 {} public static class TestClass_0739 {} public static class TestClass_0740 {} public static class TestClass_0741 {} public static class TestClass_0742 {} public static class TestClass_0743 {} public static class TestClass_0744 {} public static class TestClass_0745 {} public static class TestClass_0746 {} public static class TestClass_0747 {} public static class TestClass_0748 {} public static class TestClass_0749 {} public static class TestClass_0750 {} public static class TestClass_0751 {} public static class TestClass_0752 {} public static class TestClass_0753 {} public static class TestClass_0754 {} public static class TestClass_0755 {} public static class TestClass_0756 {} public static class TestClass_0757 {} public static class TestClass_0758 {} public static class TestClass_0759 {} public static class TestClass_0760 {} public static class TestClass_0761 {} public static class TestClass_0762 {} public static class TestClass_0763 {} public static class TestClass_0764 {} public static class TestClass_0765 {} public static class TestClass_0766 {} public static class TestClass_0767 {} public static class TestClass_0768 {} public static class TestClass_0769 {} public static class TestClass_0770 {} public static class TestClass_0771 {} public static class TestClass_0772 {} public static class TestClass_0773 {} public static class TestClass_0774 {} public static class TestClass_0775 {} public static class TestClass_0776 {} public static class TestClass_0777 {} public static class TestClass_0778 {} public static class TestClass_0779 {} public static class TestClass_0780 {} public static class TestClass_0781 {} public static class TestClass_0782 {} public static class TestClass_0783 {} public static class TestClass_0784 {} public static class TestClass_0785 {} public static class TestClass_0786 {} public static class TestClass_0787 {} public static class TestClass_0788 {} public static class TestClass_0789 {} public static class TestClass_0790 {} public static class TestClass_0791 {} public static class TestClass_0792 {} public static class TestClass_0793 {} public static class TestClass_0794 {} public static class TestClass_0795 {} public static class TestClass_0796 {} public static class TestClass_0797 {} public static class TestClass_0798 {} public static class TestClass_0799 {} public static class TestClass_0800 {} public static class TestClass_0801 {} public static class TestClass_0802 {} public static class TestClass_0803 {} public static class TestClass_0804 {} public static class TestClass_0805 {} public static class TestClass_0806 {} public static class TestClass_0807 {} public static class TestClass_0808 {} public static class TestClass_0809 {} public static class TestClass_0810 {} public static class TestClass_0811 {} public static class TestClass_0812 {} public static class TestClass_0813 {} public static class TestClass_0814 {} public static class TestClass_0815 {} public static class TestClass_0816 {} public static class TestClass_0817 {} public static class TestClass_0818 {} public static class TestClass_0819 {} public static class TestClass_0820 {} public static class TestClass_0821 {} public static class TestClass_0822 {} public static class TestClass_0823 {} public static class TestClass_0824 {} public static class TestClass_0825 {} public static class TestClass_0826 {} public static class TestClass_0827 {} public static class TestClass_0828 {} public static class TestClass_0829 {} public static class TestClass_0830 {} public static class TestClass_0831 {} public static class TestClass_0832 {} public static class TestClass_0833 {} public static class TestClass_0834 {} public static class TestClass_0835 {} public static class TestClass_0836 {} public static class TestClass_0837 {} public static class TestClass_0838 {} public static class TestClass_0839 {} public static class TestClass_0840 {} public static class TestClass_0841 {} public static class TestClass_0842 {} public static class TestClass_0843 {} public static class TestClass_0844 {} public static class TestClass_0845 {} public static class TestClass_0846 {} public static class TestClass_0847 {} public static class TestClass_0848 {} public static class TestClass_0849 {} public static class TestClass_0850 {} public static class TestClass_0851 {} public static class TestClass_0852 {} public static class TestClass_0853 {} public static class TestClass_0854 {} public static class TestClass_0855 {} public static class TestClass_0856 {} public static class TestClass_0857 {} public static class TestClass_0858 {} public static class TestClass_0859 {} public static class TestClass_0860 {} public static class TestClass_0861 {} public static class TestClass_0862 {} public static class TestClass_0863 {} public static class TestClass_0864 {} public static class TestClass_0865 {} public static class TestClass_0866 {} public static class TestClass_0867 {} public static class TestClass_0868 {} public static class TestClass_0869 {} public static class TestClass_0870 {} public static class TestClass_0871 {} public static class TestClass_0872 {} public static class TestClass_0873 {} public static class TestClass_0874 {} public static class TestClass_0875 {} public static class TestClass_0876 {} public static class TestClass_0877 {} public static class TestClass_0878 {} public static class TestClass_0879 {} public static class TestClass_0880 {} public static class TestClass_0881 {} public static class TestClass_0882 {} public static class TestClass_0883 {} public static class TestClass_0884 {} public static class TestClass_0885 {} public static class TestClass_0886 {} public static class TestClass_0887 {} public static class TestClass_0888 {} public static class TestClass_0889 {} public static class TestClass_0890 {} public static class TestClass_0891 {} public static class TestClass_0892 {} public static class TestClass_0893 {} public static class TestClass_0894 {} public static class TestClass_0895 {} public static class TestClass_0896 {} public static class TestClass_0897 {} public static class TestClass_0898 {} public static class TestClass_0899 {} public static class TestClass_0900 {} public static class TestClass_0901 {} public static class TestClass_0902 {} public static class TestClass_0903 {} public static class TestClass_0904 {} public static class TestClass_0905 {} public static class TestClass_0906 {} public static class TestClass_0907 {} public static class TestClass_0908 {} public static class TestClass_0909 {} public static class TestClass_0910 {} public static class TestClass_0911 {} public static class TestClass_0912 {} public static class TestClass_0913 {} public static class TestClass_0914 {} public static class TestClass_0915 {} public static class TestClass_0916 {} public static class TestClass_0917 {} public static class TestClass_0918 {} public static class TestClass_0919 {} public static class TestClass_0920 {} public static class TestClass_0921 {} public static class TestClass_0922 {} public static class TestClass_0923 {} public static class TestClass_0924 {} public static class TestClass_0925 {} public static class TestClass_0926 {} public static class TestClass_0927 {} public static class TestClass_0928 {} public static class TestClass_0929 {} public static class TestClass_0930 {} public static class TestClass_0931 {} public static class TestClass_0932 {} public static class TestClass_0933 {} public static class TestClass_0934 {} public static class TestClass_0935 {} public static class TestClass_0936 {} public static class TestClass_0937 {} public static class TestClass_0938 {} public static class TestClass_0939 {} public static class TestClass_0940 {} public static class TestClass_0941 {} public static class TestClass_0942 {} public static class TestClass_0943 {} public static class TestClass_0944 {} public static class TestClass_0945 {} public static class TestClass_0946 {} public static class TestClass_0947 {} public static class TestClass_0948 {} public static class TestClass_0949 {} public static class TestClass_0950 {} public static class TestClass_0951 {} public static class TestClass_0952 {} public static class TestClass_0953 {} public static class TestClass_0954 {} public static class TestClass_0955 {} public static class TestClass_0956 {} public static class TestClass_0957 {} public static class TestClass_0958 {} public static class TestClass_0959 {} public static class TestClass_0960 {} public static class TestClass_0961 {} public static class TestClass_0962 {} public static class TestClass_0963 {} public static class TestClass_0964 {} public static class TestClass_0965 {} public static class TestClass_0966 {} public static class TestClass_0967 {} public static class TestClass_0968 {} public static class TestClass_0969 {} public static class TestClass_0970 {} public static class TestClass_0971 {} public static class TestClass_0972 {} public static class TestClass_0973 {} public static class TestClass_0974 {} public static class TestClass_0975 {} public static class TestClass_0976 {} public static class TestClass_0977 {} public static class TestClass_0978 {} public static class TestClass_0979 {} public static class TestClass_0980 {} public static class TestClass_0981 {} public static class TestClass_0982 {} public static class TestClass_0983 {} public static class TestClass_0984 {} public static class TestClass_0985 {} public static class TestClass_0986 {} public static class TestClass_0987 {} public static class TestClass_0988 {} public static class TestClass_0989 {} public static class TestClass_0990 {} public static class TestClass_0991 {} public static class TestClass_0992 {} public static class TestClass_0993 {} public static class TestClass_0994 {} public static class TestClass_0995 {} public static class TestClass_0996 {} public static class TestClass_0997 {} public static class TestClass_0998 {} public static class TestClass_0999 {} public static class TestClass_1000 {} public static class TestClass_1001 {} public static class TestClass_1002 {} public static class TestClass_1003 {} public static class TestClass_1004 {} public static class TestClass_1005 {} public static class TestClass_1006 {} public static class TestClass_1007 {} public static class TestClass_1008 {} public static class TestClass_1009 {} public static class TestClass_1010 {} public static class TestClass_1011 {} public static class TestClass_1012 {} public static class TestClass_1013 {} public static class TestClass_1014 {} public static class TestClass_1015 {} public static class TestClass_1016 {} public static class TestClass_1017 {} public static class TestClass_1018 {} public static class TestClass_1019 {} public static class TestClass_1020 {} public static class TestClass_1021 {} public static class TestClass_1022 {} public static class TestClass_1023 {} public static class TestClass_1024 {} public void timeConstClassWithConflict(int count) { Class<?> class0001 = TestClass_0001.class; for (int i = 0; i < count; ++i) { $noinline$foo(class0001); // Prevent LICM on the TestClass_xxxx.class below. $noinline$foo(TestClass_0000.class); $noinline$foo(TestClass_1024.class); } } public void timeConstClassWithoutConflict(int count) { Class<?> class0000 = TestClass_0000.class; for (int i = 0; i < count; ++i) { $noinline$foo(class0000); // Prevent LICM on the TestClass_xxxx.class below. $noinline$foo(TestClass_0001.class); $noinline$foo(TestClass_1023.class); } } static void $noinline$foo(Class<?> s) { if (doThrow) { throw new Error(); } } public static boolean doThrow = false; }
seanlefevre/openduty
apps/services/migrations/0001_initial.py
<gh_stars>100-1000 # Generated by Django 2.1.3 on 2018-11-22 11:03 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('schedules', '0001_initial'), ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='Service', fields=[ ('name', models.CharField(max_length=80, unique=True)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('retry', models.IntegerField(blank=True, null=True)), ('escalate_after', models.IntegerField(blank=True, null=True)), ('notifications_disabled', models.BooleanField(default=False)), ('send_resolve_enabled', models.BooleanField(default=False)), ('policy', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='schedules.SchedulePolicy')), ], options={ 'verbose_name': 'service', 'verbose_name_plural': 'service', }, ), migrations.CreateModel( name='ServiceSilenced', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('silenced', models.BooleanField(default=False)), ('silenced_until', models.DateTimeField()), ('service', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='services.Service')), ], ), migrations.CreateModel( name='ServiceTokens', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=80)), ('service_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='services.Service')), ('token_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.Token')), ], options={ 'verbose_name': 'service_tokens', 'verbose_name_plural': 'service_tokens', }, ), ]
Iniyethawe2/google-api-java-client-services
clients/google-api-services-remotebuildexecution/v2/1.30.1/com/google/api/services/remotebuildexecution/v2/model/BuildBazelRemoteExecutionV2ActionResult.java
<gh_stars>0 /* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.remotebuildexecution.v2.model; /** * An ActionResult represents the result of an Action being run. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Remote Build Execution API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class BuildBazelRemoteExecutionV2ActionResult extends com.google.api.client.json.GenericJson { /** * The details of the execution that originally produced this result. * The value may be {@code null}. */ @com.google.api.client.util.Key private BuildBazelRemoteExecutionV2ExecutedActionMetadata executionMetadata; /** * The exit code of the command. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer exitCode; /** * The output directories of the action. For each output directory requested in the * `output_directories` or `output_paths` field of the Action, if the corresponding directory * existed after the action completed, a single entry will be present in the output list, which * will contain the digest of a Tree message containing the directory tree, and the path equal * exactly to the corresponding Action output_directories member. * * As an example, suppose the Action had an output directory `a/b/dir` and the execution produced * the following contents in `a/b/dir`: a file named `bar` and a directory named `foo` with an * executable file named `baz`. Then, output_directory will contain (hashes shortened for * readability): * * ```json // OutputDirectory proto: { path: "a/b/dir" tree_digest: { hash: * "4a73bc9d03...", size: 55 } } // Tree proto with hash "4a73bc9d03..." and size 55: { * root: { files: [ { name: "bar", digest: { hash: * "4a73bc9d03...", size: 65534 } } ], directories: [ { * name: "foo", digest: { hash: "4cf2eda940...", size: 43 } * } ] } children : { // (Directory proto with hash "4cf2eda940..." and size 43) * files: [ { name: "baz", digest: { hash: "b2c941073e...", * size: 1294, }, is_executable: true } ] } } ``` If an output of the * same name as listed in `output_files` of the Command was found in `output_directories`, but was * not a directory, the server will return a FAILED_PRECONDITION. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<BuildBazelRemoteExecutionV2OutputDirectory> outputDirectories; /** * The output directories of the action that are symbolic links to other directories. Those may be * links to other output directories, or input directories, or even absolute paths outside of the * working directory, if the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output * directory requested in the `output_directories` field of the Action, if the directory existed * after the action completed, a single entry will be present either in this field, or in the * `output_directories` field, if the directory was not a symbolic link. * * If an output of the same name was found, but was a symbolic link to a file instead of a * directory, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputDirectorySymlinks; /** * The output files of the action that are symbolic links to other files. Those may be links to * other output files, or input files, or even absolute paths outside of the working directory, if * the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output file requested in the * `output_files` or `output_paths` field of the Action, if the corresponding file existed after * the action completed, a single entry will be present either in this field, or in the * `output_files` field, if the file was not a symbolic link. * * If an output symbolic link of the same name as listed in `output_files` of the Command was * found, but its target type was not a regular file, the server will return a * FAILED_PRECONDITION. If the action does not produce the requested output, then that output will * be omitted from the list. The server is free to arrange the output list as desired; clients * MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputFileSymlinks; /** * The output files of the action. For each output file requested in the `output_files` or * `output_paths` field of the Action, if the corresponding file existed after the action * completed, a single entry will be present either in this field, or the `output_file_symlinks` * field if the file was a symbolic link to another file (`output_symlinks` field after v2.1). * * If an output listed in `output_files` was found, but was a directory rather than a regular * file, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<BuildBazelRemoteExecutionV2OutputFile> outputFiles; /** * New in v2.1: this field will only be populated if the command `output_paths` field was used, * and not the pre v2.1 `output_files` or `output_directories` fields. The output paths of the * action that are symbolic links to other paths. Those may be links to other outputs, or inputs, * or even absolute paths outside of the working directory, if the server supports * SymlinkAbsolutePathStrategy.ALLOWED. A single entry for each output requested in `output_paths` * field of the Action, if the corresponding path existed after the action completed and was a * symbolic link. * * If the action does not produce a requested output, then that output will be omitted from the * list. The server is free to arrange the output list as desired; clients MUST NOT assume that * the output list is sorted. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputSymlinks; /** * The digest for a blob containing the standard error of the action, which can be retrieved from * the ContentAddressableStorage. * The value may be {@code null}. */ @com.google.api.client.util.Key private BuildBazelRemoteExecutionV2Digest stderrDigest; /** * The standard error buffer of the action. The server SHOULD NOT inline stderr unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String stderrRaw; /** * The digest for a blob containing the standard output of the action, which can be retrieved from * the ContentAddressableStorage. * The value may be {@code null}. */ @com.google.api.client.util.Key private BuildBazelRemoteExecutionV2Digest stdoutDigest; /** * The standard output buffer of the action. The server SHOULD NOT inline stdout unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String stdoutRaw; /** * The details of the execution that originally produced this result. * @return value or {@code null} for none */ public BuildBazelRemoteExecutionV2ExecutedActionMetadata getExecutionMetadata() { return executionMetadata; } /** * The details of the execution that originally produced this result. * @param executionMetadata executionMetadata or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setExecutionMetadata(BuildBazelRemoteExecutionV2ExecutedActionMetadata executionMetadata) { this.executionMetadata = executionMetadata; return this; } /** * The exit code of the command. * @return value or {@code null} for none */ public java.lang.Integer getExitCode() { return exitCode; } /** * The exit code of the command. * @param exitCode exitCode or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setExitCode(java.lang.Integer exitCode) { this.exitCode = exitCode; return this; } /** * The output directories of the action. For each output directory requested in the * `output_directories` or `output_paths` field of the Action, if the corresponding directory * existed after the action completed, a single entry will be present in the output list, which * will contain the digest of a Tree message containing the directory tree, and the path equal * exactly to the corresponding Action output_directories member. * * As an example, suppose the Action had an output directory `a/b/dir` and the execution produced * the following contents in `a/b/dir`: a file named `bar` and a directory named `foo` with an * executable file named `baz`. Then, output_directory will contain (hashes shortened for * readability): * * ```json // OutputDirectory proto: { path: "a/b/dir" tree_digest: { hash: * "4a73bc9d03...", size: 55 } } // Tree proto with hash "4a73bc9d03..." and size 55: { * root: { files: [ { name: "bar", digest: { hash: * "4a73bc9d03...", size: 65534 } } ], directories: [ { * name: "foo", digest: { hash: "4cf2eda940...", size: 43 } * } ] } children : { // (Directory proto with hash "4cf2eda940..." and size 43) * files: [ { name: "baz", digest: { hash: "b2c941073e...", * size: 1294, }, is_executable: true } ] } } ``` If an output of the * same name as listed in `output_files` of the Command was found in `output_directories`, but was * not a directory, the server will return a FAILED_PRECONDITION. * @return value or {@code null} for none */ public java.util.List<BuildBazelRemoteExecutionV2OutputDirectory> getOutputDirectories() { return outputDirectories; } /** * The output directories of the action. For each output directory requested in the * `output_directories` or `output_paths` field of the Action, if the corresponding directory * existed after the action completed, a single entry will be present in the output list, which * will contain the digest of a Tree message containing the directory tree, and the path equal * exactly to the corresponding Action output_directories member. * * As an example, suppose the Action had an output directory `a/b/dir` and the execution produced * the following contents in `a/b/dir`: a file named `bar` and a directory named `foo` with an * executable file named `baz`. Then, output_directory will contain (hashes shortened for * readability): * * ```json // OutputDirectory proto: { path: "a/b/dir" tree_digest: { hash: * "4a73bc9d03...", size: 55 } } // Tree proto with hash "4a73bc9d03..." and size 55: { * root: { files: [ { name: "bar", digest: { hash: * "4a73bc9d03...", size: 65534 } } ], directories: [ { * name: "foo", digest: { hash: "4cf2eda940...", size: 43 } * } ] } children : { // (Directory proto with hash "4cf2eda940..." and size 43) * files: [ { name: "baz", digest: { hash: "b2c941073e...", * size: 1294, }, is_executable: true } ] } } ``` If an output of the * same name as listed in `output_files` of the Command was found in `output_directories`, but was * not a directory, the server will return a FAILED_PRECONDITION. * @param outputDirectories outputDirectories or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setOutputDirectories(java.util.List<BuildBazelRemoteExecutionV2OutputDirectory> outputDirectories) { this.outputDirectories = outputDirectories; return this; } /** * The output directories of the action that are symbolic links to other directories. Those may be * links to other output directories, or input directories, or even absolute paths outside of the * working directory, if the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output * directory requested in the `output_directories` field of the Action, if the directory existed * after the action completed, a single entry will be present either in this field, or in the * `output_directories` field, if the directory was not a symbolic link. * * If an output of the same name was found, but was a symbolic link to a file instead of a * directory, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * @return value or {@code null} for none */ public java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> getOutputDirectorySymlinks() { return outputDirectorySymlinks; } /** * The output directories of the action that are symbolic links to other directories. Those may be * links to other output directories, or input directories, or even absolute paths outside of the * working directory, if the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output * directory requested in the `output_directories` field of the Action, if the directory existed * after the action completed, a single entry will be present either in this field, or in the * `output_directories` field, if the directory was not a symbolic link. * * If an output of the same name was found, but was a symbolic link to a file instead of a * directory, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * @param outputDirectorySymlinks outputDirectorySymlinks or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setOutputDirectorySymlinks(java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputDirectorySymlinks) { this.outputDirectorySymlinks = outputDirectorySymlinks; return this; } /** * The output files of the action that are symbolic links to other files. Those may be links to * other output files, or input files, or even absolute paths outside of the working directory, if * the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output file requested in the * `output_files` or `output_paths` field of the Action, if the corresponding file existed after * the action completed, a single entry will be present either in this field, or in the * `output_files` field, if the file was not a symbolic link. * * If an output symbolic link of the same name as listed in `output_files` of the Command was * found, but its target type was not a regular file, the server will return a * FAILED_PRECONDITION. If the action does not produce the requested output, then that output will * be omitted from the list. The server is free to arrange the output list as desired; clients * MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * @return value or {@code null} for none */ public java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> getOutputFileSymlinks() { return outputFileSymlinks; } /** * The output files of the action that are symbolic links to other files. Those may be links to * other output files, or input files, or even absolute paths outside of the working directory, if * the server supports SymlinkAbsolutePathStrategy.ALLOWED. For each output file requested in the * `output_files` or `output_paths` field of the Action, if the corresponding file existed after * the action completed, a single entry will be present either in this field, or in the * `output_files` field, if the file was not a symbolic link. * * If an output symbolic link of the same name as listed in `output_files` of the Command was * found, but its target type was not a regular file, the server will return a * FAILED_PRECONDITION. If the action does not produce the requested output, then that output will * be omitted from the list. The server is free to arrange the output list as desired; clients * MUST NOT assume that the output list is sorted. * * DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API should still populate * this field in addition to `output_symlinks`. * @param outputFileSymlinks outputFileSymlinks or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setOutputFileSymlinks(java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputFileSymlinks) { this.outputFileSymlinks = outputFileSymlinks; return this; } /** * The output files of the action. For each output file requested in the `output_files` or * `output_paths` field of the Action, if the corresponding file existed after the action * completed, a single entry will be present either in this field, or the `output_file_symlinks` * field if the file was a symbolic link to another file (`output_symlinks` field after v2.1). * * If an output listed in `output_files` was found, but was a directory rather than a regular * file, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * @return value or {@code null} for none */ public java.util.List<BuildBazelRemoteExecutionV2OutputFile> getOutputFiles() { return outputFiles; } /** * The output files of the action. For each output file requested in the `output_files` or * `output_paths` field of the Action, if the corresponding file existed after the action * completed, a single entry will be present either in this field, or the `output_file_symlinks` * field if the file was a symbolic link to another file (`output_symlinks` field after v2.1). * * If an output listed in `output_files` was found, but was a directory rather than a regular * file, the server will return a FAILED_PRECONDITION. If the action does not produce the * requested output, then that output will be omitted from the list. The server is free to arrange * the output list as desired; clients MUST NOT assume that the output list is sorted. * @param outputFiles outputFiles or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setOutputFiles(java.util.List<BuildBazelRemoteExecutionV2OutputFile> outputFiles) { this.outputFiles = outputFiles; return this; } /** * New in v2.1: this field will only be populated if the command `output_paths` field was used, * and not the pre v2.1 `output_files` or `output_directories` fields. The output paths of the * action that are symbolic links to other paths. Those may be links to other outputs, or inputs, * or even absolute paths outside of the working directory, if the server supports * SymlinkAbsolutePathStrategy.ALLOWED. A single entry for each output requested in `output_paths` * field of the Action, if the corresponding path existed after the action completed and was a * symbolic link. * * If the action does not produce a requested output, then that output will be omitted from the * list. The server is free to arrange the output list as desired; clients MUST NOT assume that * the output list is sorted. * @return value or {@code null} for none */ public java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> getOutputSymlinks() { return outputSymlinks; } /** * New in v2.1: this field will only be populated if the command `output_paths` field was used, * and not the pre v2.1 `output_files` or `output_directories` fields. The output paths of the * action that are symbolic links to other paths. Those may be links to other outputs, or inputs, * or even absolute paths outside of the working directory, if the server supports * SymlinkAbsolutePathStrategy.ALLOWED. A single entry for each output requested in `output_paths` * field of the Action, if the corresponding path existed after the action completed and was a * symbolic link. * * If the action does not produce a requested output, then that output will be omitted from the * list. The server is free to arrange the output list as desired; clients MUST NOT assume that * the output list is sorted. * @param outputSymlinks outputSymlinks or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setOutputSymlinks(java.util.List<BuildBazelRemoteExecutionV2OutputSymlink> outputSymlinks) { this.outputSymlinks = outputSymlinks; return this; } /** * The digest for a blob containing the standard error of the action, which can be retrieved from * the ContentAddressableStorage. * @return value or {@code null} for none */ public BuildBazelRemoteExecutionV2Digest getStderrDigest() { return stderrDigest; } /** * The digest for a blob containing the standard error of the action, which can be retrieved from * the ContentAddressableStorage. * @param stderrDigest stderrDigest or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setStderrDigest(BuildBazelRemoteExecutionV2Digest stderrDigest) { this.stderrDigest = stderrDigest; return this; } /** * The standard error buffer of the action. The server SHOULD NOT inline stderr unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #decodeStderrRaw() * @return value or {@code null} for none */ public java.lang.String getStderrRaw() { return stderrRaw; } /** * The standard error buffer of the action. The server SHOULD NOT inline stderr unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #getStderrRaw() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeStderrRaw() { return com.google.api.client.util.Base64.decodeBase64(stderrRaw); } /** * The standard error buffer of the action. The server SHOULD NOT inline stderr unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #encodeStderrRaw() * @param stderrRaw stderrRaw or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setStderrRaw(java.lang.String stderrRaw) { this.stderrRaw = stderrRaw; return this; } /** * The standard error buffer of the action. The server SHOULD NOT inline stderr unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #setStderrRaw() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public BuildBazelRemoteExecutionV2ActionResult encodeStderrRaw(byte[] stderrRaw) { this.stderrRaw = com.google.api.client.util.Base64.encodeBase64URLSafeString(stderrRaw); return this; } /** * The digest for a blob containing the standard output of the action, which can be retrieved from * the ContentAddressableStorage. * @return value or {@code null} for none */ public BuildBazelRemoteExecutionV2Digest getStdoutDigest() { return stdoutDigest; } /** * The digest for a blob containing the standard output of the action, which can be retrieved from * the ContentAddressableStorage. * @param stdoutDigest stdoutDigest or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setStdoutDigest(BuildBazelRemoteExecutionV2Digest stdoutDigest) { this.stdoutDigest = stdoutDigest; return this; } /** * The standard output buffer of the action. The server SHOULD NOT inline stdout unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #decodeStdoutRaw() * @return value or {@code null} for none */ public java.lang.String getStdoutRaw() { return stdoutRaw; } /** * The standard output buffer of the action. The server SHOULD NOT inline stdout unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #getStdoutRaw() * @return Base64 decoded value or {@code null} for none * * @since 1.14 */ public byte[] decodeStdoutRaw() { return com.google.api.client.util.Base64.decodeBase64(stdoutRaw); } /** * The standard output buffer of the action. The server SHOULD NOT inline stdout unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #encodeStdoutRaw() * @param stdoutRaw stdoutRaw or {@code null} for none */ public BuildBazelRemoteExecutionV2ActionResult setStdoutRaw(java.lang.String stdoutRaw) { this.stdoutRaw = stdoutRaw; return this; } /** * The standard output buffer of the action. The server SHOULD NOT inline stdout unless requested * by the client in the GetActionResultRequest message. The server MAY omit inlining, even if * requested, and MUST do so if inlining would cause the response to exceed message size limits. * @see #setStdoutRaw() * * <p> * The value is encoded Base64 or {@code null} for none. * </p> * * @since 1.14 */ public BuildBazelRemoteExecutionV2ActionResult encodeStdoutRaw(byte[] stdoutRaw) { this.stdoutRaw = com.google.api.client.util.Base64.encodeBase64URLSafeString(stdoutRaw); return this; } @Override public BuildBazelRemoteExecutionV2ActionResult set(String fieldName, Object value) { return (BuildBazelRemoteExecutionV2ActionResult) super.set(fieldName, value); } @Override public BuildBazelRemoteExecutionV2ActionResult clone() { return (BuildBazelRemoteExecutionV2ActionResult) super.clone(); } }
FeatureToggleStudy/tetra
src/main/java/se/mickelus/tetra/loot/FortuneBonusCondition.java
<filename>src/main/java/se/mickelus/tetra/loot/FortuneBonusCondition.java package se.mickelus.tetra.loot; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.LootContext; import net.minecraft.world.storage.loot.conditions.LootCondition; import se.mickelus.tetra.capabilities.Capability; import se.mickelus.tetra.capabilities.CapabilityHelper; import se.mickelus.tetra.data.DataHandler; import se.mickelus.tetra.items.ItemModular; import se.mickelus.tetra.module.ItemEffect; import java.util.Random; public class FortuneBonusCondition implements LootCondition { private float chance; private float fortuneMultiplier; private Capability requiredCapability; private int capabilityLevel = -1; @Override public boolean testCondition(Random rand, LootContext context) { int fortuneLevel = 0; EntityPlayer player = (EntityPlayer) context.getKillerPlayer(); if (player != null && requiredCapability != null) { ItemStack itemStack = CapabilityHelper.getProvidingItemStack(requiredCapability, capabilityLevel, player); if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemModular) { fortuneLevel = ((ItemModular) itemStack.getItem()).getEffectLevel(itemStack, ItemEffect.fortune); } } return rand.nextFloat() < this.chance + fortuneLevel * this.fortuneMultiplier; } public static class Serializer extends LootCondition.Serializer<FortuneBonusCondition> { public Serializer() { super(new ResourceLocation("tetra:random_chance_with_fortune"), FortuneBonusCondition.class); } public void serialize(JsonObject json, FortuneBonusCondition value, JsonSerializationContext context) { DataHandler.instance.gson.toJsonTree(value).getAsJsonObject().entrySet().forEach(entry -> json.add(entry.getKey(), entry.getValue())); } public FortuneBonusCondition deserialize(JsonObject json, JsonDeserializationContext context) { return DataHandler.instance.gson.fromJson(json, FortuneBonusCondition.class); } } }
vegetaandbulma/mars
mars-db/src/main/java/com/nagao/db/nosql/dao/PaperDao.java
package com.nagao.db.nosql.dao; import org.springframework.stereotype.Repository; import com.nagao.db.nosql.common.BaseDao; import com.nagao.db.nosql.po.Paper; @Repository public class PaperDao extends BaseDao<Paper> { public PaperDao(){ super(Paper.class); } }
lnsp/gvisor
tools/nogo/filter/main.go
// Copyright 2019 The gVisor 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. // Binary check is the nogo entrypoint. package main import ( "flag" "fmt" "io/ioutil" "log" "os" "strings" yaml "gopkg.in/yaml.v2" "gvisor.dev/gvisor/tools/nogo" ) type stringList []string func (s *stringList) String() string { return strings.Join(*s, ",") } func (s *stringList) Set(value string) error { *s = append(*s, value) return nil } var ( inputFiles stringList configFiles stringList outputFile string showConfig bool ) func init() { flag.Var(&inputFiles, "input", "findings input files") flag.StringVar(&outputFile, "output", "", "findings output file") flag.Var(&configFiles, "config", "findings configuration files") flag.BoolVar(&showConfig, "show-config", false, "dump configuration only") } func main() { flag.Parse() // Load all available findings. var findings []nogo.Finding for _, filename := range inputFiles { inputFindings, err := nogo.ExtractFindingsFromFile(filename) if err != nil { log.Fatalf("unable to extract findings from %s: %v", filename, err) } findings = append(findings, inputFindings...) } // Open and merge all configuations. config := &nogo.Config{ Global: make(nogo.AnalyzerConfig), Analyzers: make(map[nogo.AnalyzerName]nogo.AnalyzerConfig), } for _, filename := range configFiles { content, err := ioutil.ReadFile(filename) if err != nil { log.Fatalf("unable to read %s: %v", filename, err) } var newConfig nogo.Config // For current file. if err := yaml.Unmarshal(content, &newConfig); err != nil { log.Fatalf("unable to decode %s: %v", filename, err) } config.Merge(&newConfig) if showConfig { bytes, err := yaml.Marshal(&newConfig) if err != nil { log.Fatalf("error marshalling config: %v", err) } mergedBytes, err := yaml.Marshal(config) if err != nil { log.Fatalf("error marshalling config: %v", err) } fmt.Fprintf(os.Stdout, "Loaded configuration from %s:\n%s\n", filename, string(bytes)) fmt.Fprintf(os.Stdout, "Merged configuration:\n%s\n", string(mergedBytes)) } } if err := config.Compile(); err != nil { log.Fatalf("error compiling config: %v", err) } if showConfig { os.Exit(0) } // Filter the findings (and aggregate by group). filteredFindings := make([]nogo.Finding, 0, len(findings)) for _, finding := range findings { if ok := config.ShouldReport(finding); ok { filteredFindings = append(filteredFindings, finding) } } // Write the output (if required). // // If the outputFile is specified, then we exit here. Otherwise, // we continue to write to stdout and treat like a test. if outputFile != "" { if err := nogo.WriteFindingsToFile(filteredFindings, outputFile); err != nil { log.Fatalf("unable to write findings: %v", err) } return } // Treat the run as a test. if len(filteredFindings) == 0 { fmt.Fprintf(os.Stdout, "PASS\n") os.Exit(0) } for _, finding := range filteredFindings { fmt.Fprintf(os.Stdout, "%s\n", finding.String()) } os.Exit(1) }
websemantics/ionic-conference-app
src/data/user/user.reducer.js
<filename>src/data/user/user.reducer.js<gh_stars>1-10 export function userReducer(state, action) { switch (action.type) { case 'set-user-loading': return { ...state, loading: action.isLoading } case 'set-user-data': return { ...state, ...action.data } case 'set-username': return { ...state, username: action.username } case 'set-has-seen-tutorial': return { ...state, hasSeenTutorial: action.hasSeenTutorial } case 'set-dark-mode': return { ...state, darkMode: action.darkMode } case 'set-is-loggedin': return { ...state, isLoggedin: action.loggedIn } } }
jcfr/SMTK
smtk/mesh/pybind11/PybindPointConnectivity.h
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #ifndef pybind_smtk_mesh_PointConnectivity_h #define pybind_smtk_mesh_PointConnectivity_h #include <pybind11/pybind11.h> #include "smtk/mesh/core/PointConnectivity.h" namespace py = pybind11; inline PySharedPtrClass< smtk::mesh::PointConnectivity > pybind11_init_smtk_mesh_PointConnectivity(py::module &m) { PySharedPtrClass< smtk::mesh::PointConnectivity > instance(m, "PointConnectivity"); instance .def(py::init<::smtk::mesh::ResourcePtr const &, ::smtk::mesh::HandleRange const &>()) .def(py::init<::smtk::mesh::PointConnectivity const &>()) .def("__ne__", (bool (smtk::mesh::PointConnectivity::*)(::smtk::mesh::PointConnectivity const &) const) &smtk::mesh::PointConnectivity::operator!=) .def("deepcopy", (smtk::mesh::PointConnectivity & (smtk::mesh::PointConnectivity::*)(::smtk::mesh::PointConnectivity const &)) &smtk::mesh::PointConnectivity::operator=) .def("__eq__", (bool (smtk::mesh::PointConnectivity::*)(::smtk::mesh::PointConnectivity const &) const) &smtk::mesh::PointConnectivity::operator==) // .def("fetchNextCell", (bool (smtk::mesh::PointConnectivity::*)(int &, ::smtk::mesh::Handle const * &)) &smtk::mesh::PointConnectivity::fetchNextCell, py::arg("numPts"), py::arg("points")) // .def("fetchNextCell", (bool (smtk::mesh::PointConnectivity::*)(::smtk::mesh::CellType &, int &, ::smtk::mesh::Handle const * &)) &smtk::mesh::PointConnectivity::fetchNextCell, py::arg("cellType"), py::arg("numPts"), py::arg("points")) .def("initCellTraversal", &smtk::mesh::PointConnectivity::initCellTraversal) .def("is_empty", &smtk::mesh::PointConnectivity::is_empty) .def("numberOfCells", &smtk::mesh::PointConnectivity::numberOfCells) .def("size", &smtk::mesh::PointConnectivity::size) ; return instance; } #endif
TanishT/Competitive-Programming
solutions/usaco/bronze/december_2019/gymnasticsv3.java
<reponame>TanishT/Competitive-Programming<filename>solutions/usaco/bronze/december_2019/gymnasticsv3.java public class gymnasticsv3 { }
XerRagnaroek/Jikai
src/com/github/xerragnaroek/jikai/anime/db/AnimeReleaseTracker.java
package com.github.xerragnaroek.jikai.anime.db; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import org.apache.commons.collections4.iterators.ReverseListIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.xerragnaroek.jasa.Anime; import com.github.xerragnaroek.jikai.util.BoundedArrayList; /** * */ @Deprecated public class AnimeReleaseTracker { private static AnimeReleaseTracker instance; // id -> last ep unix time private Map<Integer, BoundedArrayList<Long>> releaseTimes = Collections.synchronizedMap(new TreeMap<>()); private int listMax = 3; private final Logger log = LoggerFactory.getLogger(AnimeReleaseTracker.class); private AnimeReleaseTracker() { AnimeDB.runOnDBUpdate(au -> au.getRemovedAnime().forEach(this::removeAnime)); } public static AnimeReleaseTracker getInstance() { return instance == null ? (instance = new AnimeReleaseTracker()) : instance; } /** * @return the difference in minutes. dif > 0 = releases later, dif < 0 = releases earlier */ public long addAnime(Anime a) { log.debug("Adding new anime \"{}\",{}", a.getTitleRomaji(), a.getId()); long[] wrapper = new long[] { 0 }; releaseTimes.compute(a.getId(), (id, l) -> { if (l == null) { l = new BoundedArrayList<>(listMax); log.debug("First entry!"); } long nextEpAirsAt = a.getNextEpisodesAirsAt(); if (l.contains(nextEpAirsAt)) { // already in queue, no reason to mess around return l; } long dif = 0; if (l.size() > 2) { // last release time is also the last in the list, list goes oldest -> newest so we need to iterate // backwards over it to go newest -> oldest ReverseListIterator<Long> it = l.reverseListIterator(); long lastEp = it.next(); long curEp = nextEpAirsAt; long curPeriod = LocalDateTime.ofEpochSecond(lastEp, 0, ZoneOffset.UTC).until(LocalDateTime.ofEpochSecond(curEp, 0, ZoneOffset.UTC), ChronoUnit.MINUTES); log.debug("Current release period is {} minutes", curPeriod); while (it.hasNext()) { long newer = curEp; long older = it.next(); long oldPeriod = LocalDateTime.ofEpochSecond(older, 0, ZoneOffset.UTC).until(LocalDateTime.ofEpochSecond(newer, 0, ZoneOffset.UTC), ChronoUnit.MINUTES); if ((dif = curPeriod - oldPeriod) == 0) { // not a new release period log.debug("Not a new period."); break; } } if (dif != 0) { log.debug("Current period differs by {} minutes", dif); } } wrapper[0] = dif; l.add(nextEpAirsAt); return l; }); return wrapper[0]; } public void addAllAnime(Collection<Anime> col) { col.forEach(this::addAnime); } public Map<Integer, BoundedArrayList<Long>> getMap() { TreeMap<Integer, BoundedArrayList<Long>> tmp = new TreeMap<>(); tmp.putAll(releaseTimes); return tmp; } public void loadMap(Map<Integer, BoundedArrayList<Long>> map) { Set<Integer> loadedIds = AnimeDB.getLoadedAnime().stream().map(Anime::getId).collect(Collectors.toSet()); map.keySet().retainAll(loadedIds); map.forEach((i, l) -> l.setMaxCapacity(listMax)); log.debug("Loaded {} entries", map.size()); map.forEach((i, l) -> { if (releaseTimes.containsKey(i)) { BoundedArrayList<Long> curL = releaseTimes.get(i); if (curL != null && !curL.isEmpty()) { long latest = curL.get(curL.size() - 1); if (latest != l.get(l.size() - 1)) { l.add(latest); } releaseTimes.put(i, l); } } else { releaseTimes.put(i, l); } }); } public void removeAnime(Anime a) { releaseTimes.remove(a.getId()); log.debug("Removed anime {},{}", a.getTitleRomaji(), a.getId()); } }
schibsted/sebase
util/pkg/sbalance/sbalance.go
// Copyright 2018 Schibsted // This package allows you to iterate over a set of service nodes, either in // sequence or randomly. The RNG can be seeded and will give the same node // order for the same seed. package sbalance import ( "bytes" crand "crypto/rand" "hash/fnv" "io" "math/rand" ) // What kind of strategy should be used to iterate the nodes. // Sequencial simply walks from the first downwards, ignoring cost. // Random first picks a random node based on cost, with random fallback. // Hash works like random, but seeds the RNG with the seed given, thus generating // the same sequence for the same seed. type BalanceStrat int const ( StratSeq BalanceStrat = iota StratRandom StratHash ) type nodeData struct { cost int effcost int node interface{} } // A service with a set of nodes. Initialize with the Strat you will use and // call Service.AddNode to add nodes. type Service struct { Retries int // How many times to retry the whole set of nodes. FailCost int // Overrides normal node cost on hard failures (connection refused etc.) SoftFailCost int // Overrides normal node cost on soft failures (503 Service unavailable) Strat BalanceStrat nodes []nodeData } // Add a node to the service. This function is not thread safe and can't be used // while you're connecting to the nodes. func (sb *Service) AddNode(node interface{}, cost int) { sb.nodes = append(sb.nodes, nodeData{cost, cost, node}) } // Number of nodes. func (sb *Service) Len() int { return len(sb.nodes) } // Get all the nodes. func (sb *Service) Nodes() []interface{} { ret := make([]interface{}, len(sb.nodes)) for idx := range sb.nodes { ret[idx] = sb.nodes[idx].node } return ret } // An iterator for the service nodes. Each call to Next returns a new // node you should connect to. Once a node has been used successfully, call // Close to finish. // // Next will return nil when the nodes are exhausted, based // on the number of nodes and the Service.Retries count. type Connection interface { Next(status ConnStatus) interface{} Close() error } // The reason you're calling Connection.Next. // Start for the first call or when you want to move to the next node even // when the current was used successfully. // Fail if there was a hard failure, e.g. connection refused. // SoftFail if there was a soft failure, e.g. 503 Service Unavailable. type ConnStatus int const ( Start ConnStatus = iota Fail SoftFail ) // Setup a service connection, possibly seeding the random order // generator with the given seed. func (sb *Service) NewConn(seed []byte) Connection { return stratImpl[sb.Strat](sb, seed) } // Return the default and effective (current) costs for the given node at idx. func (sb *Service) GetCosts(idx int) (cost, effcost int) { return sb.nodes[idx].cost, sb.nodes[idx].effcost } var stratImpl = [...]func(*Service, []byte) Connection{ seqInit, randInit, hashInit, } type seqConn struct { nodes []nodeData idx int retries int } func seqInit(sb *Service, seed []byte) Connection { return &seqConn{sb.nodes, -1, sb.Retries} } func (conn *seqConn) Next(status ConnStatus) interface{} { conn.idx++ for conn.idx >= len(conn.nodes) { if conn.retries <= 0 { return nil } conn.retries-- conn.idx = 0 } return conn.nodes[conn.idx].node } func (conn *seqConn) Close() error { return nil } type rcycleConn struct { sb *Service rng *rand.Rand rc []int retries int last int first int } func randInit(sb *Service, seed []byte) Connection { return rcycleInit(sb, &io.LimitedReader{crand.Reader, 8}) } func hashInit(sb *Service, seed []byte) Connection { if seed == nil { return randInit(sb, nil) } return rcycleInit(sb, bytes.NewReader(seed)) } func rcycleInit(sb *Service, r io.Reader) Connection { // Ignore errors from Copy h := fnv.New64a() io.Copy(h, r) rng := rand.New(rand.NewSource(int64(h.Sum64()))) conn := &rcycleConn{sb, rng, nil, sb.Retries, -1, 0} // Pick a first node based on cost // XXX is this algorithm proven? var totw float64 for i := range conn.sb.nodes { w := float64(1.0) / float64(conn.sb.nodes[i].effcost) totw += w if w/totw > conn.rng.Float64() { conn.first = i } } return conn } func (conn *rcycleConn) shuffle() { // Cost is ignored here, just shuffle. // XXX why is cost ignored? conn.rc = conn.rng.Perm(len(conn.sb.nodes)) } func (conn *rcycleConn) Next(status ConnStatus) interface{} { if conn.last != -1 { switch status { case Fail: conn.sb.nodes[conn.last].effcost = conn.sb.FailCost case SoftFail: conn.sb.nodes[conn.last].effcost = conn.sb.SoftFailCost } } // First node special case if conn.first != -1 { conn.last = conn.first conn.first = -1 if len(conn.sb.nodes) > conn.last { return conn.sb.nodes[conn.last].node } } for len(conn.rc) == 0 { if conn.retries <= 0 { conn.last = -1 return nil } conn.retries-- conn.shuffle() } conn.last = conn.rc[0] conn.rc = conn.rc[1:] return conn.sb.nodes[conn.last].node } func (conn *rcycleConn) Close() error { if conn.last != -1 { conn.sb.nodes[conn.last].effcost = conn.sb.nodes[conn.last].cost } return nil }
dpilawa/cilantro
tests/ControlledCamera.cpp
#include "ControlledCamera.h" #include "input/Input.h" #include "input/GLFWInputController.h" #include "system/EngineContext.h" ControlledCamera::ControlledCamera (float fov, float near, float far, float speed, float sensitivity) : PerspectiveCamera (fov, near, far), speed (speed), sensitivity (sensitivity) { } ControlledCamera::~ControlledCamera() { } void ControlledCamera::Initialize () { GLFWInputController& c = dynamic_cast<GLFWInputController&> (EngineContext::GetInputController ()); c.CreateInputAxis ("moveforward", InputKey::KeyW, {}, 1.0f); c.CreateInputAxis ("moveforward", InputKey::KeyS, {}, -1.0f); c.CreateInputAxis ("moveright", InputKey::KeyD, {}, 1.0f); c.CreateInputAxis ("moveright", InputKey::KeyA, {}, -1.0f); c.CreateInputAxis ("camerapitch", InputAxis::MouseY, 1.0f); c.CreateInputAxis ("camerayaw", InputAxis::MouseX, 1.0f); c.BindInputAxis ("moveright", [&](float a) { MoveRight (a); }); c.BindInputAxis ("moveforward", [&](float a) { MoveForward (a); }); c.BindInputAxis ("camerapitch", [&](float a) { PitchBy (a); }); c.BindInputAxis ("camerayaw", [&](float a) { YawBy (a); }); } void ControlledCamera::MoveRight (float offset) { GetLocalTransform ().TranslateBy (GetRight () * offset * speed); } void ControlledCamera::MoveForward (float offset) { GetLocalTransform ().TranslateBy (-GetForward () * offset * speed); } void ControlledCamera::YawBy (float angle) { GetLocalTransform ().RotateBy (0.0f, angle * sensitivity, 0.0f); } void ControlledCamera::PitchBy (float angle) { GetLocalTransform ().RotateBy (angle * sensitivity, 0.0f, 0.0f); }
shaoyongfeng/gardener-extension-provider-alicloud
vendor/github.com/gardener/gardener/pkg/apis/core/types_exposureclass.go
<filename>vendor/github.com/gardener/gardener/pkg/apis/core/types_exposureclass.go // Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // 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 core import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ExposureClass represents a control plane endpoint exposure strategy. type ExposureClass struct { metav1.TypeMeta // Standard object metadata. metav1.ObjectMeta // Handler is the name of the handler which applies the control plane endpoint exposure strategy. // This field is immutable. Handler string // Scheduling holds information how to select applicable Seed's for ExposureClass usage. // This field is immutable. Scheduling *ExposureClassScheduling } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ExposureClassList is a collection of ExposureClass. type ExposureClassList struct { metav1.TypeMeta // Standard list object metadata. metav1.ListMeta // Items is the list of ExposureClasses. Items []ExposureClass } // ExposureClassScheduling holds information to select applicable Seed's for ExposureClass usage. type ExposureClassScheduling struct { // SeedSelector is an optional label selector for Seed's which are suitable to use the ExposureClass. SeedSelector *SeedSelector // Tolerations contains the tolerations for taints on Seed clusters. Tolerations []Toleration }
Arzana/Plutonium
code/include/Graphics/Vulkan/Framebuffer.h
<reponame>Arzana/Plutonium<filename>code/include/Graphics/Vulkan/Framebuffer.h<gh_stars>1-10 #pragma once #include "Graphics/Vulkan/Shaders/Renderpass.h" namespace Pu { class ImageView; /* Defines a storage object for all images passed to a render pass. */ class Framebuffer { public: /* Initializes a new instance of a framebuffer. */ Framebuffer(_In_ const Renderpass &renderpass, _In_ Extent2D dimensions, _In_ const vector<const ImageView*> &attachments); /* Initializes a new instance of a framebuffer for layered rendering. */ Framebuffer(const Renderpass &renderpass, _In_ Extent2D dimensions, _In_ uint32 layers, _In_ const vector<const ImageView*> &attachments); Framebuffer(_In_ const Framebuffer&) = delete; /* Move constructor. */ Framebuffer(_In_ Framebuffer &&value); /* Destroys the image view. */ ~Framebuffer(void) { Destroy(); } _Check_return_ Framebuffer& operator =(_In_ const Framebuffer&) = delete; /* Move assignment. */ _Check_return_ Framebuffer& operator =(_In_ Framebuffer &&other); /* Gets the full render area available for this framebuffer. */ _Check_return_ inline const Rect2D& GetArea(void) const { return area; } /* Sets a debuggable name for this framebuffer. */ inline void SetDebugName(_In_ const string &name) const { parent->SetDebugName(ObjectType::Framebuffer, hndl, name); } private: friend class CommandBuffer; friend class Renderpass; friend class GameWindow; FramebufferHndl hndl; Rect2D area; LogicalDevice *parent; Framebuffer(LogicalDevice &device, RenderPassHndl renderPass, Extent2D dimensions, ImageViewHndl attachment); void Destroy(void); }; }
mimo31/fluid-sim
src/app/shape-config-widget.cpp
/** * shape-config-widget.cpp * * Author: <NAME> * Created on 2021/01/14 */ #include "shape-config-widget.hpp" #include <glibmm.h> #include <gdkmm/general.h> namespace brandy0 { ShapeConfigWidget::ShapeConfigWidget(ConfigStateAbstr *const parent, ShapeConfigWindowAbstr *const parentWindow) : parent(parent), parentWindow(parentWindow), mouseInside(false) { set_has_window(); set_hexpand(); set_vexpand(); parent->initListeners.plug([this](){ refresh(); activateRefresher(); }); parent->closeListeners.plug([this](){ deactivateRefresher(); }); parent->shapeStackChangeListeners.plug([this](){ refresh(); }); parent->dimensionsChangeListeners.plug([this](){ refresh(); }); parentWindow->nextShapeChangeListeners.plug([this](){ refresh(); }); } /// Widget's minimum width (in pixels) constexpr uint32_t MINIMUM_WIDTH = 32; /// Widget's natural width (in pixels) constexpr uint32_t NATURAL_WIDTH = 512; /// Widget's minimum height (in pixels) constexpr uint32_t MINIMUM_HEIGHT = 32; /// Widget's natural height (in pixels) constexpr uint32_t NATURAL_HEIGHT = 512; void ShapeConfigWidget::get_preferred_width_vfunc(int& minimum_width, int& natural_width) const { minimum_width = MINIMUM_WIDTH; natural_width = NATURAL_WIDTH; } void ShapeConfigWidget::get_preferred_height_vfunc(int& minimum_height, int& natural_height) const { minimum_height = MINIMUM_HEIGHT; natural_height = NATURAL_HEIGHT; } void ShapeConfigWidget::get_preferred_height_for_width_vfunc(int /* width */, int& minimum_height, int& natural_height) const { minimum_height = MINIMUM_HEIGHT; natural_height = NATURAL_HEIGHT; } void ShapeConfigWidget::get_preferred_width_for_height_vfunc(int /* height */, int& minimum_width, int& natural_width) const { minimum_width = MINIMUM_WIDTH; natural_width = NATURAL_WIDTH; } void ShapeConfigWidget::on_size_allocate(Gdk::Rectangle& allocation) { set_allocation(allocation); if (win) { win->move_resize(allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height()); } } void ShapeConfigWidget::on_realize() { set_realized(); if (!win) { GdkWindowAttr attr; memset(&attr, 0, sizeof(attr)); Gtk::Allocation alloc = get_allocation(); attr.x = alloc.get_x(); attr.y = alloc.get_y(); attr.width = alloc.get_width(); attr.height = alloc.get_height(); attr.event_mask = get_events() | Gdk::EXPOSURE_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::POINTER_MOTION_MASK | Gdk::LEAVE_NOTIFY_MASK; attr.window_type = GDK_WINDOW_CHILD; attr.wclass = GDK_INPUT_OUTPUT; win = Gdk::Window::create(get_parent_window(), &attr, GDK_WA_X | GDK_WA_Y); set_window(win); win->set_user_data(gobj()); signal_button_press_event().connect(sigc::mem_fun(*this, &ShapeConfigWidget::clickHandler), false); signal_motion_notify_event().connect(sigc::mem_fun(*this, &ShapeConfigWidget::motionHandler), false); signal_leave_notify_event().connect(sigc::mem_fun(*this, &ShapeConfigWidget::leaveHandler), false); } } void ShapeConfigWidget::on_unrealize() { win.reset(); Gtk::Widget::on_unrealize(); } uint32_t ShapeConfigWidget::getWidth() const { return get_allocation().get_width(); } uint32_t ShapeConfigWidget::getHeight() const { return get_allocation().get_height(); } void moveTo(const Cairo::RefPtr<Cairo::Context>& cr, const vec2d v) { cr->move_to(v.x, v.y); } void lineTo(const Cairo::RefPtr<Cairo::Context>& cr, const vec2d v) { cr->line_to(v.x, v.y); } void ShapeConfigWidget::markPoints(const Cairo::RefPtr<Cairo::Context>& cr, const cairo_matrix_t& baseCoors, const vec<vec2d> &ps) const { const cairo_matrix_t fullCoors = cr->get_matrix(); cairo_matrix_t baseInv = baseCoors; cairo_matrix_invert(&baseInv); cairo_matrix_t transMat; cairo_matrix_multiply(&transMat, &fullCoors, &baseInv); cr->set_matrix(baseCoors); const double rad = std::min(getWidth(), getHeight()) / 128.0; for (vec2d p : ps) { cairo_matrix_transform_point(&transMat, &p.x, &p.y); cr->move_to(p.x + rad, p.y + rad / 2); cr->line_to(p.x + rad, p.y - rad / 2); cr->line_to(p.x - rad, p.y + rad / 2); cr->line_to(p.x - rad, p.y - rad / 2); cr->close_path(); cr->fill(); } } void ShapeConfigWidget::markPoint(const Cairo::RefPtr<Cairo::Context>& cr, const cairo_matrix_t& baseCoors, const vec2d p) const { markPoints(cr, baseCoors, vec<vec2d>{ p }); } bool ShapeConfigWidget::on_draw(const Cairo::RefPtr<Cairo::Context>& cr) { // TODO: split into a few shorter methods // TODO: extract the colors into constants const uint32_t sw = getWidth(), sh = getHeight(); const double w = parent->params->w, h = parent->params->h; const uint32_t wp = parent->params->wp, hp = parent->params->hp; cr->move_to(0, 0); cr->line_to(sw, sh); cr->move_to(0, sh); cr->line_to(sw, 0); cr->stroke(); cairo_matrix_t flip; cairo_matrix_init_identity(&flip); flip.yy = -1; cr->transform(flip); cr->translate(0, -sh); cairo_matrix_t baseCoors = cr->get_matrix(); if (sw * h > sh * w) { const double fac = sh * w / (sw * h); cr->scale(fac, 1); cr->translate(sw * (1 / fac - 1) / 2, 0); } else { const double fac = sw * h / (sh * w); cr->scale(1, fac); cr->translate(0, sh * (1 / fac - 1) / 2); } cr->scale(sw, sh); Gdk::Cairo::set_source_rgba(cr, Gdk::RGBA("light green")); cr->move_to(0, 0); cr->line_to(1, 0); cr->line_to(1, 1); cr->line_to(0, 1); cr->close_path(); cr->fill(); Grid<bool> solid(wp, hp); parent->params->shapeStack.set(solid); vec<vec2d> tempShape = parentWindow->nextShapeClicks; if (mouseInside) tempShape.push_back(mouseCoors); Grid<bool> tempSolid(wp, hp); tempSolid.set_all(false); const uint32_t mode = parentWindow->addShapeMode; if (mode == AddShapeRectangle && tempShape.size() == 2) ObstacleRectangle(false, tempShape[0], tempShape[1]).fill(tempSolid); else if (mode == AddShapePolygon && tempShape.size() >= 3) ObstaclePolygon(false, tempShape).fill(tempSolid); else if (mode == AddShapeCircle && tempShape.size() == 2) ObstacleCircle(false, tempShape[0], tempShape[1], w, h).fill(tempSolid); else if (mode == AddShapeEllipse && tempShape.size() == 2) ObstacleEllipse(false, tempShape[0], tempShape[1]).fill(tempSolid); const double dx = 1 / double(wp - 1) / 2; const double dy = 1 / double(hp - 1) / 2; for (uint32_t x = 0; x < wp; x++) { for (uint32_t y = 0; y < hp; y++) { const double xc = x / double(wp - 1); const double yc = y / double(hp - 1); if (solid(x, y) || (x & 1) != (y & 1)) { if (solid(x, y)) if ((x & 1) == (y & 1)) cr->set_source_rgba(.75, .8, 1, 1); else cr->set_source_rgba(.8, .75, 1, 1); else Gdk::Cairo::set_source_rgba(cr, Gdk::RGBA("light yellow")); const double x0 = x == 0 ? xc : xc - dx; const double x1 = x == wp - 1 ? xc : xc + dx; const double y0 = y == 0 ? yc : yc - dy; const double y1 = y == hp - 1 ? yc : yc + dy; cr->move_to(x0, y0); cr->line_to(x0, y1); cr->line_to(x1, y1); cr->line_to(x1, y0); cr->close_path(); cr->fill(); } if (!solid(x, y) && tempSolid(x, y)) { if ((x & 1) == (y & 1)) cr->set_source_rgba(.75, .8, 1, 1); else cr->set_source_rgba(.8, .75, 1, 1); const double x0 = x == 0 ? xc : xc - dx / 2; const double x1 = x == wp - 1 ? xc : xc + dx / 2; const double y0 = y == 0 ? yc : yc - dy / 2; const double y1 = y == hp - 1 ? yc : yc + dy / 2; cr->move_to(x0, y0); cr->line_to(x0, y1); cr->line_to(x1, y1); cr->line_to(x1, y0); cr->close_path(); cr->fill(); } } } Gdk::Cairo::set_source_rgba(cr, Gdk::RGBA("black")); for (const sptr<ObstacleShape>& shape : parent->params->shapeStack) shape->draw(cr); cr->set_source_rgba(.5, .5, .5, .5); if (mode == AddShapeRectangle) { if (tempShape.size() == 2) { const vec2d v0 = tempShape[0], v2 = tempShape[1]; const vec2d v1(v0.x, v2.y), v3(v2.x, v0.y); moveTo(cr, v0); lineTo(cr, v1); lineTo(cr, v2); lineTo(cr, v3); cr->close_path(); cr->fill(); } else if (tempShape.size() == 1) markPoint(cr, baseCoors, tempShape[0]); } else if (mode == AddShapePolygon) { if (tempShape.size() >= 3) { const vec2d v0 = tempShape[0]; cr->move_to(v0.x, v0.y); for (const vec2d v : tempShape) cr->line_to(v.x, v.y); cr->close_path(); cr->fill(); } else { const cairo_matrix_t fullCoors = cr->get_matrix(); cairo_matrix_t baseInv = baseCoors; cairo_matrix_invert(&baseInv); cairo_matrix_t transMat; cairo_matrix_multiply(&transMat, &fullCoors, &baseInv); cr->set_matrix(baseCoors); const double rad = std::min(sw, sh) / 128.0; for (vec2d v : tempShape) { cairo_matrix_transform_point(&transMat, &v.x, &v.y); cr->move_to(v.x + rad, v.y + rad / 2); cr->line_to(v.x + rad, v.y - rad / 2); cr->line_to(v.x - rad, v.y + rad / 2); cr->line_to(v.x - rad, v.y - rad / 2); cr->close_path(); cr->fill(); } if (tempShape.size() == 2) { vec2d v0 = tempShape[0], v1 = tempShape[1]; cairo_matrix_transform_point(&transMat, &v0.x, &v0.y); cairo_matrix_transform_point(&transMat, &v1.x, &v1.y); const vec2d w = v1 - v0; if (!w.is_zero()) { const vec2d sh = w.get_unit().get_lrot() * rad / 8; moveTo(cr, v0 + sh); lineTo(cr, v1 + sh); lineTo(cr, v1 - sh); lineTo(cr, v0 - sh); cr->close_path(); cr->fill(); } } } } else if (mode == AddShapeCircle || mode == AddShapeEllipse) { if (tempShape.size() == 2) { const vec2d v0 = tempShape[0], v1 = tempShape[1]; const ObstacleEllipse ell = mode == AddShapeCircle ? ObstacleCircle(false, v0, v1, w, h) : ObstacleEllipse(false, v0, v1); ell.draw(cr); } if (!tempShape.empty()) markPoints(cr, baseCoors, tempShape); } cr->set_source_rgba(1, .9, .9, 1); cr->set_matrix(baseCoors); if (sw * h > sh * w) { const double fac = sh * w / (sw * h); cr->move_to(0, 0); cr->line_to(sw * (1 - fac) / 2, 0); cr->line_to(sw * (1 - fac) / 2, sh); cr->line_to(0, sh); cr->close_path(); cr->fill(); cr->move_to(sw, 0); cr->line_to(sw - sw * (1 - fac) / 2, 0); cr->line_to(sw - sw * (1 - fac) / 2, sh); cr->line_to(sw, sh); cr->close_path(); cr->fill(); } else { const double fac = sw * h / (sh * w); cr->move_to(0, 0); cr->line_to(0, sh * (1 - fac) / 2); cr->line_to(sw, sh * (1 - fac) / 2); cr->line_to(sw, 0); cr->close_path(); cr->fill(); cr->move_to(0, sh); cr->line_to(0, sh - sh * (1 - fac) / 2); cr->line_to(sw, sh - sh * (1 - fac) / 2); cr->line_to(sw, sh); cr->close_path(); cr->fill(); } return true; } vec2d ShapeConfigWidget::widgetToUnitCoors(const vec2d wCoors) const { const uint32_t sw = getWidth(), sh = getHeight(); const double w = parent->params->w, h = parent->params->h; double rx = wCoors.x / sw, ry = 1 - wCoors.y / sh; if (sw * h > sh * w) { const double fac = sh * w / (sw * h); rx /= fac; rx -= (1 / fac - 1) / 2; } else { const double fac = sw * h / (sh * w); ry /= fac; ry -= (1 / fac - 1) / 2; } return vec2d(rx, ry); } bool ShapeConfigWidget::clickHandler(GdkEventButton *const event) { const vec2d uc = widgetToUnitCoors(vec2d(event->x, event->y)); if (uc.inside(0, 0, 1, 1)) { const uint32_t mode = parentWindow->addShapeMode; if (mode != AddShapePolygon && parentWindow->nextShapeClicks.size() == 1) { const vec2d v0 = parentWindow->nextShapeClicks[0]; parentWindow->nextShapeClicks.clear(); if (mode == AddShapeRectangle) { const vec2d v1(v0.x, uc.y), v3(uc.x, v0.y); parent->params->shapeStack.push(make_shared<ObstaclePolygon>(false, vec<vec2d>{ v0, v1, uc, v3 })); parent->shapeStackChangeListeners.invoke(); } else if (mode == AddShapeEllipse) { parent->params->shapeStack.push(make_shared<ObstacleEllipse>(false, v0, uc)); parent->shapeStackChangeListeners.invoke(); } else if (mode == AddShapeCircle) { const vec2d v = uc - v0; const double r = sqrt(parent->params->w * v.x * parent->params->w * v.x + parent->params->h * v.y * parent->params->h * v.y); parent->params->shapeStack.push(make_shared<ObstacleEllipse>(false, v0, r / parent->params->w, r / parent->params->h)); parent->shapeStackChangeListeners.invoke(); } } else parentWindow->nextShapeClicks.push_back(uc); parentWindow->nextShapeChangeListeners.invoke(); } return true; } bool ShapeConfigWidget::motionHandler(GdkEventMotion *const event) { const vec2d uc = widgetToUnitCoors(vec2d(event->x, event->y)); mouseInside = uc.inside(0, 0, 1, 1); if (mouseInside) mouseCoors = uc; return true; } bool ShapeConfigWidget::leaveHandler(GdkEventCrossing *const /*event*/) { mouseInside = false; return true; } void ShapeConfigWidget::activateRefresher() { redrawConnection = Glib::signal_timeout().connect([this]{ refresh(); return true; }, 17); } void ShapeConfigWidget::deactivateRefresher() { redrawConnection.disconnect(); } void ShapeConfigWidget::refresh() { queue_draw(); } }
alonmm/VCSamples
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/AtomPub sample (Windows 8)/C++/Scenario4.xaml.cpp
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // // Scenario4.xaml.cpp // Implementation of the Scenario4 class // #include "pch.h" #include "Scenario4.xaml.h" using namespace SDKSample::AtomPub; using namespace Windows::UI::Xaml::Controls; using namespace Concurrency; using namespace Windows::Web; Scenario4::Scenario4() { InitializeComponent(); // Helps iterating through feeds. this->feedIterator = ref new SyndicationItemIterator(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario4::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser(). rootPage = MainPage::Current; CommonData::Restore(this); } void Scenario4::OnNavigatingFrom(NavigatingCancelEventArgs^ e) { CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password); } // Download a feed. void Scenario4::GetFeed_Click(Object^ sender, RoutedEventArgs^ e) { OutputField->Text = ""; // If we retrieve the feed via the Edit uri then we will be logged in and be // able to modify/delete the resource. // Since the value of 'ServiceAddressField' was provided by the user it is untrusted input. We'll validate it // by using TryGetUri(). // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set, since // the user may provide URIs for servers located on the intErnet or intrAnet. If apps only communicate // with servers on the intErnet, only the "Internet (Client)" capability should be set. Similarly if an // app is only intended to communicate on the intrAnet, only the "Home and Work Networking" capability should be set. Uri^ resourceUri; if (!rootPage->TryGetUri(StringHelper::Trim(ServiceAddressField->Text) + CommonData::EditUri, &resourceUri)) { return; } rootPage->NotifyUser("Fetching feed...", NotifyType::StatusMessage); OutputField->Text = "Requested feed: " + resourceUri->DisplayUri + "\r\n"; task<SyndicationFeed^>(CommonData::GetClient()->RetrieveFeedAsync(resourceUri)).then([this] (SyndicationFeed^ feed) { this->feedIterator->AttachFeed(feed); rootPage->NotifyUser("Fetching feed completed.", NotifyType::StatusMessage); if (this->feedIterator->HasElements()) { OutputField->Text += "Got feed\r\n"; OutputField->Text += "Title: " + this->feedIterator->GetTitle() + "\r\n"; OutputField->Text += "EditUri: " + this->feedIterator->GetEditUri()->DisplayUri + "\r\n"; DisplayItem(); } else { OutputField->Text += "Got empty feed\r\n"; } }).then([this] (task<void> t) { try { t.get(); } catch (Exception^ exception) { if (!rootPage->HandleException(exception, OutputField)) { throw; } } }); } // Update the current item. void Scenario4::UpdateItem_Click(Object^ sender, RoutedEventArgs^ e) { if (!this->feedIterator->HasElements()) { rootPage->NotifyUser("No item currently displayed, please download a feed first.", NotifyType::ErrorMessage); return; } rootPage->NotifyUser("Updating item...", NotifyType::StatusMessage); OutputField->Text += "Item location: " + feedIterator->GetEditUri()->DisplayUri + "\r\n"; // Update the item. SyndicationItem^ updatedItem = ref new SyndicationItem(); updatedItem->Title = ref new SyndicationText(TitleBox->Text, SyndicationTextType::Text); updatedItem->Content = ref new SyndicationContent(ContentBox->Text, SyndicationTextType::Html); task<void>(CommonData::GetClient()->UpdateResourceAsync(this->feedIterator->GetEditUri(), updatedItem)).then([this] (task<void> t) { try { t.get(); rootPage->NotifyUser("Item updated.", NotifyType::StatusMessage); } catch (Exception^ exception) { if (!rootPage->HandleException(exception, OutputField)) { throw; } } }); } void Scenario4::PreviousItem_Click(Object^ sender, RoutedEventArgs^ e) { this->feedIterator->MovePrevious(); DisplayItem(); } void Scenario4::NextItem_Click(Object^ sender, RoutedEventArgs^ e) { this->feedIterator->MoveNext(); DisplayItem(); } void Scenario4::UserNameField_TextChanged(Object^ sender, TextChangedEventArgs^ e) { CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password); } void Scenario4::PasswordField_PasswordChanged(Object^ sender, RoutedEventArgs^ e) { CommonData::Save(ServiceAddressField->Text, UserNameField->Text, PasswordField->Password); } void Scenario4::DisplayItem() { IndexField->Text = this->feedIterator->GetIndexDescription(); TitleBox->Text = this->feedIterator->GetTitle(); ContentBox->Text = feedIterator->GetContent(); }
mohneesh9797-puresoftware/cat2
cat-core-report/src/main/java/org/unidal/cat/spi/report/internals/DefaultReportReducerManager.java
<reponame>mohneesh9797-puresoftware/cat2 package org.unidal.cat.spi.report.internals; import java.util.HashMap; import java.util.Map; import org.unidal.cat.spi.Report; import org.unidal.cat.spi.report.ReportReducer; import org.unidal.cat.spi.report.ReportReducerManager; import org.unidal.lookup.ContainerHolder; import org.unidal.lookup.annotation.Named; @Named(type = ReportReducerManager.class) public class DefaultReportReducerManager extends ContainerHolder implements ReportReducerManager { private Map<String, ReportReducer<Report>> m_reducers = new HashMap<String, ReportReducer<Report>>(); @Override @SuppressWarnings("unchecked") public <T extends Report> ReportReducer<T> getReducer(String reportName, String id) { String key = reportName + ":" + id; ReportReducer<Report> reducer = m_reducers.get(key); if (reducer == null) { synchronized (m_reducers) { reducer = (ReportReducer<Report>) m_reducers.get(key); if (reducer == null) { reducer = lookup(ReportReducer.class, key); m_reducers.put(key, reducer); } } } return (ReportReducer<T>) reducer; } }
threefoldfoundation/tft-stellar
ThreeBotPackages/vesting_dashboard/scripts/export.py
<reponame>threefoldfoundation/tft-stellar<gh_stars>1-10 #!/usr/bin/env python # pylint: disable=no-value-for-parameter import click import os, sys import json from jumpscale.core.base import StoredFactory current_full_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(current_full_path + "/../models/") from models import VestingEntry vesting_entry_model = StoredFactory(VestingEntry) @click.command(help="Exports the data from the vestingdashboard") def export(): for modelname in vesting_entry_model.list_all(): print(json.dumps(vesting_entry_model.get(modelname).to_dict())) if __name__ == "__main__": export()
yacchin1205/RDM-modular-file-renderer
tests/server/handlers/test_cors.py
import pytest from unittest import mock from tornado import testing from tests.utils import HandlerTestCase from mfr.server.handlers.core import CorsMixin class MockHandler(CorsMixin): request = None headers = {} def set_header(self, key, value): self.headers[key] = value class MockRequest(object): def __init__( self, method='GET', cookies=False, headers={} ): self.method = method self.cookies = cookies self.headers = headers @mock.patch('mfr.server.settings.CORS_ALLOW_ORIGIN', '') class TestCorsMixin(HandlerTestCase): def setUp(self, *args, **kwargs): super(TestCorsMixin, self).setUp(*args, **kwargs) self.handler = MockHandler() @testing.gen_test def test_set_default_headers_options(self): origin = 'http://foo.com' self.handler.request = MockRequest( method='OPTIONS', headers={ 'Origin': origin, } ) self.handler.set_default_headers() assert origin == self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_options_no_cookie_but_auth_header(self): origin = 'http://foo.com' self.handler.request = MockRequest( method='OPTIONS', cookies=False, headers={ 'Origin': origin, 'Authorization': 'fooo' } ) self.handler.set_default_headers() assert origin == self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_options_has_cookie_and_auth_header(self): origin = 'http://foo.com' self.handler.request = MockRequest( method='OPTIONS', cookies=True, headers={ 'Origin': origin, 'Authorization': 'fooo' } ) self.handler.set_default_headers() assert origin == self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_options_has_cookie_no_auth_header(self): origin = 'http://foo.com' self.handler.request = MockRequest( method='OPTIONS', cookies=True, headers={ 'Origin': origin, } ) self.handler.set_default_headers() assert origin == self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_cross_origin_with_cookie(self): origin = 'http://foo.com' for method in ('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'): self.handler.request = MockRequest( method=method, cookies=True, headers={ 'Origin': origin, } ) self.handler.set_default_headers() assert origin not in self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_cross_origin_no_cookie_no_auth_header(self): origin = 'http://foo.com' for method in ('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'): self.handler.request = MockRequest( method=method, cookies=False, headers={ 'Origin': origin, } ) self.handler.set_default_headers() assert origin not in self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_cross_origin_has_cookie_and_auth_header(self): origin = 'http://foo.com' for method in ('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'): self.handler.request = MockRequest( method=method, cookies=True, headers={ 'Origin': origin, 'Authorization': 'asdlisdfgluiwgqruf' } ) self.handler.set_default_headers() assert origin not in self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_set_default_headers_cross_origin_no_cookie_but_auth_header(self): origin = 'http://foo.com' for method in ('HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'): self.handler.request = MockRequest( method=method, cookies=False, headers={ 'Origin': origin, 'Authorization': '<PASSWORD>' } ) self.handler.set_default_headers() assert origin in self.handler.headers['Access-Control-Allow-Origin'] @testing.gen_test def test_no_origin_means_no_cors(self): for method in ('OPTIONS', 'HEAD' 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'): self.handler.request = MockRequest( method=method, ) self.handler.set_default_headers() assert 'Access-Control-Allow-Origin' not in self.handler.headers assert 'Access-Control-Allow-Credentials' not in self.handler.headers assert 'Access-Control-Allow-Headers' not in self.handler.headers assert 'Access-Control-Expose-Headers' not in self.handler.headers
mindfreakthemon-archive/revolt
server/parts/fireblast-core/lib/helpers/express/inherit.js
export default function (app) { this.locals.basedir = app.locals.basedir; this.conf = app.conf; this.db = app.db; this.model = app.model; this.set('views', app.get('views')); this.set('view engine', app.get('view engine')); this.set('view cache', app.get('view cache')); this.set('case sensitive routing', app.get('case sensitive routing')); this.set('x-powered-by', app.get('x-powered-by')); }
oguennec/Kylin
metadata/src/main/java/com/kylinolap/metadata/tool/HiveSourceTableLoader.java
<reponame>oguennec/Kylin package com.kylinolap.metadata.tool; /* * Copyright 2013-2014 eBay Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import com.kylinolap.metadata.MetadataManager; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.kylinolap.common.KylinConfig; import com.kylinolap.common.persistence.ResourceTool; import com.kylinolap.common.util.CliCommandExecutor; import com.kylinolap.common.util.JsonUtil; import com.kylinolap.metadata.model.schema.ColumnDesc; import com.kylinolap.metadata.model.schema.TableDesc; /** * Management class to sync hive table metadata with command See main method for * how to use the class * * @author jianliu */ public class HiveSourceTableLoader { private static final Logger logger = LoggerFactory.getLogger(HiveSourceTableLoader.class); public static final String OUTPUT_SURFIX = "json"; public static final String TABLE_FOLDER_NAME = "table"; public static final String TABLE_EXD_FOLDER_NAME = "table_exd"; public static Set<String> reloadHiveTables(String[] hiveTables, KylinConfig config) throws IOException { Map<String, Set<String>> db2tables = Maps.newHashMap(); for (String table : hiveTables) { int cut = table.indexOf('.'); String database = cut >= 0 ? table.substring(0, cut).trim() : "DEFAULT"; String tableName = cut >= 0 ? table.substring(cut + 1).trim() : table.trim(); Set<String> set = db2tables.get(database); if (set == null) { set = Sets.newHashSet(); db2tables.put(database, set); } set.add(tableName); } // metadata tmp dir File metaTmpDir = File.createTempFile("meta_tmp", null); metaTmpDir.delete(); metaTmpDir.mkdirs(); for (String database: db2tables.keySet()) { for (String table: db2tables.get(database)) { TableDesc tableDesc = MetadataManager.getInstance(config).getTableDesc(table); if (tableDesc == null) { continue; } if (tableDesc.getDatabase().equalsIgnoreCase(database)) { continue; } else { throw new UnsupportedOperationException(String.format("there is already a table[%s] in database[%s]", tableDesc.getName(), tableDesc.getDatabase())); } } } // extract from hive Set<String> loadedTables = Sets.newHashSet(); for (String database : db2tables.keySet()) { List<String> loaded = extractHiveTables(database, db2tables.get(database), metaTmpDir, config); loadedTables.addAll(loaded); } // save loaded tables ResourceTool.copy(KylinConfig.createInstanceFromUri(metaTmpDir.getAbsolutePath()), config); return loadedTables; } private static List<String> extractHiveTables(String database, Set<String> tables, File metaTmpDir, KylinConfig config) throws IOException { StringBuilder cmd = new StringBuilder(); cmd.append("hive -e \""); if (StringUtils.isEmpty(database) == false) { cmd.append("use " + database + "; "); } for (String table : tables) { cmd.append("show table extended like " + table + "; "); } cmd.append("\""); CliCommandExecutor cmdExec = config.getCliCommandExecutor(); String output = cmdExec.execute(cmd.toString()); return extractTableDescFromHiveOutput(database, output, metaTmpDir); } private static List<String> extractTableDescFromHiveOutput(String database, String hiveOutput, File metaTmpDir) throws IOException { BufferedReader reader = new BufferedReader(new StringReader(hiveOutput)); try { return extractTables(database, reader, metaTmpDir); } finally { IOUtils.closeQuietly(reader); } } private static List<String> extractTables(String database, BufferedReader reader, File metaTmpDir) throws IOException { File tableDescDir = new File(metaTmpDir, TABLE_FOLDER_NAME); File tableExdDir = new File(metaTmpDir, TABLE_EXD_FOLDER_NAME); mkdirs(tableDescDir); mkdirs(tableExdDir); List<TableDesc> tableDescList = new ArrayList<TableDesc>(); List<Map<String, String>> tableAttrsList = new ArrayList<Map<String, String>>(); getTables(database, reader, tableDescList, tableAttrsList); List<String> loadedTables = Lists.newArrayList(); for (TableDesc table : tableDescList) { File file = new File(tableDescDir, table.getName().toUpperCase() + "." + OUTPUT_SURFIX); JsonUtil.writeValueIndent(new FileOutputStream(file), table); loadedTables.add(table.getDatabase() + "." + table.getName()); } for (Map<String, String> tableAttrs : tableAttrsList) { File file = new File(tableExdDir, tableAttrs.get("tableName").toUpperCase() + "." + OUTPUT_SURFIX); JsonUtil.writeValueIndent(new FileOutputStream(file), tableAttrs); } return loadedTables; } private static void mkdirs(File metaTmpDir) { if (!metaTmpDir.exists()) { if (!metaTmpDir.mkdirs()) { throw new IllegalArgumentException("Failed to create Output dir : " + metaTmpDir.getAbsolutePath()); } } } private static void getTables(String database, BufferedReader reader, // List<TableDesc> tableDescList, List<Map<String, String>> tableAttrsList) throws IOException { Map<String, String> tableAttrs = new HashMap<String, String>(); TableDesc tableDesc = new TableDesc(); String line; boolean hit = false; while ((line = reader.readLine()) != null) { logger.info(line); int i = line.indexOf(":"); if (i == -1) { continue; } String key = line.substring(0, i); String value = line.substring(i + 1, line.length()); if (key.equals("tableName")) {// Create a new table object hit = true; tableAttrs = new HashMap<String, String>(); tableAttrsList.add(tableAttrs); tableDesc = new TableDesc(); tableDescList.add(tableDesc); } if (!hit) { continue; } if (line.startsWith("columns")) {// geneate source table metadata String tname = tableAttrs.get("tableName"); tableDesc.setDatabase(database.toUpperCase()); tableDesc.setName(tname.toUpperCase()); tableDesc.setUuid(UUID.randomUUID().toString()); addColumns(tableDesc, value); } tableAttrs.put(key, value); if (key.equals("lastUpdateTime")) { hit = false; } } } private static void addColumns(TableDesc sTable, String value) { List<ColumnDesc> columns = new ArrayList<ColumnDesc>(); int i1 = value.indexOf("{"); int i2 = value.indexOf("}"); if (i1 < 0 || i2 < 0 || i1 > i2) { return; } String temp = value.substring(i1 + 1, i2); String[] strArr = temp.split(", "); for (int i = 0; i < strArr.length; i++) { String t1 = strArr[i].trim(); int pos = t1.indexOf(" "); String colType = t1.substring(0, pos).trim(); String colName = t1.substring(pos).trim(); ColumnDesc cdesc = new ColumnDesc(); cdesc.setName(colName.toUpperCase()); cdesc.setDatatype(convertType(colType)); cdesc.setId(String.valueOf(i + 1)); columns.add(cdesc); } sTable.setColumns(columns.toArray(new ColumnDesc[0])); } private static String convertType(String colType) { if ("i32".equals(colType)) { return "int"; } else if ("i64".equals(colType)) { return "bigint"; } else if ("i16".equals(colType)) { return "smallint"; } else if ("byte".equals(colType)) { return "tinyint"; } else if ("bool".equals(colType)) return "boolean"; return colType; } /** */ public static void main(String[] args) { } }
windystrife/UnrealEngine_NVIDIAGameWork
Engine/Source/Runtime/Core/Private/Misc/AutomationTest.cpp
<gh_stars>1-10 // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Misc/AutomationTest.h" #include "HAL/PlatformStackWalk.h" #include "HAL/FileManager.h" #include "Misc/CommandLine.h" #include "Misc/Paths.h" #include "Internationalization/Internationalization.h" #include "Misc/ConfigCacheIni.h" #include "Misc/ScopedSlowTask.h" #include "Misc/App.h" #include "Modules/ModuleManager.h" #include "Misc/OutputDeviceRedirector.h" #include "Internationalization/Regex.h" DEFINE_LOG_CATEGORY_STATIC(LogAutomationTest, Warning, All); void FAutomationTestFramework::FAutomationTestFeedbackContext::Serialize( const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category ) { const int32 STACK_OFFSET = 7; // TODO would be nice to search for the first stack frame that isn't in outputdevice or other logging files, would be more robust. if (!IsRunningCommandlet() && (Verbosity == ELogVerbosity::SetColor)) { return; } // Ensure there's a valid unit test associated with the context if ( CurTest ) { // Warnings if ( Verbosity == ELogVerbosity::Warning ) { // If warnings should be treated as errors, log the warnings as such in the current unit test if ( TreatWarningsAsErrors ) { CurTest->AddError(FString(V), STACK_OFFSET); } else { CurTest->AddWarning(FString(V), STACK_OFFSET); } } // Errors else if ( Verbosity == ELogVerbosity::Error ) { CurTest->AddError(FString(V), STACK_OFFSET); } // Display if ( Verbosity == ELogVerbosity::Display ) { CurTest->AddInfo(FString(V), STACK_OFFSET); } // Log...etc else { // IMPORTANT NOTE: This code will never be called in a build with NO_LOGGING defined, which means pretty much // any Test or Shipping config build. If you're trying to use the automation test framework for performance // data capture in a Test config, you'll want to call the AddAnalyticsItemToCurrentTest() function instead of // using this log interception stuff. FString LogString = FString(V); FString AnalyticsString = TEXT("AUTOMATIONANALYTICS"); if (LogString.StartsWith(*AnalyticsString)) { //Remove "analytics" from the string LogString = LogString.Right(LogString.Len() - (AnalyticsString.Len() + 1)); CurTest->AddAnalyticsItem(LogString); } //else //{ // CurTest->AddInfo(LogString, STACK_OFFSET); //} } } } FAutomationTestFramework& FAutomationTestFramework::Get() { static FAutomationTestFramework Framework; return Framework; } FString FAutomationTestFramework::GetUserAutomationDirectory() const { const FString DefaultAutomationSubFolder = TEXT("Unreal Automation"); return FString(FPlatformProcess::UserDir()) + DefaultAutomationSubFolder; } bool FAutomationTestFramework::RegisterAutomationTest( const FString& InTestNameToRegister, class FAutomationTestBase* InTestToRegister ) { const bool bAlreadyRegistered = AutomationTestClassNameToInstanceMap.Contains( InTestNameToRegister ); if ( !bAlreadyRegistered ) { AutomationTestClassNameToInstanceMap.Add( InTestNameToRegister, InTestToRegister ); } return !bAlreadyRegistered; } bool FAutomationTestFramework::UnregisterAutomationTest( const FString& InTestNameToUnregister ) { const bool bRegistered = AutomationTestClassNameToInstanceMap.Contains( InTestNameToUnregister ); if ( bRegistered ) { AutomationTestClassNameToInstanceMap.Remove( InTestNameToUnregister ); } return bRegistered; } void FAutomationTestFramework::EnqueueLatentCommand(TSharedPtr<IAutomationLatentCommand> NewCommand) { //ensure latent commands are never used within smoke tests - will only catch when smokes are exclusively requested check((RequestedTestFilter & EAutomationTestFlags::FilterMask) != EAutomationTestFlags::SmokeFilter); //ensure we are currently "running a test" check(GIsAutomationTesting); LatentCommands.Enqueue(NewCommand); } void FAutomationTestFramework::EnqueueNetworkCommand(TSharedPtr<IAutomationNetworkCommand> NewCommand) { //ensure latent commands are never used within smoke tests check((RequestedTestFilter & EAutomationTestFlags::FilterMask) != EAutomationTestFlags::SmokeFilter); //ensure we are currently "running a test" check(GIsAutomationTesting); NetworkCommands.Enqueue(NewCommand); } bool FAutomationTestFramework::ContainsTest( const FString& InTestName ) const { return AutomationTestClassNameToInstanceMap.Contains( InTestName ); } bool FAutomationTestFramework::RunSmokeTests() { bool bAllSuccessful = true; uint32 PreviousRequestedTestFilter = RequestedTestFilter; //so extra log spam isn't generated RequestedTestFilter = EAutomationTestFlags::SmokeFilter; // Skip running on cooked platforms like mobile //@todo - better determination of whether to run than requires cooked data // Ensure there isn't another slow task in progress when trying to run unit tests const bool bRequiresCookedData = FPlatformProperties::RequiresCookedData(); if ((!bRequiresCookedData && !GIsSlowTask && !GIsPlayInEditorWorld && !FPlatformProperties::IsProgram()) || bForceSmokeTests) { TArray<FAutomationTestInfo> TestInfo; GetValidTestNames( TestInfo ); if ( TestInfo.Num() > 0 ) { const double SmokeTestStartTime = FPlatformTime::Seconds(); // Output the results of running the automation tests TMap<FString, FAutomationTestExecutionInfo> OutExecutionInfoMap; // Run each valid test FScopedSlowTask SlowTask(TestInfo.Num()); // We disable capturing the stack when running smoke tests, it adds too much overhead to do it at startup. FAutomationTestFramework::Get().SetCaptureStack(false); for ( int TestIndex = 0; TestIndex < TestInfo.Num(); ++TestIndex ) { SlowTask.EnterProgressFrame(1); if (TestInfo[TestIndex].GetTestFlags() & EAutomationTestFlags::SmokeFilter ) { FString TestCommand = TestInfo[TestIndex].GetTestName(); FAutomationTestExecutionInfo& CurExecutionInfo = OutExecutionInfoMap.Add( TestCommand, FAutomationTestExecutionInfo() ); int32 RoleIndex = 0; //always default to "local" role index. Only used for multi-participant tests StartTestByName( TestCommand, RoleIndex ); const bool CurTestSuccessful = StopTest(CurExecutionInfo); bAllSuccessful = bAllSuccessful && CurTestSuccessful; } } FAutomationTestFramework::Get().SetCaptureStack(true); const double EndTime = FPlatformTime::Seconds(); const double TimeForTest = static_cast<float>(EndTime - SmokeTestStartTime); if (TimeForTest > 2.0f) { //force a failure if a smoke test takes too long UE_LOG(LogAutomationTest, Warning, TEXT("Smoke tests took > 2s to run: %.2fs"), (float)TimeForTest); } FAutomationTestFramework::DumpAutomationTestExecutionInfo( OutExecutionInfoMap ); } } else if( bRequiresCookedData ) { UE_LOG( LogAutomationTest, Log, TEXT( "Skipping unit tests for the cooked build." ) ); } else if (!FPlatformProperties::IsProgram()) { UE_LOG(LogAutomationTest, Error, TEXT("Skipping unit tests.") ); bAllSuccessful = false; } //revert to allowing all logs RequestedTestFilter = PreviousRequestedTestFilter; return bAllSuccessful; } void FAutomationTestFramework::ResetTests() { bool bEnsureExists = false; bool bDeleteEntireTree = true; //make sure all transient files are deleted successfully IFileManager::Get().DeleteDirectory(*FPaths::AutomationTransientDir(), bEnsureExists, bDeleteEntireTree); } void FAutomationTestFramework::StartTestByName( const FString& InTestToRun, const int32 InRoleIndex ) { if (GIsAutomationTesting) { while(!LatentCommands.IsEmpty()) { TSharedPtr<IAutomationLatentCommand> TempCommand; LatentCommands.Dequeue(TempCommand); } while(!NetworkCommands.IsEmpty()) { TSharedPtr<IAutomationNetworkCommand> TempCommand; NetworkCommands.Dequeue(TempCommand); } FAutomationTestExecutionInfo TempExecutionInfo; StopTest(TempExecutionInfo); } FString TestName; FString Params; if (!InTestToRun.Split(TEXT(" "), &TestName, &Params, ESearchCase::CaseSensitive)) { TestName = InTestToRun; } NetworkRoleIndex = InRoleIndex; // Ensure there isn't another slow task in progress when trying to run unit tests if ( !GIsSlowTask && !GIsPlayInEditorWorld ) { // Ensure the test exists in the framework and is valid to run if ( ContainsTest( TestName ) ) { // Make any setting changes that have to occur to support unit testing PrepForAutomationTests(); InternalStartTest( InTestToRun ); } else { UE_LOG(LogAutomationTest, Error, TEXT("Test %s does not exist and could not be run."), *InTestToRun); } } else { UE_LOG(LogAutomationTest, Error, TEXT("Test %s is too slow and could not be run."), *InTestToRun); } } bool FAutomationTestFramework::StopTest( FAutomationTestExecutionInfo& OutExecutionInfo ) { check(GIsAutomationTesting); bool bSuccessful = InternalStopTest(OutExecutionInfo); // Restore any changed settings now that unit testing has completed ConcludeAutomationTests(); return bSuccessful; } bool FAutomationTestFramework::ExecuteLatentCommands() { check(GIsAutomationTesting); bool bHadAnyLatentCommands = !LatentCommands.IsEmpty(); while (!LatentCommands.IsEmpty()) { //get the next command to execute TSharedPtr<IAutomationLatentCommand> NextCommand; LatentCommands.Peek(NextCommand); bool bComplete = NextCommand->InternalUpdate(); if (bComplete) { //all done. remove from the queue LatentCommands.Dequeue(NextCommand); } else { break; } } //need more processing on the next frame if (bHadAnyLatentCommands) { return false; } return true; } bool FAutomationTestFramework::ExecuteNetworkCommands() { check(GIsAutomationTesting); bool bHadAnyNetworkCommands = !NetworkCommands.IsEmpty(); if( bHadAnyNetworkCommands ) { // Get the next command to execute TSharedPtr<IAutomationNetworkCommand> NextCommand; NetworkCommands.Dequeue(NextCommand); if (NextCommand->GetRoleIndex() == NetworkRoleIndex) { NextCommand->Run(); } } return !bHadAnyNetworkCommands; } void FAutomationTestFramework::LoadTestModules( ) { const bool bRunningEditor = GIsEditor && !IsRunningCommandlet(); bool bRunningSmokeTests = ((RequestedTestFilter & EAutomationTestFlags::FilterMask) == EAutomationTestFlags::SmokeFilter); if( !bRunningSmokeTests ) { TArray<FString> EngineTestModules; GConfig->GetArray( TEXT("/Script/Engine.AutomationTestSettings"), TEXT("EngineTestModules"), EngineTestModules, GEngineIni); //Load any engine level modules. for( int32 EngineModuleId = 0; EngineModuleId < EngineTestModules.Num(); ++EngineModuleId) { const FName ModuleName = FName(*EngineTestModules[EngineModuleId]); //Make sure that there is a name available. This can happen if a name is left blank in the Engine.ini if (ModuleName == NAME_None || ModuleName == TEXT("None")) { UE_LOG(LogAutomationTest, Warning, TEXT("The automation test module ('%s') doesn't have a valid name."), *ModuleName.ToString()); continue; } if (!FModuleManager::Get().IsModuleLoaded(ModuleName)) { UE_LOG(LogAutomationTest, Log, TEXT("Loading automation test module: '%s'."), *ModuleName.ToString()); FModuleManager::Get().LoadModule(ModuleName); } } //Load any editor modules. if( bRunningEditor ) { TArray<FString> EditorTestModules; GConfig->GetArray( TEXT("/Script/Engine.AutomationTestSettings"), TEXT("EditorTestModules"), EditorTestModules, GEngineIni); for( int32 EditorModuleId = 0; EditorModuleId < EditorTestModules.Num(); ++EditorModuleId ) { const FName ModuleName = FName(*EditorTestModules[EditorModuleId]); //Make sure that there is a name available. This can happen if a name is left blank in the Engine.ini if (ModuleName == NAME_None || ModuleName == TEXT("None")) { UE_LOG(LogAutomationTest, Warning, TEXT("The automation test module ('%s') doesn't have a valid name."), *ModuleName.ToString()); continue; } if (!FModuleManager::Get().IsModuleLoaded(ModuleName)) { UE_LOG(LogAutomationTest, Log, TEXT("Loading automation test module: '%s'."), *ModuleName.ToString()); FModuleManager::Get().LoadModule(ModuleName); } } } } } void FAutomationTestFramework::GetValidTestNames( TArray<FAutomationTestInfo>& TestInfo ) const { TestInfo.Empty(); // Determine required application type (Editor, Game, or Commandlet) const bool bRunningEditor = GIsEditor && !IsRunningCommandlet(); const bool bRunningGame = !GIsEditor || IsRunningGame(); const bool bRunningCommandlet = IsRunningCommandlet(); //application flags uint32 ApplicationSupportFlags = 0; if ( bRunningEditor ) { ApplicationSupportFlags |= EAutomationTestFlags::EditorContext; } if ( bRunningGame ) { ApplicationSupportFlags |= EAutomationTestFlags::ClientContext; } if ( bRunningCommandlet ) { ApplicationSupportFlags |= EAutomationTestFlags::CommandletContext; } //Feature support - assume valid RHI until told otherwise uint32 FeatureSupportFlags = EAutomationTestFlags::FeatureMask; // @todo: Handle this correctly. GIsUsingNullRHI is defined at Engine-level, so it can't be used directly here in Core. // For now, assume Null RHI is only used for commandlets, servers, and when the command line specifies to use it. if (FPlatformProperties::SupportsWindowedMode()) { bool bUsingNullRHI = FParse::Param( FCommandLine::Get(), TEXT("nullrhi") ) || IsRunningCommandlet() || IsRunningDedicatedServer(); if (bUsingNullRHI) { FeatureSupportFlags &= (~EAutomationTestFlags::NonNullRHI); } } if (FApp::IsUnattended()) { FeatureSupportFlags &= (~EAutomationTestFlags::RequiresUser); } for ( TMap<FString, FAutomationTestBase*>::TConstIterator TestIter( AutomationTestClassNameToInstanceMap ); TestIter; ++TestIter ) { const FAutomationTestBase* CurTest = TestIter.Value(); check( CurTest ); uint32 CurTestFlags = CurTest->GetTestFlags(); //filter out full tests when running smoke tests const bool bPassesFilterRequirement = ((CurTestFlags & RequestedTestFilter) != 0); //Application Tests uint32 CurTestApplicationFlags = (CurTestFlags & EAutomationTestFlags::ApplicationContextMask); const bool bPassesApplicationRequirements = (CurTestApplicationFlags == 0) || (CurTestApplicationFlags & ApplicationSupportFlags); //Feature Tests uint32 CurTestFeatureFlags = (CurTestFlags & EAutomationTestFlags::FeatureMask); const bool bPassesFeatureRequirements = (CurTestFeatureFlags == 0) || (CurTestFeatureFlags & FeatureSupportFlags); const bool bEnabled = (CurTestFlags & EAutomationTestFlags::Disabled) == 0; if (bEnabled && bPassesApplicationRequirements && bPassesFeatureRequirements && bPassesFilterRequirement) { CurTest->GenerateTestNames(TestInfo); } } } bool FAutomationTestFramework::ShouldTestContent(const FString& Path) const { static TArray<FString> TestLevelFolders; if ( TestLevelFolders.Num() == 0 ) { GConfig->GetArray( TEXT("/Script/Engine.AutomationTestSettings"), TEXT("TestLevelFolders"), TestLevelFolders, GEngineIni); } bool bMatchingDirectory = false; for ( const FString& Folder : TestLevelFolders ) { const FString PatternToCheck = FString::Printf(TEXT("/%s/"), *Folder); if ( Path.Contains(*PatternToCheck) ) { bMatchingDirectory = true; } } if (bMatchingDirectory) { return true; } FString DevelopersPath = FPaths::GameDevelopersDir().LeftChop(1); return bDeveloperDirectoryIncluded || !Path.StartsWith(DevelopersPath); } void FAutomationTestFramework::SetDeveloperDirectoryIncluded(const bool bInDeveloperDirectoryIncluded) { bDeveloperDirectoryIncluded = bInDeveloperDirectoryIncluded; } void FAutomationTestFramework::SetRequestedTestFilter(const uint32 InRequestedTestFlags) { RequestedTestFilter = InRequestedTestFlags; } FOnTestScreenshotCaptured& FAutomationTestFramework::OnScreenshotCaptured() { return TestScreenshotCapturedDelegate; } void FAutomationTestFramework::PrepForAutomationTests() { check(!GIsAutomationTesting); // Fire off callback signifying that unit testing is about to begin. This allows // other systems to prepare themselves as necessary without the unit testing framework having to know // about them. PreTestingEvent.Broadcast(); // Cache the contents of GWarn, as unit testing is going to forcibly replace GWarn with a specialized feedback context // designed for unit testing AutomationTestFeedbackContext.TreatWarningsAsErrors = GWarn->TreatWarningsAsErrors; //GWarn = &AutomationTestFeedbackContext; GLog->AddOutputDevice(&AutomationTestFeedbackContext); // Mark that unit testing has begun GIsAutomationTesting = true; } void FAutomationTestFramework::ConcludeAutomationTests() { check(GIsAutomationTesting); // Mark that unit testing is over GIsAutomationTesting = false; //GWarn = CachedContext; GLog->RemoveOutputDevice(&AutomationTestFeedbackContext); // Fire off callback signifying that unit testing has concluded. PostTestingEvent.Broadcast(); } /** * Helper method to dump the contents of the provided test name to execution info map to the provided feedback context * * @param InContext Context to dump the execution info to * @param InInfoToDump Execution info that should be dumped to the provided feedback context */ void FAutomationTestFramework::DumpAutomationTestExecutionInfo( const TMap<FString, FAutomationTestExecutionInfo>& InInfoToDump ) { const FString SuccessMessage = NSLOCTEXT("UnrealEd", "AutomationTest_Success", "Success").ToString(); const FString FailMessage = NSLOCTEXT("UnrealEd", "AutomationTest_Fail", "Fail").ToString(); for ( TMap<FString, FAutomationTestExecutionInfo>::TConstIterator MapIter(InInfoToDump); MapIter; ++MapIter ) { const FString& CurTestName = MapIter.Key(); const FAutomationTestExecutionInfo& CurExecutionInfo = MapIter.Value(); UE_LOG(LogAutomationTest, Log, TEXT("%s: %s"), *CurTestName, CurExecutionInfo.bSuccessful ? *SuccessMessage : *FailMessage); for ( const FAutomationEvent& Event : CurExecutionInfo.GetEvents() ) { switch ( Event.Type ) { case EAutomationEventType::Info: UE_LOG(LogAutomationTest, Display, TEXT("%s"), *Event.Message); break; case EAutomationEventType::Warning: UE_LOG(LogAutomationTest, Warning, TEXT("%s"), *Event.Message); break; case EAutomationEventType::Error: UE_LOG(LogAutomationTest, Error, TEXT("%s"), *Event.Message); break; } } } } void FAutomationTestFramework::InternalStartTest( const FString& InTestToRun ) { FString TestName; if (!InTestToRun.Split(TEXT(" "), &TestName, &Parameters, ESearchCase::CaseSensitive)) { TestName = InTestToRun; } if ( ContainsTest( TestName ) ) { CurrentTest = *( AutomationTestClassNameToInstanceMap.Find( TestName ) ); check( CurrentTest ); // Clear any execution info from the test in case it has been run before CurrentTest->ClearExecutionInfo(); // Associate the test that is about to be run with the special unit test feedback context AutomationTestFeedbackContext.SetCurrentAutomationTest( CurrentTest ); StartTime = FPlatformTime::Seconds(); //if non- uint32 NonSmokeTestFlags = (EAutomationTestFlags::FilterMask & (~EAutomationTestFlags::SmokeFilter)); if (RequestedTestFilter & NonSmokeTestFlags) { UE_LOG(LogAutomationTest, Log, TEXT("%s %s is starting at %f"), *CurrentTest->GetBeautifiedTestName(), *Parameters, StartTime); } // Run the test! bTestSuccessful = CurrentTest->RunTest(Parameters); } } bool FAutomationTestFramework::InternalStopTest(FAutomationTestExecutionInfo& OutExecutionInfo) { check(GIsAutomationTesting); check(LatentCommands.IsEmpty()); double EndTime = FPlatformTime::Seconds(); double TimeForTest = static_cast<float>(EndTime - StartTime); uint32 NonSmokeTestFlags = (EAutomationTestFlags::FilterMask & (~EAutomationTestFlags::SmokeFilter)); if (RequestedTestFilter & NonSmokeTestFlags) { UE_LOG(LogAutomationTest, Log, TEXT("%s %s ran in %f"), *CurrentTest->GetBeautifiedTestName(), *Parameters, TimeForTest); } // Disassociate the test from the feedback context AutomationTestFeedbackContext.SetCurrentAutomationTest( NULL ); // Determine if the test was successful based on three criteria: // 1) Did the test itself report success? // 2) Did any errors occur and were logged by the feedback context during execution?++---- // 3) Did we meet any errors that were expected with this test bTestSuccessful = bTestSuccessful && !CurrentTest->HasAnyErrors() && CurrentTest->HasMetExpectedErrors(); // Set the success state of the test based on the above criteria CurrentTest->SetSuccessState( bTestSuccessful ); // Fill out the provided execution info with the info from the test CurrentTest->GetExecutionInfo( OutExecutionInfo ); // Save off timing for the test OutExecutionInfo.Duration = TimeForTest; // Re-enable log parsing if it was disabled and empty the expected errors list if (CurrentTest->ExpectedErrors.Num()) { GLog->Logf(ELogVerbosity::Display, TEXT("<-- Resume Log Parsing -->")); } CurrentTest->ExpectedErrors.Empty(); // Release pointers to now-invalid data CurrentTest = NULL; return bTestSuccessful; } void FAutomationTestFramework::AddAnalyticsItemToCurrentTest( const FString& AnalyticsItem ) { if( CurrentTest != nullptr ) { CurrentTest->AddAnalyticsItem( AnalyticsItem ); } else { UE_LOG( LogAutomationTest, Warning, TEXT( "AddAnalyticsItemToCurrentTest() called when no automation test was actively running!" ) ); } } bool FAutomationTestFramework::GetTreatWarningsAsErrors() const { return AutomationTestFeedbackContext.TreatWarningsAsErrors; } void FAutomationTestFramework::SetTreatWarningsAsErrors(TOptional<bool> bTreatWarningsAsErrors) { AutomationTestFeedbackContext.TreatWarningsAsErrors = bTreatWarningsAsErrors.IsSet() ? bTreatWarningsAsErrors.GetValue() : GWarn->TreatWarningsAsErrors; } void FAutomationTestFramework::NotifyScreenshotComparisonComplete(bool bWasNew, bool bWasSimilar, double MaxLocalDifference, double GlobalDifference, FString ErrorMessage) { OnScreenshotCompared.Broadcast(bWasNew, bWasSimilar, MaxLocalDifference, GlobalDifference, ErrorMessage); } void FAutomationTestFramework::NotifyTestDataRetrieved(bool bWasNew, const FString& JsonData) { OnTestDataRetrieved.Broadcast(bWasNew, JsonData); } void FAutomationTestFramework::NotifyPerformanceDataRetrieved(bool bSuccess, const FString& ErrorMessage) { OnPerformanceDataRetrieved.Broadcast(bSuccess, ErrorMessage); } void FAutomationTestFramework::NotifyScreenshotTakenAndCompared() { OnScreenshotTakenAndCompared.Broadcast(); } FAutomationTestFramework::FAutomationTestFramework() : RequestedTestFilter(EAutomationTestFlags::SmokeFilter) , StartTime(0.0f) , bTestSuccessful(false) , CurrentTest(nullptr) , bDeveloperDirectoryIncluded(false) , NetworkRoleIndex(0) , bForceSmokeTests(false) , bCaptureStack(true) { } FAutomationTestFramework::~FAutomationTestFramework() { AutomationTestClassNameToInstanceMap.Empty(); } FString FAutomationEvent::ToString() const { FString ComplexString; if ( !Filename.IsEmpty() && LineNumber > 0 ) { ComplexString += Filename; ComplexString += TEXT("("); ComplexString += FString::FromInt(LineNumber); ComplexString += TEXT("): "); } if ( !Context.IsEmpty() ) { ComplexString += TEXT("["); ComplexString += Context; ComplexString += TEXT("] "); } ComplexString += Message; return ComplexString; } //------------------------------------------------------------------------------ void FAutomationTestExecutionInfo::Clear() { ContextStack.Reset(); Events.Empty(); AnalyticsItems.Empty(); Errors = 0; Warnings = 0; } int32 FAutomationTestExecutionInfo::RemoveAllEvents(EAutomationEventType EventType) { return RemoveAllEvents([EventType] (const FAutomationEvent& Event) { return Event.Type == EventType; }); } int32 FAutomationTestExecutionInfo::RemoveAllEvents(TFunctionRef<bool(FAutomationEvent&)> FilterPredicate) { int32 TotalRemoved = Events.RemoveAll([&](FAutomationEvent& Event) { if ( FilterPredicate(Event) ) { switch ( Event.Type ) { case EAutomationEventType::Warning: Warnings--; break; case EAutomationEventType::Error: Errors--; break; } return true; } return false; }); return TotalRemoved; } void FAutomationTestExecutionInfo::AddEvent(const FAutomationEvent& Event) { switch ( Event.Type ) { case EAutomationEventType::Warning: Warnings++; break; case EAutomationEventType::Error: Errors++; break; } const int32 Index = Events.Add(Event); FAutomationEvent& NewEvent = Events[Index]; if ( NewEvent.Context.IsEmpty() ) { NewEvent.Context = GetContext(); } } void FAutomationTestExecutionInfo::AddWarning(const FString& WarningMessage) { AddEvent(FAutomationEvent(EAutomationEventType::Warning, WarningMessage)); } void FAutomationTestExecutionInfo::AddError(const FString& ErrorMessage) { AddEvent(FAutomationEvent(EAutomationEventType::Error, ErrorMessage)); } //------------------------------------------------------------------------------ void FAutomationTestBase::ClearExecutionInfo() { ExecutionInfo.Clear(); } void FAutomationTestBase::AddError(const FString& InError, int32 StackOffset) { if( !bSuppressLogs && !IsExpectedError(InError)) { if ( FAutomationTestFramework::Get().GetCaptureStack() ) { TArray<FProgramCounterSymbolInfo> Stack = FPlatformStackWalk::GetStack(StackOffset + 1, 1); ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Error, InError, ExecutionInfo.GetContext(), Stack[0].Filename, Stack[0].LineNumber)); } else { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Error, InError, ExecutionInfo.GetContext())); } } } void FAutomationTestBase::AddError(const FString& InError, const FString& InFilename, int32 InLineNumber) { if ( !bSuppressLogs && !IsExpectedError(InError)) { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Error, InError, ExecutionInfo.GetContext(), InFilename, InLineNumber)); } } void FAutomationTestBase::AddWarning(const FString& InWarning, const FString& InFilename, int32 InLineNumber) { if ( !bSuppressLogs && !IsExpectedError(InWarning)) { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Warning, InWarning, ExecutionInfo.GetContext(), InFilename, InLineNumber)); } } void FAutomationTestBase::AddWarning( const FString& InWarning, int32 StackOffset ) { if ( !bSuppressLogs && !IsExpectedError(InWarning)) { if ( FAutomationTestFramework::Get().GetCaptureStack() ) { TArray<FProgramCounterSymbolInfo> Stack = FPlatformStackWalk::GetStack(StackOffset + 1, 1); ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Warning, InWarning, ExecutionInfo.GetContext(), Stack[0].Filename, Stack[0].LineNumber)); } else { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Warning, InWarning, ExecutionInfo.GetContext())); } } } void FAutomationTestBase::AddInfo( const FString& InLogItem, int32 StackOffset ) { if ( !bSuppressLogs ) { if ( FAutomationTestFramework::Get().GetCaptureStack() ) { TArray<FProgramCounterSymbolInfo> Stack = FPlatformStackWalk::GetStack(StackOffset + 1, 1); ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Info, InLogItem, ExecutionInfo.GetContext(), Stack[0].Filename, Stack[0].LineNumber)); } else { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Info, InLogItem, ExecutionInfo.GetContext())); } } } void FAutomationTestBase::AddAnalyticsItem(const FString& InAnalyticsItem) { ExecutionInfo.AnalyticsItems.Add(InAnalyticsItem); } bool FAutomationTestBase::HasAnyErrors() const { return ExecutionInfo.GetErrorTotal() > 0; } bool FAutomationTestBase::HasMetExpectedErrors() { bool HasMetAllExpectedErrors = true; for (auto& EError : ExpectedErrors) { if ((EError.ExpectedNumberOfOccurrences > 0) && (EError.ExpectedNumberOfOccurrences != EError.ActualNumberOfOccurrences)) { HasMetAllExpectedErrors = false; ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Error, FString::Printf(TEXT("Expected Error or Warning matching '%s' to occur %d times with %s match type, but it was found %d time(s).") , *EError.ErrorPatternString , EError.ExpectedNumberOfOccurrences , EAutomationExpectedErrorFlags::ToString(EError.CompareType) , EError.ActualNumberOfOccurrences) , ExecutionInfo.GetContext())); } else if (EError.ExpectedNumberOfOccurrences == 0) { if (EError.ActualNumberOfOccurrences == 0) { HasMetAllExpectedErrors = false; ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Error, FString::Printf(TEXT("Expected suppressed Error or Warning matching '%s' did not occur."), *EError.ErrorPatternString), ExecutionInfo.GetContext())); } else { ExecutionInfo.AddEvent(FAutomationEvent(EAutomationEventType::Info, FString::Printf(TEXT("Suppressed expected Error or Warning matching '%s' %d times.") , *EError.ErrorPatternString , EError.ActualNumberOfOccurrences) , ExecutionInfo.GetContext())); } } } return HasMetAllExpectedErrors; } void FAutomationTestBase::SetSuccessState( bool bSuccessful ) { ExecutionInfo.bSuccessful = bSuccessful; } void FAutomationTestBase::GetExecutionInfo( FAutomationTestExecutionInfo& OutInfo ) const { OutInfo = ExecutionInfo; } void FAutomationTestBase::AddExpectedError(FString ExpectedErrorPattern, EAutomationExpectedErrorFlags::MatchType InCompareType, int32 Occurrences) { if (Occurrences >= 0) { // If we already have an error matching string in our list, let's not add it again. FAutomationExpectedError* FoundEntry = ExpectedErrors.FindByPredicate( [ExpectedErrorPattern](const FAutomationExpectedError& InItem) { return InItem.ErrorPatternString == ExpectedErrorPattern; } ); if (FoundEntry) { UE_LOG(LogAutomationTest, Warning, TEXT("Adding expected error matching '%s' failed: cannot add duplicate entries"), *ExpectedErrorPattern) } else { // Disable log pre-processor the first time we successfully add an expected error // so that successful tests don't trigger CIS failures if (!ExpectedErrors.Num()) { GLog->Logf(ELogVerbosity::Display, TEXT("<-- Suspend Log Parsing -->")); } // ToDo: After UE-44340 is resolved, create FAutomationExpectedError and check that its ErrorPattern is valid before adding ExpectedErrors.Add(FAutomationExpectedError(ExpectedErrorPattern, InCompareType, Occurrences)); } } else { UE_LOG(LogAutomationTest, Error, TEXT("Adding expected error matching '%s' failed: number of expected occurrences must be >= 0"), *ExpectedErrorPattern); } } void FAutomationTestBase::GetExpectedErrors(TArray<FAutomationExpectedError>& OutInfo) const { OutInfo = ExpectedErrors; } void FAutomationTestBase::GenerateTestNames(TArray<FAutomationTestInfo>& TestInfo) const { TArray<FString> BeautifiedNames; TArray<FString> ParameterNames; GetTests(BeautifiedNames, ParameterNames); FString BeautifiedTestName = GetBeautifiedTestName(); for (int32 ParameterIndex = 0; ParameterIndex < ParameterNames.Num(); ++ParameterIndex) { FString CompleteBeautifiedNames = BeautifiedTestName; FString CompleteTestName = TestName; if (ParameterNames[ParameterIndex].Len()) { CompleteBeautifiedNames = FString::Printf(TEXT("%s.%s"), *BeautifiedTestName, *BeautifiedNames[ParameterIndex]);; CompleteTestName = FString::Printf(TEXT("%s %s"), *TestName, *ParameterNames[ParameterIndex]); } // Add the test info to our collection FAutomationTestInfo NewTestInfo( CompleteBeautifiedNames, CompleteBeautifiedNames, CompleteTestName, GetTestFlags(), GetRequiredDeviceNum(), ParameterNames[ParameterIndex], GetTestSourceFileName(CompleteTestName), GetTestSourceFileLine(CompleteTestName), GetTestAssetPath(ParameterNames[ParameterIndex]), GetTestOpenCommand(ParameterNames[ParameterIndex]) ); TestInfo.Add( NewTestInfo ); } } // -------------------------------------------------------------------------------------- void FAutomationTestBase::TestEqual(const FString& What, const int32 Actual, const int32 Expected) { if ( Actual != Expected ) { AddError(FString::Printf(TEXT("Expected '%s' to be %d, but it was %d."), *What, Expected, Actual), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be %d."), *What, Expected), 1); } } void FAutomationTestBase::TestEqual(const FString& What, const float Actual, const float Expected, float Tolerance) { if ( !FMath::IsNearlyEqual(Actual, Expected, Tolerance) ) { AddError(FString::Printf(TEXT("Expected '%s' to be %f, but it was %f within tolerance %f."), *What, Expected, Actual, Tolerance), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be %f within tolerance %f."), *What, Expected, Tolerance), 1); } } void FAutomationTestBase::TestEqual(const FString& What, const FVector Actual, const FVector Expected, float Tolerance) { if ( !Expected.Equals(Actual, Tolerance) ) { AddError(FString::Printf(TEXT("Expected '%s' to be %s, but it was %s within tolerance %f."), *What, *Expected.ToString(), *Actual.ToString(), Tolerance), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be %s within tolerance %f."), *What, *Expected.ToString(), Tolerance), 1); } } void FAutomationTestBase::TestEqual(const FString& What, const FColor Actual, const FColor Expected) { if ( Expected != Actual ) { AddError(FString::Printf(TEXT("Expected '%s' to be %s, but it was %s."), *What, *Expected.ToString(), *Actual.ToString()), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be %s."), *What, *Expected.ToString()), 1); } } void FAutomationTestBase::TestFalse(const FString& What, bool Value) { if ( Value ) { AddError(FString::Printf(TEXT("Expected '%s' to be false."), *What), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be false."), *What), 1); } } void FAutomationTestBase::TestTrue(const FString& What, bool Value) { if ( !Value ) { AddError(FString::Printf(TEXT("Expected '%s' to be true."), *What), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be true."), *What), 1); } } void FAutomationTestBase::TestNull(const FString& What, const void* Pointer) { if ( Pointer != nullptr ) { AddError(FString::Printf(TEXT("Expected '%s' to be null."), *What), 1); } else { AddInfo(FString::Printf(TEXT("Expected '%s' to be null."), *What), 1); } } bool FAutomationTestBase::IsExpectedError(const FString& Error) { for (auto& EError : ExpectedErrors) { FRegexMatcher ErrorMatcher(EError.ErrorPattern, Error); if (ErrorMatcher.FindNext()) { EError.ActualNumberOfOccurrences++; return true; } } return false; }
danadel/sakai
dashboard/api/src/java/org/sakaiproject/dash/model/CalendarItem.java
<reponame>danadel/sakai<filename>dashboard/api/src/java/org/sakaiproject/dash/model/CalendarItem.java /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2011 The Sakai Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.dash.model; import java.io.Serializable; import java.util.Date; /** * CalendarItem encapsulates all information about dashboard items to * appear in the "Calendar" section of users' dashboards. * */ public class CalendarItem implements Serializable { protected Long id; protected String title; protected Date calendarTime; protected String calendarTimeLabelKey; protected String entityReference; protected Context context; protected SourceType sourceType; protected String subtype; protected RepeatingCalendarItem repeatingCalendarItem = null; protected Integer sequenceNumber = null; /** * */ public CalendarItem() { super(); } /** * * @param title * @param calendarTime * @param calendarTimeLabelKey * @param entityReference * @param context * @param sourceType * @param subtype TODO * @param repeatingCalendarItem * @param sequenceNumber TODO */ public CalendarItem(String title, Date calendarTime, String calendarTimeLabelKey, String entityReference, Context context, SourceType sourceType, String subtype, RepeatingCalendarItem repeatingCalendarItem, Integer sequenceNumber) { super(); this.title = title; this.calendarTime = calendarTime; this.calendarTimeLabelKey = calendarTimeLabelKey; this.entityReference = entityReference; this.context = context; this.sourceType = sourceType; this.subtype = subtype; this.repeatingCalendarItem = repeatingCalendarItem; this.sequenceNumber = sequenceNumber; } /** * @param id * @param title * @param calendarTime * @param calendarTimeLabelKey * @param entityReference * @param context * @param sourceType * @param subtype TODO * @param repeatingCalendarItem * @param sequenceNumber TODO * @param realm */ public CalendarItem(Long id, String title, Date calendarTime, String calendarTimeLabelKey, String entityReference, Context context, SourceType sourceType, String subtype, RepeatingCalendarItem repeatingCalendarItem, Integer sequenceNumber) { super(); this.id = id; this.title = title; this.calendarTime = calendarTime; this.calendarTimeLabelKey = calendarTimeLabelKey; this.entityReference = entityReference; this.context = context; this.sourceType = sourceType; this.subtype = subtype; this.repeatingCalendarItem = repeatingCalendarItem; this.sequenceNumber = sequenceNumber; } /** * @return the id */ public Long getId() { return id; } /** * @return the title */ public String getTitle() { return title; } /** * @return the calendarTime */ public Date getCalendarTime() { return calendarTime; } /** * * @return */ public String getCalendarTimeLabelKey() { return this.calendarTimeLabelKey; } /** * @return the entityReference */ public String getEntityReference() { return entityReference; } /** * @return the context */ public Context getContext() { return context; } /** * @return the repeatingCalendarItem */ public RepeatingCalendarItem getRepeatingCalendarItem() { return repeatingCalendarItem; } /** * @return the sequenceNumber */ public Integer getSequenceNumber() { return sequenceNumber; } /** * @return the sourceType */ public SourceType getSourceType() { return sourceType; } /** * @return the subtype */ public String getSubtype() { return subtype; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @param calendarTime the calendarTime to set */ public void setCalendarTime(Date calendarTime) { this.calendarTime = calendarTime; } public void setCalendarTimeLabelKey(String calendarTimeLabelKey) { this.calendarTimeLabelKey = calendarTimeLabelKey; } /** * @param entityReference the entityReference to set */ public void setEntityReference(String entityReference) { this.entityReference = entityReference; } /** * @param context the context to set */ public void setContext(Context context) { this.context = context; } /** * @param repeatingCalendarItem the repeatingCalendarItem to set */ public void setRepeatingCalendarItem(RepeatingCalendarItem repeatingCalendarItem) { this.repeatingCalendarItem = repeatingCalendarItem; } /** * @param sequenceNumber the sequenceNumber to set */ public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } /** * @param sourceType the sourceType to set */ public void setSourceType(SourceType sourceType) { this.sourceType = sourceType; } /** * @param subtype the subtype to set */ public void setSubtype(String subtype) { this.subtype = subtype; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("CalendarItem [id="); builder.append(id); builder.append(", title="); builder.append(title); builder.append(", calendarTime="); builder.append(calendarTime); builder.append(", calendarTimeLabelKey="); builder.append(calendarTimeLabelKey); builder.append(", entityReference="); builder.append(entityReference); builder.append(", context="); builder.append(context); builder.append(", sourceType="); builder.append(sourceType); builder.append(", subtype="); builder.append(subtype); builder.append(", repeatingCalendarItem="); builder.append(repeatingCalendarItem); builder.append(", sequenceNumber="); builder.append(sequenceNumber); builder.append("]"); return builder.toString(); } }
xgSama/bigdata
flink/src/test/java/com/xgsama/flink/TestDemo.java
package com.xgsama.flink; /** * TestDemo * * @author : xgSama * @date : 2022/1/10 11:41:06 */public class TestDemo { }
Bloxxel64/sm64js
src/levels/ssl/tox_box/collision.inc.js
// Ssl import { COL_INIT, COL_VERTEX_INIT, COL_VERTEX, COL_TRI_INIT, COL_TRI, COL_TRI_STOP, COL_END, SURFACE_WALL_MISC } from "../../../include/surface_terrains" // 0x07012644 - 0x07012758 export const ssl_seg7_collision_tox_box = [ COL_INIT(), COL_VERTEX_INIT(0x10), COL_VERTEX(-255, 256, 256), COL_VERTEX(256, 256, -255), COL_VERTEX(-255, 256, -255), COL_VERTEX(256, 256, 256), COL_VERTEX(-255, -255, 256), COL_VERTEX(256, -255, 256), COL_VERTEX(256, -255, -255), COL_VERTEX(-255, -255, -255), COL_VERTEX(154, -255, 154), COL_VERTEX(154, -255, -153), COL_VERTEX(-153, -255, -153), COL_VERTEX(-153, -255, 154), COL_VERTEX(-153, 154, 154), COL_VERTEX(-153, 154, -153), COL_VERTEX(154, 154, -153), COL_VERTEX(154, 154, 154), COL_TRI_INIT(SURFACE_WALL_MISC, 28), COL_TRI(12, 13, 14), COL_TRI(0, 1, 2), COL_TRI(0, 3, 1), COL_TRI(4, 0, 2), COL_TRI(5, 0, 4), COL_TRI(5, 3, 0), COL_TRI(6, 3, 5), COL_TRI(6, 1, 3), COL_TRI(7, 1, 6), COL_TRI(7, 2, 1), COL_TRI(4, 2, 7), COL_TRI(8, 6, 5), COL_TRI(8, 9, 6), COL_TRI(7, 6, 9), COL_TRI(4, 8, 5), COL_TRI(7, 9, 10), COL_TRI(7, 11, 4), COL_TRI(7, 10, 11), COL_TRI(4, 11, 8), COL_TRI(12, 11, 10), COL_TRI(12, 10, 13), COL_TRI(10, 14, 13), COL_TRI(10, 9, 14), COL_TRI(8, 11, 12), COL_TRI(14, 9, 8), COL_TRI(12, 14, 15), COL_TRI(8, 12, 15), COL_TRI(14, 8, 15), COL_TRI_STOP(), COL_END(), ].flat(); // 2021-06-14 09:53:10 -0400 (Convert.rb 2021-06-14 09:43:28 -0400)
fu7mu4/entonetics
sfml/CSFML/include/SFML/Network/SocketTCP.h
<reponame>fu7mu4/entonetics //////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007 <NAME> (<EMAIL>) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_SOCKETTCP_H #define SFML_SOCKETTCP_H //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Config.h> #include <SFML/Network/IPAddress.h> #include <SFML/Network/Packet.h> #include <SFML/Network/SocketStatus.h> //////////////////////////////////////////////////////////// /// SocketTCP wraps a socket using TCP protocol to /// send data safely (but a bit slower) //////////////////////////////////////////////////////////// typedef struct sfSocketTCP sfSocketTCP; //////////////////////////////////////////////////////////// /// Construct a new TCP socket /// /// \return Pointer to the new socket /// //////////////////////////////////////////////////////////// CSFML_API sfSocketTCP* sfSocketTCP_Create(); //////////////////////////////////////////////////////////// /// Destroy an existing TCP socket /// /// \param Socket : Socket to destroy /// //////////////////////////////////////////////////////////// CSFML_API void sfSocketTCP_Destroy(sfSocketTCP* Socket); //////////////////////////////////////////////////////////// /// Connect a TCP socket to another computer on a specified port /// /// \param Socket : Socket to use for connecting /// \param Port : Port to use for transfers (warning : ports < 1024 are reserved) /// \param HostAddress : IP Address of the host to connect to /// /// \return sfTrue if operation has been successful /// //////////////////////////////////////////////////////////// CSFML_API sfBool sfSocketTCP_Connect(sfSocketTCP* Socket, unsigned short Port, sfIPAddress HostAddress); //////////////////////////////////////////////////////////// /// Listen to a specified port for incoming data or connections /// /// \param Socket : Socket to use for listening /// \param Port : Port to listen to /// /// \return sfTrue if operation has been successful /// //////////////////////////////////////////////////////////// CSFML_API sfBool sfSocketTCP_Listen(sfSocketTCP* Socket, unsigned short Port); //////////////////////////////////////////////////////////// /// Wait for a connection (must be listening to a port). /// This function is blocking, ie. it won't return before /// a connection has been accepted /// /// \param Socket : Socket to use for accepting /// \param Connected : Pointer to a socket pointer that will be filled with the connected client /// \param Address : Pointer to an address to fill with client infos /// /// \return Socket status /// //////////////////////////////////////////////////////////// CSFML_API sfSocketStatus sfSocketTCP_Accept(sfSocketTCP* Socket, sfSocketTCP** Connected, sfIPAddress* Address); //////////////////////////////////////////////////////////// /// Send an array of bytes to the host (must be connected first) /// /// \param Socket : Socket to use for sending /// \param Data : Pointer to the bytes to send /// \param Size : Number of bytes to send /// /// \return Socket status /// //////////////////////////////////////////////////////////// CSFML_API sfSocketStatus sfSocketTCP_Send(sfSocketTCP* Socket, const char* Data, size_t Size); //////////////////////////////////////////////////////////// /// Receive an array of bytes from the host (must be connected first) /// /// \param Socket : Socket to use for receiving /// \param Data : Pointer to a byte array to fill (make sure it is big enough) /// \param MaxSize : Maximum number of bytes to read /// \param SizeReceived : Number of bytes received /// /// \return Socket status /// //////////////////////////////////////////////////////////// CSFML_API sfSocketStatus sfSocketTCP_Receive(sfSocketTCP* Socket, char* Data, size_t MaxSize, size_t* SizeReceived); //////////////////////////////////////////////////////////// /// Send a packet of data to the host (must be connected first) /// /// \param Socket : Socket to use for sending /// \param Packet : Packet to send /// /// \return Socket status /// //////////////////////////////////////////////////////////// CSFML_API sfSocketStatus sfSocketTCP_SendPacket(sfSocketTCP* Socket, sfPacket* Packet); //////////////////////////////////////////////////////////// /// Receive a packet from the host (must be connected first) /// /// \param Socket : Socket to use for receiving /// \param Packet : Packet to fill with received data /// /// \return Socket status /// //////////////////////////////////////////////////////////// CSFML_API sfSocketStatus sfSocketTCP_ReceivePacket(sfSocketTCP* Socket, sfPacket* Packet); //////////////////////////////////////////////////////////// /// Check if a socket is in a valid state ; this function /// can be called any time to check if the socket is OK /// /// \param Socket : Socket to check /// /// \return True if the socket is valid /// //////////////////////////////////////////////////////////// CSFML_API sfBool sfSocketTCP_IsValid(sfSocketTCP* Socket); #endif // SFML_SOCKETTCP_H
mttkay/license_scout
lib/license_scout/reporter.rb
# # Copyright:: Copyright 2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # 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. # require "ffi_yajl" unless defined?(FFI_Yajl) require "terminal-table" require "license_scout/exceptions" module LicenseScout class Reporter class Result class << self def success(dependency) new(dependency, nil, true) end def failure(dependency, reason) new(dependency, reason, false) end end attr_reader :dependency attr_reader :reason def initialize(dependency, reason, did_succeed) @dependency = dependency @reason = reason @did_succeed = did_succeed end def <=>(other) dependency.path <=> other.dependency.path end def succeeded? @did_succeed end def dependency_string dependency.uid end def license_string dependency.license.records.map(&:id).compact.uniq.join(", ") end def reason_string case reason when :not_allowed "Not Allowed" when :flagged "Flagged" when :undetermined "Undetermined" when :missing "Missing" else "OK" end end end attr_reader :all_dependencies attr_reader :results attr_reader :dependency_license_manifest def initialize(all_dependencies) @all_dependencies = all_dependencies.sort @results = {} @did_fail = false @needs_fallback = false @needs_exception = false end def report generate_dependency_license_manifest save_manifest_file detect_problems evaluate_results end private def save_manifest_file LicenseScout::Log.info("[reporter] Writing dependency license manifest written to #{license_manifest_path}") File.open(license_manifest_path, "w+") do |file| file.print(FFI_Yajl::Encoder.encode(dependency_license_manifest, pretty: true)) end end def detect_problems LicenseScout::Log.info("[reporter] Analyzing dependency's license information against requirements") LicenseScout::Log.info("[reporter] Allowed licenses: #{LicenseScout::Config.allowed_licenses.join(", ")}") unless LicenseScout::Config.allowed_licenses.empty? LicenseScout::Log.info("[reporter] Flagged licenses: #{LicenseScout::Config.flagged_licenses.join(", ")}") unless LicenseScout::Config.flagged_licenses.empty? all_dependencies.each do |dependency| @results[dependency.type] ||= [] if dependency.license.records.empty? @results[dependency.type] << Result.failure(dependency, :missing) @did_fail = true @needs_fallback = true elsif dependency.license.undetermined? @results[dependency.type] << Result.failure(dependency, :undetermined) @did_fail = true @needs_fallback = true elsif !LicenseScout::Config.allowed_licenses.empty? && !dependency.license.is_allowed? unless dependency.has_exception? @results[dependency.type] << Result.failure(dependency, :not_allowed) @did_fail = true @needs_exception = true else @results[dependency.type] << Result.success(dependency) end elsif dependency.license.is_flagged? unless dependency.has_exception? @results[dependency.type] << Result.failure(dependency, :flagged) @did_fail = true @needs_exception = true else @results[dependency.type] << Result.success(dependency) end else @results[dependency.type] << Result.success(dependency) end end end def evaluate_results table = Terminal::Table.new table.headings = ["Type", "Dependency", "License(s)", "Results"] table.style = { border_bottom: false } # the extra :separator will add this results.each do |type, results_for_type| type_in_table = false results_for_type.each do |result| next if LicenseScout::Config.only_show_failures && result.succeeded? modified_row = [] modified_row << (type_in_table ? "" : type) modified_row << result.dependency_string modified_row << result.license_string modified_row << result.reason_string type_in_table = true table.add_row(modified_row) end table.add_separator if type_in_table end puts table unless LicenseScout::Config.only_show_failures && !@did_fail if @did_fail puts puts "Additional steps are required in order to pass Open Source license compliance:" puts " * Please add fallback licenses for the 'Missing' or 'Undetermined' dependencies" if @needs_fallback puts " https://github.com/chef/license_scout#fallback-licenses" if @needs_fallback puts " * Please add exceptions for the 'Flagged' or 'Not Allowed' dependencies" if @needs_exception puts " https://github.com/chef/license_scout#dependency-exceptions" if @needs_exception raise Exceptions::FailExit.new("missing or not allowed licenses detected") end end def generate_dependency_license_manifest @dependency_license_manifest = { license_manifest_version: 2, generated_on: DateTime.now.to_s, name: LicenseScout::Config.name, dependencies: [], } all_dependencies.each do |dep| dependency_license_manifest[:dependencies] << { type: dep.type, name: dep.name, version: dep.version, has_exception: dep.has_exception?, exception_reason: dep.exception_reason, licenses: dep.license.records.map(&:to_h), } end end def license_manifest_path File.join(LicenseScout::Config.output_directory, "#{LicenseScout::Config.name}-dependency-licenses.json") end end end
chinesemanbobo/PPMaker
PPMakerExample/PPTeemo/OtherDemoExamples(demos)/PPMakeTreeView/HBRoom.h
// // HBRoom.h // PPMakerExample // // Created by ╰莪呮想好好宠Nǐつ on 2018/8/7. // Copyright © 2018年 PPAbner. All rights reserved. // #import "PPMakeTreeItem.h" @interface HBRoom : PPMakeTreeItem @property(nonatomic,copy) NSString *roomTypeName; @property(nonatomic,copy) NSString *roomTypePrice; @end @interface HBHotel : PPMakeTreeItem @property(nonatomic,copy) NSString *hotelName; @end @interface HBRoomCell : UITableViewCell -(void)setupWithRoom:(HBRoom *)room; @end @interface HBHotelCell : UITableViewCell -(void)setupWithHotel:(HBHotel *)hotel; @end
leha-bot/eve
include/eve/module/real/core/function/regular/generic/binarize.hpp
<reponame>leha-bot/eve //================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/detail/implementation.hpp> #include <eve/logical.hpp> #include <eve/constant/one.hpp> #include <eve/constant/mone.hpp> #include <eve/constant/allbits.hpp> #include <eve/function/bit_and.hpp> #include <eve/function/if_else.hpp> #include <type_traits> #include <eve/concept/value.hpp> #include <eve/detail/apply_over.hpp> namespace eve::detail { template<real_value T> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , logical<T> const &cond ) noexcept { if constexpr(has_native_abi_v<T>) { return bit_and(one(eve::as<T>()),cond.bits()); } else return apply_over(binarize, cond); } template<real_value T, real_scalar_value U> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , logical<T> const &cond , U const & val ) noexcept { if constexpr(has_native_abi_v<T>) { return if_else(cond, val, zero); } else return apply_over(binarize, cond, val); } template<real_value T, real_scalar_value U> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , logical<T> const &cond , eve::as<U> const & ) noexcept { using R = eve::as_wide_t<U, eve::cardinal_t<T>>; return if_else(cond, one(as<R>()), zero); } template<real_scalar_value U> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , bool const &cond , eve::as<U> const & ) noexcept { using l_t = as_logical_t<U>; return binarize(l_t(cond)); } template<real_value T> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , logical<T> const &cond , callable_allbits_ const & ) noexcept { return cond.mask(); } template<real_value T> EVE_FORCEINLINE auto binarize_(EVE_SUPPORTS(cpu_) , logical<T> const &cond , callable_mone_ const & ) noexcept { if constexpr(integral_value<T>) return cond.mask(); else return eve::binarize(cond,mone(eve::as<value_type_t<T>>())); } }
liuluheng/CTCI
leetcode/remove_dup_list2.cc
//Given a sorted linked list, delete all nodes that have duplicate numbers, //leaving only distinct numbers //from the original list. //For example, //Given 1->2->3->3->4->4->5, return 1->2->5. //Given 1->1->1->2->3, return 2->3. // #include <iostream> using namespace std; struct listNode { listNode(int data = 0, listNode *next = nullptr) : data(data), next(next) {} int data; listNode *next; }; void print(listNode *head) { listNode *head2 = head; while (head2) { cout << head2->data; head2 = head2->next; } cout << endl; } listNode* removedup_recur(listNode *head) { if (!head || !head->next) { return head; } listNode *p = head->next; if (head->data == p->data) { while (p && p->data == head->data) { listNode *tmp = p; p = p->next; delete tmp; } delete head; return removedup_recur(p); } else { head->next = removedup_recur(head->next); return head; } } listNode* removedup(listNode *head) { if (!head) { return nullptr; } listNode dummy(-1); dummy.next = head; bool dup = false; for (listNode *prev = &dummy, *cur = prev->next; cur;) { while (cur->next && cur->data == cur->next->data) { dup = true; listNode *tmp = cur->next; delete cur; cur = tmp; } if (dup) { dup = false; prev->next = cur->next; delete cur; cur = prev->next; continue; } prev = cur; cur = cur->next; } return dummy.next; } void free_list(listNode *head) { listNode *orig; while (head) { orig = head; head = head->next; delete orig; } } int main() { listNode *head; //Given 1->2->3->3->4->4->5, return 1->2->5. head = new listNode(5); head = new listNode(4, head); head = new listNode(4, head); head = new listNode(3, head); head = new listNode(3, head); head = new listNode(2, head); head = new listNode(1, head); print(head); listNode *result = removedup_recur(head); print(result); free_list(result); // //Given 1->1->1->2->3, return 2->3. head = new listNode(3); head = new listNode(2, head); head = new listNode(1, head); head = new listNode(1, head); head = new listNode(1, head); print(head); result = removedup_recur(head); print(result); free_list(result); return 0; }
walkerrandolphsmith/apollo-gql-playground
services/app/src/shared/components/SignOut/SignOut.mutation.js
<filename>services/app/src/shared/components/SignOut/SignOut.mutation.js import gql from 'graphql-tag'; export default gql` mutation signOut { signOut } `;
yoniakabecky/kaori-menu
components/DraggableCard.js
<reponame>yoniakabecky/kaori-menu<gh_stars>0 import { useRouter } from "next/router"; import React from "react"; import { Draggable } from "react-beautiful-dnd"; import { makeStyles } from "@material-ui/core/styles"; import Grid from "@material-ui/core/Grid"; import IconButton from "@material-ui/core/IconButton"; import Paper from "@material-ui/core/Paper"; import Typography from "@material-ui/core/Typography"; import { downloadUrl } from "@@/utils/imageHandlers"; import DraggableIcon from "./Icons/DraggableIcon"; import EditIcon from "./Icons/EditIcon"; const useStyles = makeStyles((theme) => ({ root: { position: "relative", margin: "1rem auto", padding: "0.5rem 0", minHeight: "40px", }, name: { margin: "0 2.5rem", lineHeight: "24px", }, description: { marginTop: "0.5rem", padding: "0 1rem", color: "#828282", }, price: { padding: "0.25rem 1rem", fontWeight: 700, }, display: { padding: "0 1rem", }, image: { paddingRight: "1rem", textAlign: "right", "& img": { maxWidth: "85%", height: "100%", maxHeight: 80, borderRadius: 5, }, }, drag: { position: "absolute", top: "0.5rem", left: "0.5rem", }, edit: { position: "absolute", top: "0", right: "0.5rem", }, })); export default function DraggableCard({ type, ...props }) { const classes = useStyles(); const router = useRouter(); const [imageUrl, setImageUrl] = React.useState(null); const { id, description, price, image, askAvailability, display, name, index, } = props; React.useEffect(() => { if (image) { async function getImageUrl() { setImageUrl(await downloadUrl(image)); } getImageUrl(); } }, []); return ( <Draggable draggableId={id} index={index}> {(provided) => ( <Paper className={classes.root} ref={provided.innerRef} {...provided.draggableProps} > <span className={classes.drag} {...provided.dragHandleProps}> <DraggableIcon /> </span> <Typography variant="h3" className={classes.name}> {name} </Typography> <IconButton className={classes.edit} onClick={() => router.push(`/admin/${type}/${id}`)} > <EditIcon /> </IconButton> {description && ( <Typography variant="body1" className={classes.description}> {description} </Typography> )} {type === "item" && ( <Grid container> <Grid item xs={6} sm={8}> <Typography variant="body1" className={classes.price}> $ {price} </Typography> <Typography variant="body2" color="secondary" className={classes.display} > Display: {display ? "On" : "Off"} </Typography> <Typography variant="body2" color="secondary" className={classes.display} > Ask Server: {askAvailability ? "On" : "Off"} </Typography> </Grid> {image && imageUrl && ( <Grid item xs={6} sm={4} className={classes.image}> <img src={imageUrl} alt={name} /> </Grid> )} </Grid> )} </Paper> )} </Draggable> ); }
yerang823/landmark-detection
SBR/lib/config_utils/basic_args.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import os, sys, time, random, argparse def obtain_args(): parser = argparse.ArgumentParser(description='Train facial landmark detectors on 300-W or AFLW', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--train_lists', type=str, nargs='+', help='The list file path to the video training dataset.') parser.add_argument('--eval_vlists', type=str, nargs='+', help='The list file path to the video testing dataset.') parser.add_argument('--eval_ilists', type=str, nargs='+', help='The list file path to the image testing dataset.') parser.add_argument('--num_pts', type=int, help='Number of point.') parser.add_argument('--model_config', type=str, help='The path to the model configuration') parser.add_argument('--opt_config', type=str, help='The path to the optimizer configuration') # Data Generation parser.add_argument('--heatmap_type', type=str, choices=['gaussian','laplacian'], help='The method for generating the heatmap.') parser.add_argument('--data_indicator', type=str, default='300W-68',help='The method for generating the heatmap.') # Data Transform parser.add_argument('--pre_crop_expand', type=float, help='parameters for pre-crop expand ratio') parser.add_argument('--sigma', type=float, help='sigma distance for CPM.') parser.add_argument('--scale_prob', type=float, help='argument scale probability.') parser.add_argument('--scale_min', type=float, help='argument scale : minimum scale factor.') parser.add_argument('--scale_max', type=float, help='argument scale : maximum scale factor.') parser.add_argument('--scale_eval', type=float, help='argument scale : maximum scale factor.') parser.add_argument('--rotate_max', type=int, help='argument rotate : maximum rotate degree.') parser.add_argument('--crop_height', type=int, default=256, help='argument crop : crop height.') parser.add_argument('--crop_width', type=int, default=256, help='argument crop : crop width.') parser.add_argument('--crop_perturb_max', type=int, help='argument crop : center of maximum perturb distance.') parser.add_argument('--arg_flip', action='store_true', help='Using flip data argumentation or not ') # Optimization options parser.add_argument('--eval_once', action='store_true', help='evaluation only once for evaluation ') parser.add_argument('--error_bar', type=float, help='For drawing the image with large distance error.') parser.add_argument('--batch_size', type=int, default=2, help='Batch size for training.') # Checkpoints parser.add_argument('--print_freq', type=int, default=100, help='print frequency (default: 200)') parser.add_argument('--save_path', type=str, help='Folder to save checkpoints and log.') # Acceleration parser.add_argument('--workers', type=int, default=8, help='number of data loading workers (default: 2)') # Random Seed parser.add_argument('--rand_seed', type=int, help='manual seed') args = parser.parse_args() if args.rand_seed is None: args.rand_seed = random.randint(1, 100000) assert args.save_path is not None, 'save-path argument can not be None' #state = {k: v for k, v in args._get_kwargs()} #Arguments = namedtuple('Arguments', ' '.join(state.keys())) #arguments = Arguments(**state) return args
fiware-austria/fiware-idm
routes/web/organizations.js
const express = require('express'); const router = express.Router(); const multer = require('multer'); const path = require('path'); const uuid = require('uuid'); const csrf = require('csurf'); const csrf_protection = csrf({ cookie: true }); const fs = require('fs'); // Home web Controller const web_org_controller = require('../../controllers/web/index').organizations; const web_auth_org_controller = require('../../controllers/web/index') .authorize_org_apps; const web_man_memb_controller = require('../../controllers/web/index') .manage_members; // Autoloads router.param('organization_id', web_org_controller.load_organization); // Route to save images of applications const image_org_upload = multer.diskStorage({ destination(req, file, callback) { if (!fs.existsSync('./public/img/organizations/')) { fs.mkdirSync('./public/img/organizations/'); } callback(null, './public/img/organizations/'); }, filename(req, file, callback) { callback(null, uuid.v4() + path.extname(file.originalname)); }, }); // Routes for organziations router.get( '/available', csrf_protection, web_auth_org_controller.available_organizations ); router.get('/', csrf_protection, web_org_controller.index); router.get('/filtered', csrf_protection, web_org_controller.filter); router.get('/new', csrf_protection, web_org_controller.new); router.post('/', csrf_protection, web_org_controller.create); router.get('/:organization_id', csrf_protection, web_org_controller.show); router.get( '/:organization_id/members', csrf_protection, web_org_controller.get_members ); router.get( '/:organization_id/applications', csrf_protection, web_org_controller.get_applications ); router.get( '/:organization_id/edit', web_org_controller.owned_permissions, csrf_protection, web_org_controller.edit ); router.put( '/:organization_id/edit/avatar', web_org_controller.owned_permissions, multer({ storage: image_org_upload }).single('image'), csrf_protection, web_org_controller.update_avatar ); router.put( '/:organization_id/edit/info', web_org_controller.owned_permissions, csrf_protection, web_org_controller.update_info ); router.delete( '/:organization_id/edit/delete_avatar', web_org_controller.owned_permissions, csrf_protection, web_org_controller.delete_avatar ); router.delete( '/:organization_id', web_org_controller.owned_permissions, csrf_protection, web_org_controller.destroy ); router.delete( '/:organization_id/remove', csrf_protection, web_org_controller.remove ); // Routes to manage members in organizations router.get( '/:organization_id/edit/members', web_org_controller.owned_permissions, csrf_protection, web_man_memb_controller.get_members ); router.post( '/:organization_id/edit/members', web_org_controller.owned_permissions, csrf_protection, web_man_memb_controller.add_members ); module.exports = router;
klenkes74/egress-ip-operator
pkg/cloudprovider/aws_provider/aws_cloudprovider_assign_specified_ip_test.go
/* * Copyright 2020 Kaiserpfalz EDV-Service, <NAME>. * * 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 aws_provider_test import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "net" "strconv" ) var _ = Describe("AssignSpecifiedIP", func() { BeforeEach(func() { initMock() }) AfterEach(func() { mockCtrl.Finish() }) It("should add a specified ip when ip is unused", func() { awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( createDescribeInstancesOutput(hostName, hostId, networkInterfaceId, mainIP, []*net.IP{}), nil, ) allowReassignement := false awsDirect. EXPECT().AssignPrivateIpAddresses(&ec2.AssignPrivateIpAddressesInput{ AllowReassignment: &allowReassignement, NetworkInterfaceId: aws.String(networkInterfaceId), PrivateIpAddresses: aws.StringSlice([]string{ip.String()}), }). Return( &ec2.AssignPrivateIpAddressesOutput{ AssignedPrivateIpAddresses: []*ec2.AssignedPrivateIpAddress{ { PrivateIpAddress: aws.String(ip.String()), }, }, NetworkInterfaceId: aws.String(networkInterfaceId), }, nil, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(BeNil()) }) It("should throw an error when specified ip is already used", func() { expectedErr := fmt.Errorf("instance '%v' has already a secondary ip '%v' - can not add it again", hostId, ip.String()) secondaryIPs := make([]*net.IP, 1) secondaryIPs[0] = ip awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( createDescribeInstancesOutput(hostName, hostId, networkInterfaceId, mainIP, secondaryIPs), nil, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(MatchError(expectedErr)) }) It("should return an error when cloud instance can't be found", func() { expectedErr := fmt.Errorf("host '%v' not found", hostName) awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( nil, expectedErr, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(MatchError(expectedErr)) }) It("should return failure when specified ip is already used", func() { awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( createDescribeInstancesOutput(hostName, hostId, networkInterfaceId, mainIP, []*net.IP{}), nil, ) expectedErr := fmt.Errorf("ip '%v' already in use", ip) allowReassignement := false awsDirect. EXPECT().AssignPrivateIpAddresses(&ec2.AssignPrivateIpAddressesInput{ AllowReassignment: &allowReassignement, NetworkInterfaceId: aws.String(networkInterfaceId), PrivateIpAddresses: aws.StringSlice([]string{ip.String()}), }). Return( nil, expectedErr, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(MatchError(expectedErr)) }) It("should return an error when cloud instance has already too many IPs", func() { expectedErr := fmt.Errorf("instance '%v' has already %v IP addresses - maximum of %v reached", hostId, maxIPsPerInstance, maxIPsPerInstance) secondaryIPs := make([]*net.IP, sut.MaxIPsPerInstance-1) for i := 0; i < sut.MaxIPsPerInstance-1; i++ { s := strconv.Itoa(20 + i) ip := net.ParseIP("10.0.1." + s) secondaryIPs[i] = &ip } awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( createDescribeInstancesOutput(hostName, hostId, networkInterfaceId, mainIP, secondaryIPs), nil, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(MatchError(expectedErr)) }) It("should return an error when cloud instance has no interface", func() { expectedErr := fmt.Errorf("instance '%v' has no network interface", hostId) awsDirect. EXPECT().DescribeInstances(createDescribeInstancesInput(hostName)). Return( createDescribeInstancesOutput(hostName, hostId, "", mainIP, []*net.IP{}), nil, ) err := sut.AddSpecifiedIP(ip, hostName) Expect(err).To(MatchError(expectedErr)) }) })
cancervariants/variant-normalization
tests/tokenizers/test_genomic_insertion.py
<reponame>cancervariants/variant-normalization """A module for testing Genomic Insertion Tokenization.""" import unittest from variation.tokenizers import GenomicInsertion from .tokenizer_base import TokenizerBase from variation.tokenizers.caches import AminoAcidCache, NucleotideCache class TestGenomicInsertionTokenizer(TokenizerBase, unittest.TestCase): """A class for testing Genomic Insertion Tokenization.""" def tokenizer_instance(self): """Return Genomic Insertion instance.""" return GenomicInsertion(AminoAcidCache(), NucleotideCache()) def token_type(self): """Return genomic insertion token type.""" return 'GenomicInsertion' def fixture_name(self): """Return the fixture name for Genomic Insertion.""" return 'genomic_insertion'
sigurasg/ghidra
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/actions/AbstractMarkupItemAction.java
<filename>Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/gui/actions/AbstractMarkupItemAction.java /* ### * IP: GHIDRA * * 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 ghidra.feature.vt.gui.actions; import ghidra.feature.vt.api.main.*; import ghidra.feature.vt.gui.plugin.VTController; import ghidra.feature.vt.gui.plugin.VTPlugin; import ghidra.feature.vt.gui.task.ApplyMarkupItemTask; import ghidra.framework.options.ToolOptions; import ghidra.program.model.address.Address; import ghidra.util.task.Task; import ghidra.util.task.TaskListener; import java.util.List; import docking.ActionContext; import docking.action.DockingAction; public abstract class AbstractMarkupItemAction extends DockingAction { final VTController controller; AbstractMarkupItemAction(VTController controller, String actionName) { super(actionName, VTPlugin.OWNER); this.controller = controller; } abstract VTMarkupItemApplyActionType getActionType(); abstract ToolOptions getApplyOptions(); @Override public void actionPerformed(ActionContext context) { List<VTMarkupItem> markupItems = controller.getMarkupItems(context); ApplyMarkupItemTask task = createApplyTask(controller.getSession(), markupItems, getApplyOptions()); task.addTaskListener(new TaskListener() { @Override public void taskCompleted(Task t) { controller.refresh(); } @Override public void taskCancelled(Task t) { // don't care; nothing to do } }); controller.runVTTask(task); } protected ApplyMarkupItemTask createApplyTask(VTSession session, List<VTMarkupItem> markupItems, ToolOptions options) { return new ApplyMarkupItemTask(session, markupItems, options); } @Override public boolean isEnabledForContext(ActionContext context) { List<VTMarkupItem> markupItems = controller.getMarkupItems(context); if (markupItems.size() == 0) { return false; } for (VTMarkupItem markupItem : markupItems) { if (!markupItem.canApply()) { return false; } if (!markupItem.supportsApplyAction(getActionType())) { return false; // disabled if any of the items do not support our action type } Address address = markupItem.getDestinationAddress(); if (address == null || address == Address.NO_ADDRESS) { return false; // disabled if we don't have an address to apply to } } return true; } @Override public boolean isAddToPopup(ActionContext context) { List<VTMarkupItem> markupItems = controller.getMarkupItems(context); if (markupItems.size() == 0) { return false; } for (VTMarkupItem markupItem : markupItems) { if (!markupItem.canApply()) { return false; } if (!markupItem.supportsApplyAction(getActionType())) { return false; // disabled if any of the items do not support our action type } } return true; } }
nodefony/nodefony-core
src/nodefony/cli/builder/microService/skeletons/src/browser/index.js
const nodefony = require("nodefony-client"); import "./index.css"; /* * Class */ class App extends nodefony.Service { constructor() { super("App"); this.initSyslog(); this.log("INIT APP CLIENT"); this.log(`Nodefony Client version : ${nodefony.version}`); } } export default new App();
cellog/unlock
unlock-js/src/v11/purchaseKey.js
<reponame>cellog/unlock import utils from '../utils' import { GAS_AMOUNTS } from '../constants' import TransactionTypes from '../transactionTypes' import Errors from '../errors' import { approveTransfer } from '../erc20' /** * Purchase a key to a lock by account. * The key object is passed so we can kepe track of it from the application * The lock object is required to get the price data * We pass both the owner and the account because at some point, these may be different (someone * purchases a key for someone else) * @param {PropTypes.address} lock * @param {PropTypes.address} owner * @param {string} keyPrice * @param {string} data * @param {string} account */ export default async function( lockAddress, owner, keyPrice, account, data, erc20Address ) { const lockContract = await this.getLockContract(lockAddress) // TODO, use the actual decimals from the contract. We assume 18 here because it is the most frequent default. const actualAmount = utils.toDecimal(keyPrice, 18) const purchaseForOptions = { gasLimit: GAS_AMOUNTS.purchaseFor, // overrides default value for transaction gas price } if (erc20Address) { await approveTransfer( erc20Address, lockAddress, actualAmount, this.provider ) } else { purchaseForOptions.value = actualAmount } let transactionPromise try { transactionPromise = lockContract['purchaseFor(address)']( owner, purchaseForOptions ) const ret = await this._handleMethodCall( transactionPromise, TransactionTypes.KEY_PURCHASE ) return ret } catch (error) { this.emit('error', new Error(Errors.FAILED_TO_PURCHASE_KEY)) } }
tradecraftio/tradecraft
src/zmq/zmqnotificationinterface.h
<filename>src/zmq/zmqnotificationinterface.h // Copyright (c) 2015-2018 The Bitcoin Core developers // Copyright (c) 2011-2021 The Freicoin Developers // // This program is free software: you can redistribute it and/or modify it under // the terms of version 3 of the GNU Affero General Public License as published // by the Free Software Foundation. // // 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 Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef FREICOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H #define FREICOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H #include <validationinterface.h> #include <string> #include <map> #include <list> class CBlockIndex; class CZMQAbstractNotifier; class CZMQNotificationInterface final : public CValidationInterface { public: virtual ~CZMQNotificationInterface(); std::list<const CZMQAbstractNotifier*> GetActiveNotifiers() const; static CZMQNotificationInterface* Create(); protected: bool Initialize(); void Shutdown(); // CValidationInterface void TransactionAddedToMempool(const CTransactionRef& tx) override; void BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindexConnected, const std::vector<CTransactionRef>& vtxConflicted) override; void BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) override; void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; private: CZMQNotificationInterface(); void *pcontext; std::list<CZMQAbstractNotifier*> notifiers; }; extern CZMQNotificationInterface* g_zmq_notification_interface; #endif // FREICOIN_ZMQ_ZMQNOTIFICATIONINTERFACE_H
darkice1/hydrogen-ssdb
src/main/java/com/hyd/ssdb/AbstractClient.java
package com.hyd.ssdb; import com.hyd.ssdb.conf.*; import com.hyd.ssdb.conn.*; import com.hyd.ssdb.protocol.*; import com.hyd.ssdb.util.IdScore; import com.hyd.ssdb.util.KeyValue; import java.util.*; import org.slf4j.LoggerFactory; /** * 实现 SsdbClient 的一些底层方法 * * @author Yiding */ @SuppressWarnings("WeakerAccess") public abstract class AbstractClient { static final org.slf4j.Logger LOG = LoggerFactory.getLogger(AbstractClient.class); /** * 管理所有的 SSDB 连接 */ private ConnectionPoolManager connectionPoolManager; ////////////////////////////////////////////////////////////// public AbstractClient(Sharding sharding) { this.connectionPoolManager = new ConnectionPoolManager(sharding); } /** * 获取负载均衡策略(可用于在运行时变更配置) * * @return 负载均衡策略对象 */ public Sharding getSharding() { return this.connectionPoolManager.getSharding(); } /** * 发送一整条命令,例如 "set key1 value1" * * @param command 一整条命令 * * @return 执行结果 */ public Response sendRequest(String command) { return sendRequest(new Request(command)); } public Response sendRequest(Server server, String command) { Request request = new Request(command); request.setForceServer(server); return sendRequest(request); } /** * 发送包含写入操作的命令,每个参数为命令的一部分,例如 "set", "key1", "value1" * * @param tokens 命令中的各个部分 * * @return 执行结果 */ public Response sendWriteRequest(Object... tokens) { return sendRequest(new WriteRequest(tokens)); } /** * 发送命令,每个参数为命令的一部分,例如 "set", "key1", "value1" * * @param tokens 命令中的各个部分 * * @return 执行结果 */ public Response sendRequest(Object... tokens) { return sendRequest(new Request(tokens)); } /** * 发送一个命令 * * @param request 命令对象 * * @return 执行结果 */ public Response sendRequest(Request request) { boolean needResend; Response response = null; // 这是一个在失败时重新发送请求的循环。 // 发送请求会遇到下面几种失败情况,分别有对应的 catch 块: // 1、无法获得 Connection,这时候会遇到 SsdbNoServerAvailableException 异常,直接抛出; // 2、能够获得 Connection,但执行收发时出错,这时候会遇到 // SsdbSocketFailedException 异常,需要标记服务器为不可用,并重新尝试循环; // 3、执行收发完成,但服务器返回的是错误信息,这时候会遇到 SsdbServerException 异常,直接抛出。 // 4、其他 SsdbException 或 Exception 异常,表示代码逻辑可能存在问题,直接抛出或包装后抛出。 do { PoolAndConnection poolAndConnection = connectionPoolManager.getConnection(request); ConnectionPool connectionPool = null; Connection connection = null; try { connectionPool = poolAndConnection.getConnectionPool(); connection = poolAndConnection.getConnection(); if (LOG.isDebugEnabled()) { LOG.debug("choose server " + connection.getHost() + ":" + connection.getPort()); } response = sendRequest(request, connection); needResend = false; } catch (SsdbNoServerAvailableException | SsdbServerException e) { throw e; } catch (SsdbClientException e) { LOG.error("Connection error", e); // 标记不可用的服务器,这样下次循环就会切换到其他服务器了 if (connection != null) { connectionPoolManager.reportInvalidConnection(connection); } needResend = true; } catch (SsdbException e) { throw e; } catch (Exception e) { throw new SsdbException(e); } finally { if (connection != null) { connectionPool.returnObject(connection); // 把连接返回给连接池 } } } while (needResend); return response; } protected List<Response> sendRequestToAll(Object... tokens) { return sendRequestToAll(new Request(tokens)); } protected List<Response> sendRequestToAll(Request request) { List<PoolAndConnection> pacList = connectionPoolManager.getAllConnections(request); List<Response> responseList = new ArrayList<>(); for (PoolAndConnection pac : pacList) { Connection connection = pac.getConnection(); try { responseList.add(sendRequest(request, connection)); } finally { pac.getConnectionPool().returnObject(connection); } } return responseList; } // 发送一个命令,但不会把连接返回给连接池(内部使用) private static Response sendRequest(Request request, Connection connection) { try { connection.send(request.toBytes()); Response response = connection.receivePacket(); checkResponse(request.getHeader().toString(), response); return response; } catch (SsdbException e) { throw e; } catch (Exception e) { throw new SsdbException(e); } } // 检查服务器回应,如果是错误回应则抛出一个异常 private static void checkResponse(String requestHeader, Response response) { String header = response.getHead().toString(); LOG.debug("RESPONSE(" + requestHeader + "): [" + header + "] - (" + response.getBody().size() + " blocks)"); if (!(header.equals("ok") || header.equals("not_found"))) { SsdbException e = new SsdbException("Server return error: '" + header + "'"); e.setServerErrorCode(header); throw e; } } /** * 将 token 插入到 parameters 的第一位,生成一个新的数组 * * @param token 要插入的内容 * @param parameterList 参数 * * @return 新生成的数组 */ protected String[] prependCommand(String token, List<String> parameterList) { String[] parameters = parameterList.toArray(new String[0]); String[] command = new String[parameters.length + 1]; command[0] = token; System.arraycopy(parameters, 0, command, 1, parameters.length); return command; } /** * 将 token 插入到 parameters 的第一位,生成一个新的数组 * * @param token 要插入的内容 * @param parameters 参数 * * @return 新生成的数组 */ protected String[] prependCommand(String token, String[] parameters) { String[] command = new String[parameters.length + 1]; command[0] = token; System.arraycopy(parameters, 0, command, 1, parameters.length); return command; } /** * 将两个 token 插入到 parameters 的第一位,生成一个新的数组 * * @param token1 要插入的内容 * @param token2 要插入的内容 * @param parameters 参数 * * @return 新生成的数组 */ protected String[] prependCommand(String token1, String token2, String[] parameters) { String[] command = new String[parameters.length + 2]; command[0] = token1; command[1] = token2; System.arraycopy(parameters, 0, command, 2, parameters.length); return command; } // 将 token1,token2 和 parameters 组合成一个字符串数组 protected String[] prependCommand(String token1, String token2, List<String> parameters) { return prependCommand(token1, token2, parameters.toArray(new String[0])); } // 将 token1,token2 和 keyValues 组合成一个字符串数组 protected String[] prependCommandKeyValue(String token1, String token2, List<KeyValue> keyValues) { String[] command = new String[keyValues.size() * 2 + 2]; command[0] = token1; command[1] = token2; for (int i = 0; i < keyValues.size(); i++) { KeyValue keyValue = keyValues.get(i); command[i * 2 + 2] = keyValue.getKey(); command[i * 2 + 3] = keyValue.getValue(); } return command; } // 将 token1,token2 和 idScores 组合成一个字符串数组 protected String[] prependCommandIdScore(String token1, String token2, List<IdScore> idScores) { String[] command = new String[idScores.size() * 2 + 2]; command[0] = token1; command[1] = token2; for (int i = 0; i < idScores.size(); i++) { IdScore idScore = idScores.get(i); command[i * 2 + 2] = idScore.getId(); command[i * 2 + 3] = String.valueOf(idScore.getScore()); } return command; } /** * 关闭 SSDB 客户端 */ public void close() { this.connectionPoolManager.close(); } /** * 根据 Sharding 对 key 列表进行分组 * * @param keys 要进行分组的 key 列表 * * @return 分组结果 */ protected List<String[]> splitKeys(String[] keys) { // {clusterId -> List<key>} Map<String, List<String>> groups = new HashMap<>(); for (String key : keys) { Cluster cluster = getSharding().getClusterByKey(key); String clusterId = cluster.getId(); if (!groups.containsKey(clusterId)) { groups.put(clusterId, new ArrayList<>()); } groups.get(clusterId).add(key); } ArrayList<String[]> result = new ArrayList<>(); for (List<String> keyList : groups.values()) { result.add(keyList.toArray(new String[0])); } return result; } protected List<String[]> splitKeys(List<String> keys) { return splitKeys(keys.toArray(new String[0])); } protected List<String[]> splitKeyValues(String[] keyValues) { // {clusterId -> List<key,value,...>} Map<String, List<String>> groups = new HashMap<>(); for (int i = 0; i < keyValues.length; i += 2) { String key = keyValues[i]; String value = keyValues[i + 1]; Cluster cluster = getSharding().getClusterByKey(key); String clusterId = cluster.getId(); if (!groups.containsKey(clusterId)) { groups.put(clusterId, new ArrayList<>()); } groups.get(clusterId).add(key); groups.get(clusterId).add(value); } ArrayList<String[]> result = new ArrayList<>(); for (List<String> keyList : groups.values()) { result.add(keyList.toArray(new String[0])); } return result; } protected List<List<KeyValue>> splitKeyValues(List<KeyValue> keyValues) { // {clusterId -> List<key,value,...>} Map<String, List<KeyValue>> groups = new HashMap<>(); for (KeyValue keyValue : keyValues) { String key = keyValue.getKey(); Cluster cluster = getSharding().getClusterByKey(key); String clusterId = cluster.getId(); if (!groups.containsKey(clusterId)) { groups.put(clusterId, new ArrayList<>()); } groups.get(clusterId).add(keyValue); } return new ArrayList<>(groups.values()); } protected List<String> combineBlocks(List<Response> responseList) { List<String> result = new ArrayList<>(); for (Response response : responseList) { result.addAll(response.getBlocks()); } return result; } protected List<KeyValue> combineKeyValues(List<Response> responseList) { List<KeyValue> result = new ArrayList<>(); for (Response response : responseList) { result.addAll(response.getKeyValues()); } return result; } }
ProfessorDey/lbry-app
flow-typed/render-media.js
declare module 'render-media' { declare module.exports: any; }
scrumsnail/BossZP
BossZP/BossZP/Classes/General/Categories/NSDictionary+Json.h
// // NSDictionary+Json.h // BossZP // // Created by allthings_LuYD on 16/9/7. // Copyright © 2016年 scrum_snail. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (Json) - (NSInteger)jsonInteger:(NSString *)key; @end
liammews/Briefrr
studio/node_modules/@sanity/base/lib/theme/helpers.js
<reponame>liammews/Briefrr "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._buildTints = _buildTints; exports._toHex = _toHex; exports._isDark = _isDark; exports._multiply = _multiply; exports._screen = _screen; var _ui = require("@sanity/ui"); var _polished = require("polished"); /** * @internal */ function _buildTints(bg, mid, fg) { return { 50: (0, _polished.mix)(0.1, mid, bg), 100: (0, _polished.mix)(0.2, mid, bg), 200: (0, _polished.mix)(0.4, mid, bg), 300: (0, _polished.mix)(0.6, mid, bg), 400: (0, _polished.mix)(0.8, mid, bg), 500: mid, 600: (0, _polished.mix)(0.8, mid, fg), 700: (0, _polished.mix)(0.6, mid, fg), 800: (0, _polished.mix)(0.4, mid, fg), 900: (0, _polished.mix)(0.2, mid, fg), 950: (0, _polished.mix)(0.1, mid, fg) }; } /** * @internal */ function _toHex(color) { var _parseToRgb = (0, _polished.parseToRgb)(color), red = _parseToRgb.red, green = _parseToRgb.green, blue = _parseToRgb.blue; return (0, _polished.rgb)(red, green, blue); } /** * @internal */ function _isDark(bg, fg) { return (0, _polished.getLuminance)(bg) < (0, _polished.getLuminance)(fg); } /** * Blend two colors using the "screen" blend mode * @internal */ function _multiply(bg, fg) { var b = (0, _ui.parseColor)(bg); var s = (0, _ui.parseColor)(fg); var hex = (0, _ui.rgbToHex)((0, _ui.multiply)(b, s)); return hex; } /** * Blend two colors using the "screen" blend mode * @internal */ function _screen(bg, fg) { var b = (0, _ui.parseColor)(bg); var s = (0, _ui.parseColor)(fg); var hex = (0, _ui.rgbToHex)((0, _ui.screen)(b, s)); return hex; }
lklima/constru-app
src/components/Header/index.js
<filename>src/components/Header/index.js import React from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { styles } from './styles'; const Header = ({ title, navigation }) => ( <View style={styles.container}> <TouchableOpacity onPress={() => navigation.goBack()}> <Icon name="arrow-back" size={30} color="white" /> </TouchableOpacity> <Text style={styles.title}>{title}</Text> <View /> </View> ); export default Header;