repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
kirbo/slacky
src/container/Loading/Loading.js
<reponame>kirbo/slacky<filename>src/container/Loading/Loading.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { COLOR, DIMENSION, GlobalStyles, FONT_SIZE } from '../../assets/css'; import Logo from '../../component/Logo'; /** * Loading */ class Loading extends Component { state = { }; /** * ComponentDidMount */ componentDidMount = () => { setTimeout(() => { document.querySelector('.loading').classList.remove('hidden'); }, 250); } /** * ComponentWillReceiveProps * @param {object} props - Properties for the component. * @param {object} state - State of the component. * @returns {object} state */ componentWillReceiveProps = ({ slackInstancesLoaded, configurationsLoaded, appConfigurationsLoaded, setProperty }, state) => { if (slackInstancesLoaded && configurationsLoaded && appConfigurationsLoaded) { document.querySelector('.loading').classList.add('loaded'); setTimeout(() => { setProperty({ hideLoading: true, }); }, 400); setTimeout(() => { setProperty({ showLoading: false, }); }, 1500); } return state; } /** * Duh. */ render = () => { const { hideLoading } = this.props; return ( <> <GlobalStyles /> <Styled hideLoading={hideLoading}> <Layout> <div className="container"> <Logo withText /> <div className="loading hidden"> Loading, please standby... </div> </div> </Layout> </Styled> </> ); } } Loading.defaultProps = { appConfigurationsLoaded: false, }; Loading.propTypes = { slackInstancesLoaded: PropTypes.bool.isRequired, configurationsLoaded: PropTypes.bool.isRequired, appConfigurationsLoaded: PropTypes.bool, hideLoading: PropTypes.bool.isRequired, setProperty: PropTypes.func.isRequired, }; const Styled = styled.div` position: absolute; z-index: 1000; font-size: ${FONT_SIZE.m}; color: ${COLOR.black}; font-family: arial; display: flex; height: 100vh; width: 100vw; top: 0; left: 0; align-items: center; justify-content: center; background: radial-gradient(${COLOR.darkBlue}, ${COLOR.black}); transition: all 0.5s ease; z-index: 10000; opacity: ${({ hideLoading }) => (hideLoading ? 0 : 1)}; & div.logo { height: ${DIMENSION['10x']}; min-height: ${DIMENSION['10x']}; max-height: ${DIMENSION['10x']}; width: 20rem; min-width: 20rem; max-width: 20rem; display: flex; align-items: center; justify-content: center; & svg.logo-text { fill: ${COLOR.white}; } } `; const Layout = styled.div` display: flex; flex: 1; & .container { position: relative; width: 100%; justify-content: center; display: flex; } & .loading { color: ${COLOR.lightGray}; opacity: 1; height: ${DIMENSION['1.5x']}; top: calc(50% - ${DIMENSION['1.5x']}/2 + ${DIMENSION['4x']}); transition: all 0.25s ease; position: absolute; margin-left: 0; &.hidden { opacity: 0; margin-left: -10rem; } &.loaded { opacity: 0; margin-left: 10rem; } } `; export default Loading;
niranjan21/skt
app/controllers/general-item-outward-entries.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), GeneralItemOutwardEntry = mongoose.model('GeneralItemOutwardEntry'), _ = require('lodash'); /** * Create a General item outward entry */ exports.create = function(req, res) { var generalItemOutwardEntry = new GeneralItemOutwardEntry(req.body); generalItemOutwardEntry.user = req.user; generalItemOutwardEntry.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(generalItemOutwardEntry); } }); }; /** * Show the current General item outward entry */ exports.read = function(req, res) { res.jsonp(req.generalItemOutwardEntry); }; /** * Update a General item outward entry */ exports.update = function(req, res) { var generalItemOutwardEntry = req.generalItemOutwardEntry ; generalItemOutwardEntry = _.extend(generalItemOutwardEntry , req.body); generalItemOutwardEntry.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(generalItemOutwardEntry); } }); }; /** * Delete an General item outward entry */ exports.delete = function(req, res) { var generalItemOutwardEntry = req.generalItemOutwardEntry ; generalItemOutwardEntry.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(generalItemOutwardEntry); } }); }; /** * List of General item outward entries */ exports.list = function(req, res) { GeneralItemOutwardEntry.find().sort('-created').populate('user', 'displayName').exec(function(err, generalItemOutwardEntries) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(generalItemOutwardEntries); } }); }; /** * General item outward entry middleware */ exports.generalItemOutwardEntryByID = function(req, res, next, id) { GeneralItemOutwardEntry.findById(id).populate('user', 'displayName').exec(function(err, generalItemOutwardEntry) { if (err) return next(err); if (! generalItemOutwardEntry) return next(new Error('Failed to load General item outward entry ' + id)); req.generalItemOutwardEntry = generalItemOutwardEntry ; next(); }); }; /** * General item outward entry authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.generalItemOutwardEntry.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
karstensensensen/AsciiRender
src/Asciir/Math/Matrix.h
<filename>src/Asciir/Math/Matrix.h<gh_stars>1-10 #pragma once #include "Vertices.h" namespace Asciir { // A wrapper for MatrixX that overloads functions like size() to return Asciir types instead of Eigen types. template<typename T> struct arMatrix : public Eigen::MatrixX<T> { using Eigen::MatrixX<T>::MatrixX; arMatrix(Size2D size); template<typename TOther> arMatrix(const arMatrix<TOther>& other); // constructor for eigen generic expressions template<typename TOther> arMatrix(const Eigen::MatrixBase<TOther>& other); Size2D size() const; void resize(Size2D size); T& operator[](size_t indx); T operator[](size_t indx) const; T& operator()(Size2D coord) { return get(coord); } T operator()(Size2D coord) const { return get(coord); } T& operator()(size_t x, size_t y) { return get(x, y); } T operator()(size_t x, size_t y) const { return get(x, y); } T& get(Size2D coord); T get(Size2D coord) const; T& get(size_t x, size_t y); T get(size_t x, size_t y) const; }; template<typename T, size_t w, size_t h> struct s_arMatrix : public Eigen::MatrixX<T> { using Eigen::Matrix<T, w, h>::MatrixX; template<typename TOther> s_arMatrix(const s_arMatrix<TOther, w, h>& other); // constructor for eigen generic expressions template<typename TOther> s_arMatrix(const Eigen::EigenBase<TOther>& other); template<typename TOther> s_arMatrix(const Eigen::ReturnByValue<TOther>& other); static Size2D size(); s_arMatrix<T, w, h> operator=(const s_arMatrix<T, w, h>& other); T& operator[](size_t indx); T operator[](size_t indx) const; T& operator()(Size2D coord) { return get(coord); } T operator()(Size2D coord) const { return get(coord); } T& operator()(size_t x, size_t y) { return get(x, y); } T operator()(size_t x, size_t y) const { return get(x, y); } T& get(Size2D coord); T get(Size2D coord) const; T& get(size_t x, size_t y); T get(size_t x, size_t y) const; }; // typedef / using / variables for Eigen::Matrix // s_ = static size template<typename T> static const arMatrix<T> arMatrix2 = arMatrix<T>(2, 2); template<typename T> static const arMatrix<T> arMatrix3 = arMatrix<T>(3, 3); template<typename T> static const arMatrix<T> arMatrix4 = arMatrix<T>(4, 4); template<typename T> using s_arMatrix2 = s_arMatrix<T, 2, 2>; template<typename T> using s_arMatrix3 = s_arMatrix<T, 3, 3>; template<typename T> using s_arMatrix4 = s_arMatrix<T, 4, 4>; } #include "Matrix.ipp"
Zhitao-Li/clMagma
control/trace.h
<gh_stars>0 /* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date @author <NAME> */ #ifndef TRACE_H #define TRACE_H // has MagmaMaxGPUs, strlcpy, max #include "common_magma.h" // ---------------------------------------- const int MAX_CORES = 1; // CPU cores const int MAX_GPU_QUEUES = MagmaMaxGPUs * 4; // #devices * #queues per device const int MAX_EVENTS = 20000; const int MAX_LABEL_LEN = 16; // ---------------------------------------- #ifdef TRACING void trace_init ( int ncore, int ngpu, int nqueue, magma_queue_t *queues ); void trace_cpu_start( int core, const char* tag, const char* label ); void trace_cpu_end ( int core ); magma_event_t* trace_gpu_event( int dev, int queue_num, const char* tag, const char* label ); void trace_gpu_start( int dev, int queue_num, const char* tag, const char* label ); void trace_gpu_end ( int dev, int queue_num ); void trace_finalize ( const char* filename, const char* cssfile ); #else #define trace_init( x1, x2, x3, x4 ) ((void)(0)) #define trace_cpu_start( x1, x2, x3 ) ((void)(0)) #define trace_cpu_end( x1 ) ((void)(0)) #define trace_gpu_event( x1, x2, x3, x4 ) (NULL) #define trace_gpu_start( x1, x2, x3, x4 ) ((void)(0)) #define trace_gpu_end( x1, x2 ) ((void)(0)) #define trace_finalize( x1, x2 ) ((void)(0)) #endif #endif // #ifndef TRACE_H
Holaplace/path_to_python
9-1.py
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('The restaurant name is ' + self.restaurant_name.title() + ', and the cuisine type is ' + self.cuisine_type.title()) def open_restaurant(self): print(self.restaurant_name.title() + ' is opening.') res = Restaurant('me', 'chinese') res.describe_restaurant() res.open_restaurant()
iqianxing/ant-design-charts
config/jest.js
const BaseJestConfig = { verbose: true, runner: 'jest-electron/runner', testEnvironment: 'jest-electron/environment', testTimeout: 30000, setupFilesAfterEnv: ['jest-extended'], transform: { '^.+\\.(tsx|ts)?$': 'ts-jest', '\\.(less|css)$': 'jest-less-loader', }, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], collectCoverage: false, collectCoverageFrom: ['packages/**/*.ts', '!**/node_modules/**'], testRegex: '/tests/.*-spec\\.tsx|\\.(t|j)s?$', }; module.exports = { BaseJestConfig };
lingnand/Helium
src/srchilite/regexrulefactory.cpp
// // Author: <NAME> <http://www.lorenzobettini.it>, (C) 2004-2008 // // Copyright: See COPYING file that comes with this distribution // #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "regexrulefactory.h" #include "regexhighlightrule.h" #include "tostringcollection.h" #include "highlightstate.h" #include "regexpreprocessor.h" namespace srchilite { /** * Build a non-marking group (i.e., (? ... ) starting from s * @param s * @return */ static const std::string non_marking_group(const std::string &s) { return "(?:" + s + ")"; } /** * Whether the passed string consists of a single char (escluding * the escape char back slash) * @param s * @return */ static bool is_single_char(const std::string &s) { if (s.size() && s[0] == '\\') return (s.size() == 2); return (s.size() == 1); } RegexRuleFactory::RegexRuleFactory() { } RegexRuleFactory::~RegexRuleFactory() { } HighlightRule *RegexRuleFactory::createSimpleRule(const std::string &name, const std::string &s) { return new RegexHighlightRule(name, s); } HighlightRule *RegexRuleFactory::createWordListRule(const std::string &name, const WordList &list, bool caseSensitive) { // \< and \> are word boundaries // we must make a non-marking group since the string can contain // alternative symbols. For instance, // \<(?:class|for|else)\> // correctly detects 'for' only in isolation, while // (?:\<class|for|else\>) // will not std::string alternatives = toStringCollection(list, '|'); if (!caseSensitive) alternatives = RegexPreProcessor::make_nonsensitive(alternatives); return new RegexHighlightRule(name, "\\<" + non_marking_group(alternatives) + "\\>"); } HighlightRule *RegexRuleFactory::createListRule(const std::string &name, const WordList &list, bool caseSensitive) { std::string alternatives = toStringCollection(list, '|'); if (!caseSensitive) alternatives = RegexPreProcessor::make_nonsensitive(alternatives); return new RegexHighlightRule(name, non_marking_group(alternatives)); } HighlightRule *RegexRuleFactory::createLineRule(const std::string &name, const std::string &start, const std::string &end, const std::string &escape, bool nested) { // if start or end is not a single char we cannot create a regexp directly: // we need to use states, and this is achieved by switching to a multi line rule if (nested || !is_single_char(start) || !is_single_char(end)) { return createMultiLineRule(name, start, end, escape, nested); } std::string exp_string; /* in case the expression is not the start element of a State/Environment and it must not spawn multiple lines, and the delimiters are only one character, build a regular expression of the shape <startdelim>(everything but delimiters)<enddelim> For instance if delimiters are "<" and ">" the built regular expression is "<(?:[^<>])*>" */ if (!escape.size()) { exp_string = start + non_marking_group("[^" + start + (end != start ? end : "") + "]") + "*" + end; } else { /* in case of a specified escape character it will use it for the (everything but delimiters) part. For instace, if in the example above the escape character is the backslash, the generated expression is <(?:[^\\<\\>]|\\.)*> */ exp_string = start + non_marking_group("[^" + escape + start + (end != start ? escape + end : "") + "]|"+ escape + ".") + "*" + end; } return createSimpleRule(name, exp_string); } HighlightRule *RegexRuleFactory::createMultiLineRule(const std::string &name, const std::string &start, const std::string &_end, const std::string &escape, bool nested) { std::string end = _end; if (!end.size()) { // if end is not specified, then end of buffer is assumed end = "\\z"; } // rule matching the start expression HighlightRule *startRule = createSimpleRule(name, start); // rule matching the end expression HighlightRule *endRule = createSimpleRule(name, end); // when we match the end we must exit one level endRule->setExitLevel(1); // the state to enter when we match the start expression HighlightStatePtr innerState = HighlightStatePtr(new HighlightState); // this is the rule for exiting the inner state innerState->addRule(HighlightRulePtr(endRule)); // if escape is given, we must not match the end string when preceeded by the // escape string, thus we build an expression that matches the escape sequence // followed by one character if (escape.size()) { HighlightRule *escapeRule = createSimpleRule(name, escape + "."); innerState->addRule(HighlightRulePtr(escapeRule)); } if (nested) { // if the rule is nested it means that the start expression will // enter the same inner state. // rule matching the start expression within the inner state HighlightRule *nestedStartRule = createSimpleRule(name, start); nestedStartRule->setNested(true); innerState->addRule(HighlightRulePtr(nestedStartRule)); } startRule->setNextState(innerState); return startRule; } HighlightRule *RegexRuleFactory::createCompoundRule( const ElemNameList &nameList, const std::string &rep) { HighlightRule *rule = new RegexHighlightRule(rep); for (ElemNameList::const_iterator it = nameList.begin(); it != nameList.end(); ++it) { rule->addElem(*it); } return rule; } }
satnath/tesseractindic
ccstruct/labls.h
<filename>ccstruct/labls.h /********************************************************************** * File: labls.h (Formerly labels.h) * Description: Attribute definition tables * Author: <NAME>? * Created: * * (C) Copyright 1993, Hewlett-Packard Ltd. ** 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. * **********************************************************************/ #ifndef LABLS_H #define LABLS_H #include "host.h" #include "hpdsizes.h" #include "hpddef.h" //must be last (handpd.dll) extern DLLSYM inT32 tn[NUM_TEXT_ATTR]; extern DLLSYM char tlabel[NUM_TEXT_ATTR][4][MAXLENGTH]; extern DLLSYM inT32 bn[NUM_BLOCK_ATTR]; extern DLLSYM inT32 tvar[NUM_TEXT_ATTR]; extern DLLSYM inT32 bvar[NUM_BLOCK_ATTR]; extern DLLSYM char blabel[NUM_BLOCK_ATTR][4][MAXLENGTH]; extern DLLSYM char backlabel[NUM_BACKGROUNDS][MAXLENGTH]; #endif
lshowbiz/agnt_ht
src/dao/com/joymain/jecs/mi/dao/JmiSpecialListDao.java
package com.joymain.jecs.mi.dao; import java.util.List; import java.math.BigDecimal; import com.joymain.jecs.dao.Dao; import com.joymain.jecs.mi.model.JmiSpecialList; import com.joymain.jecs.util.data.CommonRecord; import com.joymain.jecs.util.data.Pager; public interface JmiSpecialListDao extends Dao { /** * Retrieves all of the jmiSpecialLists */ public List getJmiSpecialLists(JmiSpecialList jmiSpecialList); /** * Gets jmiSpecialList's information based on primary key. An * ObjectRetrievalFailureException Runtime Exception is thrown if * nothing is found. * * @param id the jmiSpecialList's id * @return jmiSpecialList populated jmiSpecialList object */ public JmiSpecialList getJmiSpecialList(final Long id); /** * Saves a jmiSpecialList's information * @param jmiSpecialList the object to be saved */ public void saveJmiSpecialList(JmiSpecialList jmiSpecialList); /** * Removes a jmiSpecialList from the database by id * @param id the jmiSpecialList's id */ public void removeJmiSpecialList(final Long id); //added for getJmiSpecialListsByCrm public List getJmiSpecialListsByCrm(CommonRecord crm, Pager pager); public void saveJmiSpecialList(List<JmiSpecialList> jmiSpecialList); public boolean getJmiSpecialExist(String userCode); }
Wollac/mtg-prob
src/main/java/probability/csv/ManaDorkCSVParser.java
<reponame>Wollac/mtg-prob package probability.csv; import probability.attr.ColorsAttributeKey; import probability.attr.ImmutableAttributeHolder; import probability.attr.IntegerAttributeKey; import probability.attr.ManaCostAttributeKey; import probability.attr.StringAttributeKey; import probability.core.ManaDork; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; public class ManaDorkCSVParser extends AbstractCSVParser<ManaDork> { public ManaDorkCSVParser(Reader reader) throws IOException { super(reader); addOptionalAttribute(AttributeKeys.NUM); addMandatoryAttribute(AttributeKeys.NAME); addMandatoryAttribute(AttributeKeys.MANA_COST); addMandatoryAttribute(AttributeKeys.COLORS); } @Override protected Collection<ManaDork> createInstance(ImmutableAttributeHolder row) { int num = row.getAttributeValue(AttributeKeys.NUM); Collection<ManaDork> manaDorks = new ArrayList<>(num); ManaDork manaDork = new ManaDork(row.getAttributeValue(AttributeKeys.NAME), row.getAttributeValue(AttributeKeys.MANA_COST), row.getAttributeValue(AttributeKeys.COLORS)); for (int i = 0; i < num; i++) { manaDorks.add(manaDork); } return manaDorks; } private interface AttributeKeys { IntegerAttributeKey NUM = new IntegerAttributeKey("num", 1, i -> (i > 0)); StringAttributeKey NAME = new StringAttributeKey("name"); ManaCostAttributeKey MANA_COST = new ManaCostAttributeKey("cost"); ColorsAttributeKey COLORS = new ColorsAttributeKey("colors"); } }
jfuruness/lib_bgp_data
lib_bgp_data/collectors/bgpstream_website/tables.py
<gh_stars>10-100 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module contains numerous bgpstream.com tables These tables must all inherit from the Database class. The Database class allows for the conection to a database upon initialization. Also upon initialization the _create_tables function is called to initialize any tables if they do not yet exist. Beyond that the class can clear the table, create an index, and has the name and columns properties that are used in utils function to insert CSVs into the database. Each table follows the table name followed by a _Table since it inherits from the database class. These tables also contain functions that delete duplicates, format tables for IPV4 or IPV6 data, and can create subtables that are subsets of the data Design choices: -Indexes are created on the times for the what if analysis -The main tables are never deleted to never get rid of website data Possible future improvements: -Add test cases """ __author__ = "<NAME>" __credits__ = ["<NAME>"] __Lisence__ = "BSD" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" import logging from ...utils.database import Generic_Table class Data_Table(Generic_Table): """Data table class, inherits from database. This is supposed to have general functions for other bgpstream.com tables. For a more in depth explanation see the top of the file. """ __slots__ = [] def create_index(self): """Creates an index on the times for later table creations""" sql = f"""CREATE INDEX IF NOT EXISTS {self.name}_index ON {self.name} USING BTREE(start_time, end_time);""" self.execute(sql) def delete_duplicates(self): """Deletes all duplicates from the table.""" logging.debug(f"About to delete duplicates in {self.name}") sql = f"""DELETE FROM {self.name} a USING {self.name} b WHERE a.id < b.id AND a.event_number = b.event_number ;""" logging.debug(sql) self.execute(sql) logging.debug(f"Duplicates deleted in {self.name}") class Hijacks_Table(Data_Table): """Hijack table class, inherits from database. For a more in depth explanation see the top of the file. """ __slots__ = [] name = "hijacks" prefix_column = "expected_prefix" def _create_tables(self): """Creates tables if they do not exist""" sql = """CREATE UNLOGGED TABLE IF NOT EXISTS hijacks ( id serial PRIMARY KEY, country varchar (50), detected_as_path bigint ARRAY, detected_by_bgpmon_peers integer, detected_origin_name varchar (200), detected_origin_number bigint, start_time timestamp with time zone, end_time timestamp with time zone, event_number integer, event_type varchar (50), expected_origin_name varchar (200), expected_origin_number bigint, expected_prefix cidr, more_specific_prefix cidr, url varchar (250) );""" self.cursor.execute(sql) class Leaks_Table(Data_Table): """Leak Table class, inherits from Database. For a more in depth explanation see the top of the file. """ __slots__ = [] name = "leaks" prefix_column = "leaked_prefix" def _create_tables(self): """Creates tables if they do not exist.""" sql = """CREATE UNLOGGED TABLE IF NOT EXISTS leaks ( id serial PRIMARY KEY, country varchar (50), detected_by_bgpmon_peers integer, start_time timestamp with time zone, end_time timestamp with time zone, event_number integer, event_type varchar (50), example_as_path bigint ARRAY, leaked_prefix cidr, leaked_to_name varchar (200) ARRAY, leaked_to_number bigint ARRAY, leaker_as_name varchar (200), leaker_as_number bigint, origin_as_name varchar (200), origin_as_number bigint, url varchar (250) );""" self.cursor.execute(sql) class Outages_Table(Data_Table): """Outage Table class, inherits from Database. For a more in depth explanation see the top of the file. """ __slots__ = [] name = "outages" def _create_tables(self): """Creates tables if they do not exist""" sql = """CREATE UNLOGGED TABLE IF NOT EXISTS outages ( id serial PRIMARY KEY, as_name varchar (200), as_number bigint, country varchar (25), start_time timestamp with time zone, end_time timestamp with time zone, event_number integer, event_type varchar (25), number_prefixes_affected integer, percent_prefixes_affected smallint, url varchar(150) );""" self.cursor.execute(sql)
sunabove/ProgBasic
src/lec/pattern/PatternB.java
<gh_stars>0 package lec.pattern; public class PatternB { public static void main(String[] args) { var out = System.out; var data = "JAVA" ; for( int i = 0; i < data.length() ; i ++ ) { for( int k = 0; k < i + 1 ; k ++ ) { out.print( data.charAt(k) ); } out.println(); } } }
gii-is-psg2/PSG2-2021-G4-42
src/test/java/org/springframework/samples/petclinic/web/CausaControllerTests.java
package org.springframework.samples.petclinic.web; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.samples.petclinic.configuration.SecurityConfiguration; import org.springframework.samples.petclinic.service.CausaService; import org.springframework.security.config.annotation.web.WebSecurityConfigurer; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @WebMvcTest(controllers=CausaController.class, excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebSecurityConfigurer.class), excludeAutoConfiguration= SecurityConfiguration.class) class CausaControllerTests { @Autowired private MockMvc mockMvc; @MockBean CausaService causaService; @WithMockUser(value = "spring") @Test void testCausas() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/causa")).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("causas/causaList")); } @WithMockUser(value = "spring") @Test void testCreateNewCausa() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/causa/new")).andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("causas/createOrUpdateCausaForm")); } @WithMockUser(value = "spring") @Test void testPostNewCausa() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/causa/new") .with(SecurityMockMvcRequestPostProcessors.csrf()) .param("nombre", "Joe") .param("organizacion", "organi") .param("descripcion", "descripcion") .param("recaudacionObjetivo", "10000.")) .andExpect(MockMvcResultMatchers.view().name("redirect:/causa/")); } }
jdbon/ad-verano-2018
tp-repositorio/src/enumerator/Bloque.java
package enumerator; public enum Bloque { UNO, DOS, TRES, CUATRO, CINCO; }
DragonJoker/Ashes
samples/00-Common/Src/PrecompiledHeader.hpp
#pragma once #include "Prerequisites.hpp" #include <ashespp/Buffer/Buffer.hpp> #include <ashespp/Buffer/PushConstantsBuffer.hpp> #include <ashespp/Buffer/StagingBuffer.hpp> #include <ashespp/Buffer/UniformBuffer.hpp> #include <ashespp/Buffer/VertexBuffer.hpp> #include <ashespp/Command/CommandBuffer.hpp> #include <ashespp/Command/CommandPool.hpp> #include <ashespp/Core/Surface.hpp> #include <ashespp/Core/Device.hpp> #include <ashespp/Core/PlatformWindowHandle.hpp> #include <ashespp/Core/Instance.hpp> #include <ashespp/Core/SwapChain.hpp> #include <ashespp/Descriptor/DescriptorSet.hpp> #include <ashespp/Descriptor/DescriptorSetLayout.hpp> #include <ashespp/Descriptor/DescriptorSetPool.hpp> #include <ashespp/Image/Sampler.hpp> #include <ashespp/Image/Image.hpp> #include <ashespp/Image/ImageView.hpp> #include <ashespp/Miscellaneous/QueryPool.hpp> #include <ashespp/Pipeline/GraphicsPipeline.hpp> #include <ashespp/Pipeline/PipelineLayout.hpp> #include <ashespp/RenderPass/FrameBuffer.hpp> #include <ashespp/RenderPass/RenderPass.hpp> #include <ashespp/Sync/Queue.hpp> #include <util/StringUtils.hpp> #include <util/Transform.hpp> #include <util/GlslToSpv.hpp> #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <cstdlib> #include <fstream> #include <functional> #include <numeric> #include <sstream> #include <assimp/Importer.hpp> // C++ importer interface #include <assimp/scene.h> // Output data structure #include <assimp/postprocess.h> // Post processing flags #include <assimp/Importer.hpp> #pragma warning( disable: 4996 ) #include <wx/app.h> #include <wx/cmdline.h> #include <wx/frame.h> #include <wx/panel.h> #include <wx/sizer.h> #include <wx/windowptr.h> #include <wx/wx.h> #if defined( __WXGTK__ ) # include <gdk/gdkx.h> # include <gtk/gtk.h> #elif defined( __WXMSW__ ) # include <wx/msw/private.h> #endif #if defined( _WIN32 ) #include <cstdio> #include <cstring> #include <sys/types.h> #include <sys/stat.h> #include <iostream> #include <direct.h> #include <Shlobj.h> #include <windows.h> #elif defined( __linux__ ) #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <pwd.h> #endif #if defined( near ) # undef near # undef far #endif
Ciechan/Revolved
Revolved/RVPointSprite.h
<filename>Revolved/RVPointSprite.h // // RVPointSprite.h // Revolved // // Created by <NAME> on 19.08.2013. // Copyright (c) 2013 <NAME>. All rights reserved. // #import "RVSprite.h" #import "RVPoint.h" @interface RVPointSprite : RVSprite @property (nonatomic) PointType type; @property (nonatomic) SegmentEnd segmentEnd; @property (nonatomic) GLKVector2 position; @property (nonatomic) GLKVector3 extraTranslationVector; @property (nonatomic) float alpha; @property (nonatomic) float scale; @end
j-oe/segments
core/src/utilities/pdftext.js
/** fastclass PDFTEXT MODULE (c) 2017 <NAME> <EMAIL> License: MIT */ define(['modules/tokens'], function (tkns) { this.pdf = { config: { // which resolution should be used for chunk generation (fraction of average component size) indexShift: 0.25, // optional deviation (+/-) from average component size avgDeviation: 0, }, chunk: function (pdfData, avgWordCount) { var extracted = pdf._getText(pdfData), inputText = extracted[0], inputMeta = extracted[1]; var inputTokens = tkns.seperate(inputText), avgLength = Math.round(avgWordCount + pdf.config.avgDeviation), indexShift = Math.round(avgLength * pdf.config.indexShift); var txtObjects = [], absPosition = 0, absIndex = 0; for (var o = 0; o < inputTokens.length - avgLength; o += indexShift) { var currTokens = inputTokens.slice(o, o + avgLength), joinedTokens = currTokens.join(' '); absIndex++; txtObjects.push({ "xid": 'n' + o, /* ID for chunk based on token nr */ "idx": absIndex, /* absolute index (chunk nr) */ "pos": pdf._getPage(absPosition, inputMeta), /* reconstructed page position*/ "txt": joinedTokens, /* fastclass-conformant text */ }); //absPosition += Math.floor(joinedTokens.length * pdf.config.indexShift); absPosition += inputTokens.slice(o, o + indexShift).join(' ').length+1; } return txtObjects; }, extractText: function (pdfData) { var textData = pdf._getText(pdfData), filtered = pdf._filterLines(textData); return filtered.join(' '); }, _getPage: function (position, metaArr) { var page = -1; for (var i = 0; i < metaArr.length; i++){ var currObj = metaArr[i]; if (position >= currObj.s && position <= currObj.e){ page = currObj.p; } } return page; }, _getText: function (pdfData) { var pdfLines = [], pdfMeta = [], pdfChars = 0; for (var p = 0; p < pdfData.length; p++) { var page = pdfData[p], pageNr = p + 1, pageChars = 0, pageLines = []; for (var i = 0; i < page.items.length; i++) { var lineContentRaw = page.items[i].str, cleanedNoSpaces = lineContentRaw.replace(/\s+/g, ' '), cleanedNoHyphens = cleanedNoSpaces.replace(/(\w)(\-\s)([^u])/g, '$1$3'); pdfLines.push(cleanedNoHyphens); pageChars += cleanedNoHyphens.length; } pdfMeta.push({p: pageNr, c: pageChars, s: pdfChars, e: pdfChars + pageChars}); pdfChars += pageChars; } var joinedLines = pdfLines.join(' '); return [joinedLines, pdfMeta, pdfLines]; }, /* DEPRECATED */ _filterLines: function (lines, nrOfPages, treshold) { var groupedLines = tkns.count(lines), boundary = treshold || 10, badLines = []; for (var line in groupedLines) { if (groupedLines[line] > (nrOfPages - boundary)){ badLines.push(line); } } var filteredLines = lines.filter(function (line) { return badLines.indexOf(line) === -1; }); return filteredLines; } }; return pdf; });
vault-the/changes
migrations/versions/3c93047c66c8_add_index_to_jobstep_status.py
"""Add index to JobStep.status Revision ID: 3c93047c66c8 Revises: 4ab789ea6b6f Create Date: 2015-04-28 22:55:23.139295 """ # revision identifiers, used by Alembic. revision = '3c93047c66c8' down_revision = '4ab789ea6b6f' from alembic import op def upgrade(): op.create_index('idx_jobstep_status', 'jobstep', ['status'], unique=False) def downgrade(): op.drop_index('idx_jobstep_status', table_name='jobstep')
ddstest/ddsprep
dataprep-webapp/src/app/services/state/home/home-state-service.spec.js
<reponame>ddstest/ddsprep<gh_stars>0 /* ============================================================================ Copyright (C) 2006-2018 Talend Inc. - www.talend.com This source code is available under agreement available at https://github.com/Talend/data-prep/blob/master/LICENSE You should have received a copy of the agreement along with this program; if not, write to Talend SA 9 rue Pages 92150 Suresnes, France ============================================================================*/ import i18n from '../../../../i18n/en.json'; describe('home state', () => { beforeEach(angular.mock.module('data-prep.services.state')); beforeEach(angular.mock.module('pascalprecht.translate', function ($translateProvider) { $translateProvider.translations('en', i18n); $translateProvider.preferredLanguage('en'); })); describe('toggleSidepanel', () => { it('should toggle sidepanel', inject((homeState, HomeStateService) => { //given homeState.sidePanelDocked = false; //when HomeStateService.toggleSidepanel(); //then expect(homeState.sidePanelDocked).toBeTruthy(); })); }); describe('toggleCopyMovePreparation', () => { it('should toggle copy/move preparation', inject((homeState, HomeStateService) => { //given homeState.preparations.copyMove.isVisible = false; //when HomeStateService.toggleCopyMovePreparation(); //then expect(homeState.preparations.copyMove.isVisible).toBeTruthy(); })); it('should set preparation and its initial folder', inject((homeState, HomeStateService) => { //given homeState.preparations.copyMove.initialFolder = { id: 'folder 1' }; homeState.preparations.copyMove.preparation = { id: 'prep 1' }; const initialFolder = { id: 'folder 2' }; const preparation = { id: 'prep 2' }; //when HomeStateService.toggleCopyMovePreparation(initialFolder, preparation); //then expect(homeState.preparations.copyMove.initialFolder).toBe(initialFolder); expect(homeState.preparations.copyMove.preparation).toBe(preparation); }) ); it('should set copy move tree', inject((homeState, HomeStateService) => { //given homeState.preparations.copyMove.tree = { id: 'folder 1' }; const tree = { id: 'folder 2' }; //when HomeStateService.setCopyMoveTree(tree); //then expect(homeState.preparations.copyMove.tree).toBe(tree); }) ); it('should set copy move tree loading', inject((homeState, HomeStateService) => { //given homeState.preparations.copyMove.isTreeLoading = false; //when HomeStateService.setCopyMoveTreeLoading(true); //then expect(homeState.preparations.copyMove.isTreeLoading).toBeTruthy(); }) ); }); describe('content', () => { it('should set content loading flag', inject((homeState, HomeStateService) => { //given homeState.content.isLoading = false; //when HomeStateService.setContentLoading(true); //then expect(homeState.content.isLoading).toBeTruthy(); })); }); describe('togglePreparationCreator', () => { it('should toggle preparation creator', inject((homeState, HomeStateService) => { //given homeState.preparations.creator.isVisible = false; //when HomeStateService.togglePreparationCreator(); //then expect(homeState.preparations.creator.isVisible).toBeTruthy(); })); }); describe('toggleFolderCreator', () => { it('should toggle folder creator', inject((homeState, HomeStateService) => { //given homeState.folders.creator.isVisible = false; //when HomeStateService.toggleFolderCreator(); //then expect(homeState.folders.creator.isVisible).toBeTruthy(); })); }); describe('About', () => { it('should toggle about modal', inject((homeState, HomeStateService) => { //when HomeStateService.toggleAbout(); //then expect(homeState.about.isVisible).toBeTruthy(); })); it('should populate builds', inject((homeState, HomeStateService) => { //given const allBuildDetails = [ { "versionId": "2.0.0-SNAPSHOT", "buildId": "2adb70d", "serviceName": "API" }, { "versionId": "2.0.0-SNAPSHOT", "buildId": "2adb70d", "serviceName": "DATASET" }, { "versionId": "2.0.0-SNAPSHOT", "buildId": "2adb70d", "serviceName": "PREPARATION" }, { "versionId": "2.0.0-SNAPSHOT", "buildId": "2adb70d", "serviceName": "TRANSFORMATION" } ]; //when HomeStateService.setBuilds(allBuildDetails); //then expect(homeState.about.builds).toBe(allBuildDetails); })); }); });
asac-geeks/childbook
finalProject/src/main/java/com/example/finalProject/entity/GroupPost.java
package com.example.finalProject.entity; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import java.util.Date; import java.util.List; import java.util.Set; @Entity public class GroupPost { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String imageUrl; private String videoSrc; private String videoType; private String postTitle; private String body; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date createdAt; @UpdateTimestamp @Temporal(TemporalType.TIMESTAMP) private Date modifiedAt; @ManyToOne private AppUser GroupPostUser; @OneToMany(mappedBy = "groupPost", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Comment> comments; @OneToMany(mappedBy = "groupPost", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set<Likes> likes; @OneToMany(mappedBy = "groupPost", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set<Share> shares; @ManyToOne Groups group; public GroupPost(String body, AppUser appUser, String imageUrl, String videoSrc, String videoType, String postTitle, boolean isPublic) { this.body = body; this.GroupPostUser = appUser; // should this be shared ? this.imageUrl = imageUrl; this.videoSrc = videoSrc; this.videoType = videoType; this.postTitle = postTitle; this.isPublic = isPublic; } public boolean isPublic() { return isPublic; } public void setPublic(boolean aPublic) { isPublic = aPublic; } private boolean isPublic; public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public GroupPost() { } public Integer getId() { return id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getModifiedAt() { return modifiedAt; } public void setModifiedAt(Date modifiedAt) { this.modifiedAt = modifiedAt; } public AppUser getAppUser() { return GroupPostUser; } public void setAppUser(AppUser appUser) { this.GroupPostUser = appUser; } public String getVideoSrc() { return videoSrc; } public void setVideoSrc(String videoSrc) { this.videoSrc = videoSrc; } public String getVideoType() { return videoType; } public void setVideoType(String videoType) { this.videoType = videoType; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public Set<Likes> getLikes() { return likes; } public void setLikes(Set<Likes> likes) { this.likes = likes; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public Set<Share> getShares() { return shares; } public void setShares(Set<Share> shares) { this.shares = shares; } public AppUser getGroupPostUser() { return GroupPostUser; } public void setGroupPostUser(AppUser groupPostUser) { GroupPostUser = groupPostUser; } public Groups getGroup() { return group; } public void setGroup(Groups group) { this.group = group; } }
mparnaudeau/clib2
library/contrib/byteswap/byteswap_bswap64.c
#if defined(USE_64_BIT_INTS) #if defined(__PPC__) && defined(__GNUC__) asm(" .text\n\ .align 2\n\ .globl bswap64\n\ .type bswap64, @function\n\ bswap64:\n\ rlwinm %r5,%r3,8,8,31\n\ rlwimi %r5,%r3,24,0,7\n\ rlwimi %r5,%r3,24,16,23\n\ rlwinm %r3,%r4,8,8,31\n\ rlwimi %r3,%r4,24,0,7\n\ rlwimi %r3,%r4,24,16,23\n\ or %r4,%r5,%r5\n\ blr\n\ "); #else #include <stdint.h> uint64_t bswap64(uint64_t u64) { union { uint64_t ll; uint32_t l[2]; } v={.ll=u64}; uint32_t tmp; tmp=v.l[0]; v.l[0]=((v.l[1]&0xff)<<24)| ((v.l[1]&0xff00)<<8)| ((v.l[1]&0xff0000)>>8)| ((v.l[1]&0xff000000)>>24); v.l[1]=((tmp&0xff)<<24)| ((tmp&0xff00)<<8)| ((tmp&0xff0000)>>8)| ((tmp&0xff000000)>>24); return(v.ll); } #endif #endif
crupest/Cru
src/common/platform/win/Win32FileStreamPrivate.h
<gh_stars>0 #include "cru/common/platform/win/WinPreConfig.h" #include <objidl.h> namespace cru::platform::win { namespace details { struct Win32FileStreamPrivate { IStream* stream_ = nullptr; }; } // namespace details } // namespace cru::platform::win
pixelballoon/pixelboost
tools/editor/source/view/entity/entity.h
#pragma once #include <map> #include <string> #include "glm/glm.hpp" #include "pixelboost/logic/entity.h" #include "pixelboost/maths/boundingBox.h" #include "project/definitions.h" namespace pb { class RectangleComponent; class RenderLayer; } class ProjectEntity; class ProjectStruct; class Property; class SchemaItem; class SchemaStruct; class Selection; class ViewProperty; class ViewEntity : public pb::Entity { PB_DECLARE_ENTITY protected: ViewEntity(pb::Scene* scene, pb::Entity* parent, pb::DbEntity* creationEntity); virtual ~ViewEntity(); public: void Initialise(ProjectEntity* entity); ProjectEntity* GetEntity(); pb::Uid GetEntityUid(); public: glm::vec3 GetPosition(); glm::vec3 GetRotation(); glm::vec3 GetScale(); void SetPosition(glm::vec3 position); void SetRotation(glm::vec3 rotation); void SetScale(glm::vec3 scale); void Transform(glm::vec3 positionOffset, glm::vec3 rotationOffset = glm::vec3(0,0,0), glm::vec3 scaleOffset = glm::vec3(1,1,1)); void CommitTransform(); void ResetTransform(); public: pb::BoundingBox GetBoundingBox(); Uid GetPropertyIdByPath(const std::string& path); ViewProperty* GetPropertyByPath(const std::string& path); ViewProperty* GetPropertyById(Uid uid); private: void OnUpdate(const pb::Message& message); void OnSelectionChanged(const Selection* selection); Uid AddProperty(ViewProperty* property); void RemoveProperty(ViewProperty* property); void RemovePropertyById(Uid uid); Uid GeneratePropertyId(const std::string& path); void ParseProperties(); void ParseStruct(const std::string& path, const SchemaStruct* schemaStruct); void ParseItem(const std::string& path, const SchemaItem* item); void OnDestroyed(ProjectStruct* structure); void OnPropertyChanged(ProjectStruct* structure, Property* property); void DirtyBounds(); void UpdateBounds(); private: typedef std::map<std::string, Uid> PropertyIdMap; typedef std::map<Uid, ViewProperty*> PropertyMap; private: ProjectEntity* _Entity; PropertyIdMap _PropertyIdMap; PropertyMap _Properties; bool _BoundsDirty; pb::BoundingBox _BoundingBox; friend class ViewProperty; };
andrqxa/stepic_programming_go
02_functions/04_strings/main1.go
<gh_stars>0 /* На вход подается строка. Нужно определить, является ли она правильной или нет. Правильная строка начинается с заглавной буквы и заканчивается точкой. Если строка правильная - вывести Right иначе - вывести Wrong Маленькая подсказка: fmt.Scan() считывает строку до первого пробела, вы можете считать полностью строку за раз с помощью bufio: text, _ := bufio.NewReader(os.Stdin).ReadString('\n') Sample Input: Быть или не быть. Sample Output: Right */ package main import ( "bufio" "fmt" "os" "unicode" ) func main() { text, _ := bufio.NewReader(os.Stdin).ReadString('\n') runes := []rune(text) if unicode.IsUpper(runes[0]) && runes[len(runes)-1] == '.' { fmt.Println("Right") } else { fmt.Println("Wrong") } }
agorsk1/car-rating-app
apps/cars/factory/user_factory.py
<reponame>agorsk1/car-rating-app import factory from django.contrib.auth import get_user_model class UserFactory(factory.django.DjangoModelFactory): """" User factory for testing purposes default values: username - user1, user2 etc. (Sequence) !IMPORTANT If you will use email as username you must create extra factory for that. """ class Meta: model = get_user_model() username = factory.Sequence(lambda n: f'user{n}')
jiseungjeong/cppPracticeForTetris
CH5/ch5-1/first_operator_overloading.cpp
<filename>CH5/ch5-1/first_operator_overloading.cpp #include <iostream> #include <string.h> class MyString { char *string_content; int string_length; int memory_capacity; public: MyString(char c); MyString(const char *str); MyString(const MyString &str); ~MyString(); int length() const; int capacity() const; void reserve(int size); void print() const; void println() const; char at(int i) const; int compare(const MyString &str) const; bool operator==(MyString &str); }; MyString::MyString(char c) { string_content = new char[1]; string_content[0] = c; memory_capacity = 1; string_length = 1; } MyString::MyString(const char *str) { string_length = strlen(str); memory_capacity = string_length; string_content = new char[string_length]; for (int i = 0; i != string_length; i++) string_content[i] = str[i]; } MyString::MyString(const MyString &str) { string_length = str.string_length; string_content = new char[string_length]; for (int i = 0; i != string_length; i++) { string_content[i] = str.string_content[i]; } } MyString::~MyString() { delete[] string_content; } int MyString::length() const { return string_length; } void MyString::print() const { for (int i = 0; i != string_length; i++) std::cout << string_content[i]; } void MyString::println() const { for (int i = 0; i != string_length; i++) std::cout << string_content[i]; std::cout << std::endl; } int MyString::capacity() const { return memory_capacity; } void MyString::reserve(int size) { if (size > memory_capacity) { char *prev_string_content = string_content; string_content = new char[size]; memory_capacity = size; for (int i = 0; i != string_length; i++) string_content[i] = prev_string_content[i]; delete[] prev_string_content; } } char MyString::at(int i) const { if (i >= string_length || i < 0) return 0; else return string_content[i]; } int MyString::compare(const MyString &str) const { for (int i = 0; i < std::min(string_length, str.string_length); i++) { if (string_content[i] > str.string_content[i]) return 1; else if (string_content[i] < str.string_content[i]) return -1; } if (string_length == str.string_length) return 0; else if (string_length > str.string_length) return 1; return -1; } bool MyString::operator==(MyString &str) { return !compare(str); } int main() { MyString str1("a word"); MyString str2("sentence"); MyString str3("sentence"); if (str1 == str2) std::cout << "str1 와 str2 는 같다." << std::endl; else std::cout << "str1 와 str2 는 다르다." << std::endl; if (str2 == str3) std::cout << "str2 와 str3 는 같다." << std::endl; else std::cout << "str2 와 str3 는 다르다." << std::endl; }
melin/carbondata
core/src/main/java/org/apache/carbondata/core/constants/CarbonVersionConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.core.constants; import java.io.InputStream; import java.util.Properties; import org.apache.carbondata.common.logging.LogService; import org.apache.carbondata.common.logging.LogServiceFactory; public final class CarbonVersionConstants { private static final LogService LOGGER = LogServiceFactory.getLogService(CarbonVersionConstants.class.getName()); /** * the file name of CarbonData version info */ private static final String CARBONDATA_VERSION_INFO_FILE = "carbondata-version-info.properties"; /** * current CarbonData version */ public static final String CARBONDATA_VERSION; /** * which branch current version build from */ public static final String CARBONDATA_BRANCH; /** * the latest commit revision which current branch point to */ public static final String CARBONDATA_REVISION; /** * the date of building current version */ public static final String CARBONDATA_BUILD_DATE; /** * number of rows per blocklet column page default value for V2 version */ public static final int NUMBER_OF_ROWS_PER_BLOCKLET_COLUMN_PAGE_DEFAULT_V2 = 120000; static { // create input stream for CARBONDATA_VERSION_INFO_FILE InputStream resourceStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(CARBONDATA_VERSION_INFO_FILE); Properties props = new Properties(); try { // read CARBONDATA_VERSION_INFO_FILE into props props.load(resourceStream); } catch (Exception e) { LOGGER.error(e, "Error loading properties from " + CARBONDATA_VERSION_INFO_FILE); } finally { if (resourceStream != null) { try { resourceStream.close(); } catch (Exception e) { LOGGER.error(e, "Error closing CarbonData build info resource stream"); } } } // set the values CARBONDATA_VERSION = props.getProperty("version"); CARBONDATA_BRANCH = props.getProperty("branch"); CARBONDATA_REVISION = props.getProperty("revision"); CARBONDATA_BUILD_DATE = props.getProperty("date"); } }
liguangyuaaa/bigdatajava
src/main/java/lgystudy/day2_06_20210327/exer/ListExerLgy.java
package lgystudy.day2_06_20210327.exer; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class ListExerLgy { // 分区List中remove(int index)和remove(Object obj) @Test public void testListRemove(){ List list = new ArrayList(); list.add(1); list.add(2); list.add(3); updateList(list); System.out.println(list); } private void updateList(List list) { // list.remove(2); list.remove(new Integer(2)); } }
GoodforGod/aws-lambda-java-events
src/main/java/io/goodforgod/aws/lambda/events/cognito/CognitoUserPoolCreateAuthChallengeEvent.java
<gh_stars>1-10 package io.goodforgod.aws.lambda.events.cognito; import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * Represent the class for the Cognito User Pool Create Auth Challenge Lambda Trigger * * @see <a href= * "https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html">Create * Auth Challenge Lambda Trigger</a> * @author <NAME> (GoodforGod) * @since 24.07.2021 */ @Data @Accessors(chain = true) @EqualsAndHashCode(callSuper = true) public class CognitoUserPoolCreateAuthChallengeEvent extends CognitoUserPoolEvent { /** * The request from the Amazon Cognito service. */ private Request request; /** * The response from your Lambda trigger. */ private Response response; @Data @EqualsAndHashCode(callSuper = true) public static class Request extends CognitoUserPoolEvent.Request { /** * One or more key-value pairs that you can provide as custom input to the Lambda function that you * specify for the create auth challenge trigger. */ private Map<String, String> clientMetadata; /** * The name of the new challenge. */ private String challengeName; private ChallengeResult[] session; /** * This boolean is populated when PreventUserExistenceErrors is set to ENABLED for your User Pool * client. */ private boolean userNotFound; } @Data public static class ChallengeResult { /** * The challenge type. One of: "CUSTOM_CHALLENGE", "PASSWORD_VERIFIER", "SMS_MFA", * "DEVICE_SRP_AUTH", "DEVICE_PASSWORD_VERIFIER", or "ADMIN_NO_SRP_AUTH". */ private String challengeName; /** * Set to true if the user successfully completed the challenge, or false otherwise. */ private boolean challengeResult; /** * Your name for the custom challenge. Used only if challengeName is CUSTOM_CHALLENGE. */ private String challengeMetadata; } @Data public static class Response { /** * One or more key-value pairs for the client app to use in the challenge to be presented to the * user. Contains the question that is presented to the user. */ private Map<String, String> publicChallengeParameters; /** * Contains the valid answers for the question in publicChallengeParameters */ private Map<String, String> privateChallengeParameters; /** * Your name for the custom challenge, if this is a custom challenge. */ private String challengeMetadata; } }
jeremydeanlakey/lakey-finicity-python
tests/response/test_institutions_list_response.py
import json import unittest from lakey_finicity.responses import InstitutionsListResponse EXAMPLE_INSTITUTIONS_RESPONSE = ''' { "found":7843, "displaying":25, "moreAvailable":true, "createdDate":1582938670, "institutions":[ { "id":15436, "name":"Mass Mutual Financial Group(Retirement Access)", "aha":false, "accountTypeDescription":"Workplace Retirement", "phone":"1-866-630-5295", "urlHomeApp":"https://www.massmutual.com/", "urlLogonApp":"https://retirementsolutions.financialtrans.com/tf/myPLAN/Welcome?cz=d07001719051417031511001318", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"retirement", "specialText":"Please enter your Mass Mutual Financial Group (Retirement Access) Email Address and Password required for login.", "address":{ "city":"Atlanta", "state":"GA", "country":"USA", "postalCode":"30357-2566", "addressLine1":"Post Office Box 78566", "addressLine2":"" }, "currency":"USD", "email":"https://www.amsouthdailyelect.com/contact.asp", "oauthInstitutionId":null }, { "id":15974, "name":"<NAME>", "aha":false, "accountTypeDescription":"Banking", "phone":"817-284-9598", "urlHomeApp":"https://www.spectra.bank/", "urlLogonApp":"https://www.myebanking.net/riverbendbank/login/login.aspx", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your River Bend Bank Access ID and Password required for login.", "address":{ "city":"Texas", "state":"IL", "country":"USA", "postalCode":"76181-0070", "addressLine1":"P.O. Box 185070", "addressLine2":"<NAME>" }, "currency":"USD", "email":"<EMAIL>", "oauthInstitutionId":null }, { "id":1411, "name":"Royal Bank of Canada", "aha":true, "accountTypeDescription":"Banking", "phone":"1-800-769-2555", "urlHomeApp":"http://www.rbcbank.com", "urlLogonApp":"https://www1.royalbank.com/cgi-bin/rbaccess/rbunxcgi?F6=1&F7=IB&F21=IB&F22=IB&REQUEST=ClientSignin&LANGUAGE=ENGLISH", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your Royal Bank of Canada Username or Client Card Number and Password.", "address":{ "city":"", "state":"", "country":"CAN", "postalCode":"", "addressLine1":"", "addressLine2":"" }, "currency":"USD", "email":"http://www.royalbank.com/rd_form1.html", "oauthInstitutionId":null }, { "id":7999, "name":"<NAME>", "aha":false, "accountTypeDescription":"Credit Cards/Accounts", "phone":"1-800-653-6289", "urlHomeApp":"http://www.oldnavy.com", "urlLogonApp":"https://lakey_finicity.rfecom.com/eSecurity/Login/login.action?clientId=oldnavy&accountType=generic&langId=en", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"creditCards", "specialText":"Please enter your Old Navy User Name and Password Required for Login", "address":{ "city":"Grove City", "state":"OH", "country":"USA", "postalCode":"43123-8605", "addressLine1":"200 Old Navy Lane", "addressLine2":"" }, "currency":"USD", "email":"http://www.oldnavy.com/asp/feedback_other.asp?FromPg=Other", "oauthInstitutionId":null }, { "id":14121, "name":"Bank2", "aha":false, "accountTypeDescription":"Banking", "phone":"1(405) 946-2265", "urlHomeApp":"https://www.bank2.biz", "urlLogonApp":"https://olb.bank2online.com/", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your Bank2 Username and password required for login.", "address":{ "city":"Oklahoma City", "state":"OK", "country":"USA", "postalCode":"73108", "addressLine1":"909 S. Meridian", "addressLine2":"" }, "currency":"USD", "email":"", "oauthInstitutionId":null }, { "id":12721, "name":"<NAME> - Web Cash Manager", "aha":false, "accountTypeDescription":"Banking", "phone":"1-800-377-0800", "urlHomeApp":"https://www.popularbank.com/#home", "urlLogonApp":"https://webcmpr.bancopopular.com/K1/", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Banking", "specialText":"Please enter your Banco Popular Customer ID, User ID and Password required for login.", "address":{ "city":"New York", "state":"NY", "country":"USA", "postalCode":"10004", "addressLine1":"85 Broad Street", "addressLine2":"" }, "currency":"USD", "email":"<EMAIL>", "oauthInstitutionId":null }, { "id":13037, "name":"<NAME>", "aha":false, "accountTypeDescription":"Loan", "phone":"1-800-831-1117", "urlHomeApp":"https://www.bmwusa.com/", "urlLogonApp":"https://securelogin.bmwusa.com/login?returnUrl=%2F", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Loan", "specialText":"Please Enter your BMW Financial Services Email Address and Password required for login.", "address":{ "city":"Woodcliff Lake", "state":"NJ", "country":"USA", "postalCode":"84109-0488", "addressLine1":"BMW of North America, LLC", "addressLine2":"300 Chestnut Ridge Roa" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":14341, "name":"<NAME>", "aha":false, "accountTypeDescription":"Investment", "phone":"1 (877) 924-3967", "urlHomeApp":"https://myspendingaccount.wageworks.com/Welcome/PortalLandingPage.aspx", "urlLogonApp":"https://myspendingaccount.wageworks.com/Welcome/PortalLandingPage.aspx", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Investment", "specialText":null, "address":{ "city":"San Mateo", "state":"CA", "country":"USA", "postalCode":"10016", "addressLine1":"NA", "addressLine2":"NA" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":15680, "name":"Fifth Third Direct - Business Banking", "aha":false, "accountTypeDescription":null, "phone":"1-866-671-5353", "urlHomeApp":"https://www.53.com/wps/portal/personal", "urlLogonApp":"https://express.53.com/portal/authn/#/login", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Business Banking", "specialText":"Please enter your Fifth Third Direct - Business Banking User ID and Password required for login. \\t", "address":{ "city":"Cincinnati", "state":"OH", "country":"USA", "postalCode":"45263", "addressLine1":"Fifth Third Center", "addressLine2":"38 Fountain Square Plaza" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":16021, "name":"<NAME>", "aha":false, "accountTypeDescription":"Credit Card", "phone":"(800) 782-7282", "urlHomeApp":"https://www.starbucks.com/", "urlLogonApp":"https://app.starbucks.com/account/signin", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Credit Card", "specialText":"Please enter your Starbucks Username/ email and Password required for login.", "address":{ "city":"San Angelo", "state":"TX", "country":"USA", "postalCode":"98124-3717", "addressLine1":"P.O. Box 60650", "addressLine2":"San Angelo" }, "currency":"USD", "email":"https://customerservice.starbucks.com", "oauthInstitutionId":null }, { "id":100389, "name":"HealthEquity", "aha":false, "accountTypeDescription":"Banking", "phone":"877.694.3942", "urlHomeApp":"https://www.healthequity.com", "urlLogonApp":"https://www.healthequity.com/HE.aspx", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your HealthEquity Username or Email Address and Password required for login.", "address":{ "city":"Draper ", "state":"UT", "country":"USA", "postalCode":"84020", "addressLine1":"15 W Scenic Pointe Dr", "addressLine2":"" }, "currency":"USD", "email":"http://www.healthequity.com", "oauthInstitutionId":null }, { "id":170837, "name":"Navirefi: Student Loan Refinancing", "aha":false, "accountTypeDescription":"Loan", "phone":null, "urlHomeApp":"https://navirefi.com/", "urlLogonApp":"https://login2.navirefi.com/CALM2/pages/CALM2CookieJsCheck.jsp?sourceAppName=NRILP", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"loan", "specialText":"Please enter your Navirefi User ID and Password required for login.", "address":{ "city":"Wilkes-Barre", "state":"PA", "country":"USA", "postalCode":"18773-9115", "addressLine1":"NaviRefi", "addressLine2":"P.O. Box 9115" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170838, "name":"InBank", "aha":false, "accountTypeDescription":"Banking", "phone":"303.805.0321", "urlHomeApp":"https://inbank.com/", "urlLogonApp":"https://inbank.com/personal-banking/", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"banking", "specialText":"Please enter your IN Bank's User ID and Password required for login.", "address":{ "city":"Aurora", "state":"CO", "country":"USA", "postalCode":"800165", "addressLine1":"24450 e smoky hill rd", "addressLine2":"Aurora-80016" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170839, "name":"City National Bank Credit Card Online", "aha":false, "accountTypeDescription":"Credit Card", "phone":null, "urlHomeApp":"https://cnb.cardmanager.com/", "urlLogonApp":"https://cnb.cardmanager.com/", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Credit Card", "specialText":"Please enter your User Name and Password required for login. \\t", "address":{ "city":"Lost Angeles", "state":"CA", "country":"USA", "postalCode":"90071", "addressLine1":"City National Plaza", "addressLine2":"555 South Flower Street" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170840, "name":"Community Bank & Trust of Florida (MIDFLORIDA CCU)", "aha":false, "accountTypeDescription":"Banking", "phone":"352-369-1000", "urlHomeApp":"https://online.cbtfl.com", "urlLogonApp":"https://online.cbtfl.com/cbtfl/uux.aspx#/login", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"banking", "specialText":"Please enter your Login ID & Password required for login.", "address":{ "city":"Ocala", "state":"FL", "country":"USA", "postalCode":"34471", "addressLine1":"1603 SW 19th Avenue", "addressLine2":"Ocala" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170846, "name":"Gazelle", "aha":false, "accountTypeDescription":null, "phone":null, "urlHomeApp":"https://www.daveramsey.com/", "urlLogonApp":"https://gazelle.id.ramseysolutions.net/sign-in?&client_id=debit-web-app&code_challenge_method=S256&code_challenge=OmLfNzomO5fdRbNFfH-MwOwAtLntlN_ENOCimI4dllw&redirect_uri=https%3A%2F%2Fwww.gazelleintense.com%2Fauth%2Fsession%2Faccess&response_type=code&sc", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"1", "specialText":"Please enter your Gazelle Intense Email and Password required for login.", "address":{ "city":"Franklin", "state":"TN", "country":"USA", "postalCode":"37064", "addressLine1":"Ramsey Solutions", "addressLine2":"1011 Reams Fleming Blvd" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170848, "name":"Prosperity Bank - Treasury Center", "aha":false, "accountTypeDescription":"Business Banking", "phone":"1-855-888-2242", "urlHomeApp":"https://www.prosperitybankusa.com", "urlLogonApp":"https://prosperity.olbanking.com/", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Business Banking", "specialText":"Please enter your Prosperity Bank - Treasury Center's Company ID, User ID and Password required for login.", "address":{ "city":"El Campo", "state":"TX", "country":"USA", "postalCode":"77437", "addressLine1":"1301 North Mechanic", "addressLine2":"" }, "currency":"USD", "email":"<EMAIL>", "oauthInstitutionId":null }, { "id":170852, "name":"Platinum Federal Credit Union", "aha":false, "accountTypeDescription":"Banking", "phone":"404-297-9797", "urlHomeApp":"https://www.platinumfcu.org/", "urlLogonApp":"https://platinumfcu.onlinecu.com/?user", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Banking", "specialText":"Please enter your Platinum Federal username and password required for login.", "address":{ "city":"1059 Mistletoe Road", "state":"GA", "country":"USA", "postalCode":"30033", "addressLine1":"Decatur", "addressLine2":"1000-A" }, "currency":"USD", "email":"<EMAIL>", "oauthInstitutionId":null }, { "id":170853, "name":"Key bank - Businesses & Institutions", "aha":false, "accountTypeDescription":"Business Banking", "phone":null, "urlHomeApp":"https://www.key.com/businesses-institutions/index.jsp", "urlLogonApp":"https://keynavigator.key.com/ktt/cmd/logonFromKeyComNew", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Business Banking", "specialText":"Please enter your Key Bank Business & Institutions User ID & Password required for login", "address":{ "city":"Cleveland", "state":"OH", "country":"USA", "postalCode":"44114", "addressLine1":"127 Public Square", "addressLine2":"" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":170856, "name":"<NAME>", "aha":false, "accountTypeDescription":"Banking", "phone":"322172438", "urlHomeApp":"https://uhaulfedcu.com/", "urlLogonApp":"https://www.ea.financial-net.com/vbsts/Login/UserPassLogin.aspx?ReturnUrl=%2fvbsts%2f%3fwa%3dwsignin1.0%26wtrealm%3dhttps%253a%252f%252fwww.financial-net.com%252f%26wctx%3drm%253d0%2526id%253dpassive%2526ru%253d%25252fuhaulfedcu%25252fsecurity%25252fOlbCm", "oauthEnabled":false, "urlForgotPassword":null, "urlOnlineRegistration":null, "class":"Banking", "specialText":"Please enter your U-Haul Federal Credit Union Username &b Password required for login.", "address":{ "city":"Phoenix", "state":"AZ", "country":"USA", "postalCode":"85004", "addressLine1":"2700 N 3rd St Suite", "addressLine2":"1000-A" }, "currency":"USD", "email":null, "oauthInstitutionId":null }, { "id":31, "name":"<NAME>", "aha":true, "accountTypeDescription":"Banking", "phone":"1-800-956-4442", "urlHomeApp":"https://www.wellsfargo.com", "urlLogonApp":"https://connect.secure.wellsfargo.com/auth/login/present?origin=cob", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your Username or Social Security Number and your Password required to login.", "address":{ "city":"San Francisco", "state":"CA", "country":"USA", "postalCode":"94163", "addressLine1":"", "addressLine2":"" }, "currency":"USD", "email":"https://www.wellsfargo.com/per/per_ask_us.jhtml", "oauthInstitutionId":null }, { "id":14007, "name":"Bank of America", "aha":false, "accountTypeDescription":"Banking", "phone":"1-800-792-0808", "urlHomeApp":"https://secure.bankofamerica.com/", "urlLogonApp":"https://secure.bankofamerica.com/login/sign-in/signOnV2Screen.go", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your Bank of America Online ID(Minimum 6 character) and Passcode required for login. (Note: We do not support the BOA Safe passcode feature. Please disable it at your bank's website to successfully add your accounts)", "address":{ "city":"Charlotte", "state":"NC", "country":"USA", "postalCode":"28255", "addressLine1":"307 S. MAIN", "addressLine2":"" }, "currency":"USD", "email":"https://www.bankofamerica.com/contact/", "oauthInstitutionId":null }, { "id":5, "name":"Chase", "aha":true, "accountTypeDescription":"Banking", "phone":"1-800-242-7324", "urlHomeApp":"https://secure01c.chase.com/", "urlLogonApp":"https://secure01c.chase.com/web/auth/#/logon/logon/chaseOnline", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"banking", "specialText":"Please enter your Chase User ID and Password. ", "address":{ "city":"New York", "state":"NY", "country":"USA", "postalCode":"10017", "addressLine1":"270 Park Avenue", "addressLine2":"270 Park Avenue, New York" }, "currency":"USD", "email":"https://www.bankone.com/contactus/#personal", "oauthInstitutionId":null }, { "id":1003, "name":"Citibank", "aha":true, "accountTypeDescription":"Credit Cards/Accounts", "phone":"1-800-950-5114", "urlHomeApp":"https://online.citibank.com/US/Welcome.c", "urlLogonApp":"https://online.citi.com/US/login.do", "oauthEnabled":false, "urlForgotPassword":"", "urlOnlineRegistration":"", "class":"creditCards", "specialText":"Enter your Citibank Credit Card User ID and Password. Please note that if you have not accessed Citibank Account Online in the past 6 months, please register again and choose a new User ID.", "address":{ "city":"New York", "state":"NY", "country":"USA", "postalCode":"10043", "addressLine1":"", "addressLine2":"" }, "currency":"USD", "email":"https://online.citibank.com/US/Welcome.c", "oauthInstitutionId":null } ] } ''' class TestInstitutionsListResponse(unittest.TestCase): def test_institutions_response(self): response_dict = json.loads(EXAMPLE_INSTITUTIONS_RESPONSE) response = InstitutionsListResponse.from_dict(response_dict) self.assertEqual({}, response._unused_fields) for institution in response.institutions: self.assertEqual({}, institution._unused_fields) self.assertEqual({}, institution.address._unused_fields)
ojasonbernal/McDonaldsDatabaseSystem
CustomerPortal/src/MainPortal.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import javax.swing.JOptionPane; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * * @author ojaso */ public class MainPortal extends javax.swing.JFrame { /** * Creates new form MainPortal */ public MainPortal() { initComponents(); String [] topEntrees = DatabaseAccess.topEntrees(); String [] last4 = DatabaseAccess.last4Entrees(Order.id); System.out.println(last4[0]); jTextField_Top1.setText(topEntrees[0]); jTextField_Top2.setText(topEntrees[1]); jTextField_Top3.setText(topEntrees[2]); jTextField_Top4.setText(topEntrees[3]); jTextField_Top5.setText(last4[0]); jTextField_Top6.setText(last4[1]); jTextField_Top7.setText(last4[2]); jTextField_Top8.setText(last4[3]); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jButton_SignOut = new javax.swing.JButton(); jButton_Entrees = new javax.swing.JButton(); jButton_Cart = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jTextField_Top2 = new javax.swing.JTextField(); jTextField_Top1 = new javax.swing.JTextField(); jTextField_Top3 = new javax.swing.JTextField(); jTextField_Top4 = new javax.swing.JTextField(); jTextField_Top5 = new javax.swing.JTextField(); jTextField_Top6 = new javax.swing.JTextField(); jTextField_Top7 = new javax.swing.JTextField(); jTextField_Top8 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel2.setBackground(new java.awt.Color(0, 0, 0)); jPanel3.setBackground(new java.awt.Color(255, 255, 153)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel4.setText("Customer - Home Page:"); jButton_SignOut.setBackground(new java.awt.Color(255, 0, 0)); jButton_SignOut.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jButton_SignOut.setText("Sign Out"); jButton_SignOut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_SignOutActionPerformed(evt); } }); jButton_Entrees.setBackground(new java.awt.Color(51, 153, 255)); jButton_Entrees.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jButton_Entrees.setText("Create Order"); jButton_Entrees.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_EntreesActionPerformed(evt); } }); jButton_Cart.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jButton_Cart.setText("Cart"); jButton_Cart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_CartActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel5.setText("Hi, what would you like to order?"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel6.setText("Last entrees you ordered:"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel7.setText("Top 4 trending entrees this past week:"); jTextField_Top2.setEditable(false); jTextField_Top2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top2ActionPerformed(evt); } }); jTextField_Top1.setEditable(false); jTextField_Top1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top1ActionPerformed(evt); } }); jTextField_Top3.setEditable(false); jTextField_Top3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top3ActionPerformed(evt); } }); jTextField_Top4.setEditable(false); jTextField_Top4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top4ActionPerformed(evt); } }); jTextField_Top5.setEditable(false); jTextField_Top5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top5ActionPerformed(evt); } }); jTextField_Top6.setEditable(false); jTextField_Top6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top6ActionPerformed(evt); } }); jTextField_Top7.setEditable(false); jTextField_Top7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top7ActionPerformed(evt); } }); jTextField_Top8.setEditable(false); jTextField_Top8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextField_Top8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_Top8ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_Top8, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top7, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top6, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top5, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_Top4, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top3, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top2, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_Top1, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton_Entrees, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_Cart, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(277, 277, 277)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(35, 35, 35))) .addComponent(jButton_SignOut, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton_SignOut, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel7) .addGap(18, 18, 18) .addComponent(jTextField_Top1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(jLabel6) .addGap(18, 18, 18) .addComponent(jTextField_Top5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField_Top8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton_Cart, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_Entrees, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29)) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField_Top8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top8ActionPerformed private void jTextField_Top7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top7ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top7ActionPerformed private void jTextField_Top6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top6ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top6ActionPerformed private void jTextField_Top5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top5ActionPerformed private void jTextField_Top4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top4ActionPerformed private void jTextField_Top3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top3ActionPerformed private void jTextField_Top1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top1ActionPerformed private void jTextField_Top2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_Top2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_Top2ActionPerformed private void jButton_CartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CartActionPerformed // TODO add your handling code here: new Cart().setVisible(true); }//GEN-LAST:event_jButton_CartActionPerformed private void jButton_EntreesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EntreesActionPerformed // TODO add your handling code here: new Entrees_page().setVisible(true); }//GEN-LAST:event_jButton_EntreesActionPerformed private void jButton_SignOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SignOutActionPerformed // TODO add your handling code here: int a = JOptionPane.showConfirmDialog(null,"Do you really want to Logout,","Select",JOptionPane.YES_NO_OPTION); if(a == 0){ this.dispose(); new Login_customer().setVisible(true); } }//GEN-LAST:event_jButton_SignOutActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainPortal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainPortal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainPortal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainPortal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainPortal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_Cart; private javax.swing.JButton jButton_Entrees; private javax.swing.JButton jButton_SignOut; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JTextField jTextField_Top1; private javax.swing.JTextField jTextField_Top2; private javax.swing.JTextField jTextField_Top3; private javax.swing.JTextField jTextField_Top4; private javax.swing.JTextField jTextField_Top5; private javax.swing.JTextField jTextField_Top6; private javax.swing.JTextField jTextField_Top7; private javax.swing.JTextField jTextField_Top8; // End of variables declaration//GEN-END:variables }
Amr-Abd-El-Latief/courses
src/com/asset/eg/courses/model/util/OracleConnection.java
package com.asset.eg.courses.model.util; import java.sql.*; // for standard JDBC programs public class OracleConnection { private static final String URL = PropertiesConstants.labels.getString("URL"); private static final String USER = PropertiesConstants.labels.getString("USER"); private static final String PASS = PropertiesConstants.labels.getString("PASS"); //private static Connection conn = null; public static Connection instantiateConnection() throws CoursesException { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection(URL, USER, PASS); conn.setAutoCommit(false); return conn; } catch (ClassNotFoundException ex) { CoursesException CE = new CoursesException(ErrorsStrings.CONNECT_TO_ORACLE_ERROR,ErrorsStrings.CONNECT_TO_ORACLE_MESSAGE); CE.initCause(ex); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.CONNECT_TO_ORACLE_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.CONNECT_TO_ORACLE_ERROR,ErrorsStrings.CONNECT_TO_ORACLE_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.CONNECT_TO_ORACLE_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } public static Connection getOracleConnection() throws CoursesException { return instantiateConnection(); } public static void closeOracleConnection(Connection conn) throws CoursesException { if (conn != null) { try { conn.close(); } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.CLOSE_ORACLE_CONNECTION_ERROR,ErrorsStrings.CLOSE_ORACLE_CONNECTION_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.CLOSE_ORACLE_CONNECTION_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } } public static void closeOracleConnectionSTMNT(PreparedStatement pstmnt) throws CoursesException { if (pstmnt != null) { try { pstmnt.close(); } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.CLOSE_ORACLE_CONNECTION_ERROR,ErrorsStrings.CLOSE_ORACLE_STATEMENT_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.CLOSE_ORACLE_CONNECTION_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } } public static void closeOracleResultSet(ResultSet rs) throws CoursesException { if (rs != null) { try { rs.close(); } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.CLOSE_ORACLE_RESULT_SET_ERROR, ErrorsStrings.CLOSE_ORACLE_RESULT_SET_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.CLOSE_ORACLE_RESULT_SET_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } } public static void commitOracleConnection(Connection conn) throws CoursesException { if (conn != null) { try { conn.commit(); } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.COMMIT_ORACLE_CONNECTION_ERROR,ErrorsStrings.COMMIT_ORACLE_CONNECTION_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.COMMIT_ORACLE_CONNECTION_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } } public static void rollBackOracleConnection(Connection conn) throws CoursesException { if (conn != null) { try { conn.rollback(); } catch (SQLException e) { CoursesException CE = new CoursesException(ErrorsStrings.ROLLBACK_ORACLE_CONNECTION_ERROR,ErrorsStrings.ROLLBACK_ORACLE_CONNECTION_MESSAGE); CE.initCause(e); CoursesLoggers.ORACLECONNECTION.info(ErrorsStrings.ROLLBACK_ORACLE_CONNECTION_MESSAGE); CoursesLoggers.ORACLECONNECTION.error(CE); throw CE; } } } }
paser4se/XCoLab
microservices/clients/contest-client/src/main/java/org/xcolab/client/contest/proposals/ProposalPhaseClientMockImpl.java
<reponame>paser4se/XCoLab package org.xcolab.client.contest.proposals; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import org.xcolab.client.contest.pojo.IProposal2Phase; import org.xcolab.client.contest.pojo.IProposalContestPhaseAttribute; import java.util.Collections; import java.util.List; @Component @Profile("test") public class ProposalPhaseClientMockImpl implements IProposalPhaseClient { @Override public List<IProposal2Phase> getProposal2Phases(Long proposalId, Long contestPhaseId, Integer version) { return Collections.emptyList(); } @Override public void createProposal2Phase(IProposal2Phase proposal2Phase) { } @Override public boolean updateProposal2Phase(IProposal2Phase proposal2Phase) { return false; } @Override public boolean deleteProposal2Phase(IProposal2Phase proposal2Phase) { return false; } @Override public int getProposalCountForActiveContestPhase(Long proposal2PhaseId) { return 0; } @Override public boolean promoteProposal(Long proposalId, Long activePhaseForContest, Long currentProposalContestPhase) { return false; } @Override public List<IProposalContestPhaseAttribute> getProposalContestPhaseAttributes( Long contestPhaseId, Long proposalId, String name) { return Collections.emptyList(); } @Override public IProposalContestPhaseAttribute getProposalContestPhaseAttribute(Long contestPhaseId, Long proposalId, String name) { return null; } @Override public boolean updateProposalContestPhaseAttribute( IProposalContestPhaseAttribute proposalContestPhaseAttribute) { return false; } @Override public IProposalContestPhaseAttribute createProposalContestPhaseAttribute( IProposalContestPhaseAttribute proposalContestPhaseAttribute) { return null; } @Override public boolean deleteProposalContestPhaseAttribute(Long id) { return false; } @Override public List<Long> getContestPhasesForProposal(Long proposalId) { return Collections.emptyList(); } }
wup364/GoFileService
src/gutils/fstool/fstool.go
<filename>src/gutils/fstool/fstool.go // Copyright (C) 2019 WuPeng <<EMAIL>>. // Use of this source code is governed by an MIT-style. // 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. // 文件工具 package fstool import ( "encoding/json" "io" "os" "path" "path/filepath" "strings" "time" ) // CopyCallback 文件复制回调(源路径, 目标路径, 错误信息) 返回的错误信息 type CopyCallback func(srcPath, dstPath string, err error) error // MoveCallback 文件移动回调(源路径, 目标路径, 错误信息) 返回的错误信息 type MoveCallback func(srcPath, dstPath string, err error) error // GetFileInfo 获取文件信息对象 func GetFileInfo(path string) (os.FileInfo, error) { return os.Stat(path) } // OpenFile 获取文件信息对象 func OpenFile(path string) (*os.File, error) { return os.Open(path) } // GetWriter 获取只写文件对象 // O_RDONLY: 只读模式(read-only) // O_WRONLY: 只写模式(write-only) // O_RDWR: 读写模式(read-write) // O_APPEND: 追加模式(append) // O_CREATE: 文件不存在就创建(create a new file if none exists.) // O_EXCL: 与 O_CREATE 一起用, 构成一个新建文件的功能, 它要求文件必须不存在 // O_SYNC: 同步方式打开,即不使用缓存,直接写入硬盘 // O_TRUNC: 打开并清空文件 func GetWriter(path string) (*os.File, error) { return os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) } // IsExist 文件/夹是否存在 func IsExist(path string) bool { _, err := GetFileInfo(path) return err == nil } // IsDir 是否是文件夹 func IsDir(path string) bool { stat, err := GetFileInfo(path) if err == nil { return stat.IsDir() } return false } // MkdirAll 创建文件夹-多级 func MkdirAll(path string) error { return os.MkdirAll(path, os.ModePerm) } // Mkdir 创建文件夹 func Mkdir(path string) error { return os.Mkdir(path, os.ModePerm) } // IsFile 是否是文件 func IsFile(path string) bool { stat, err := GetFileInfo(path) if err == nil { return !stat.IsDir() } return false } // GetDirList 获取一级子目录名字(包含文件|文件夹,无序) func GetDirList(path string) ([]string, error) { f, err := OpenFile(path) defer f.Close() if err != nil { return nil, err } list, err := f.Readdirnames(-1) if err != nil { return nil, err } return list, nil } // GetFileSize 获取文件大小 func GetFileSize(path string) (int64, error) { f, err := OpenFile(path) if err != nil { return 0, err } fInfo, errStat := f.Stat() f.Close() if errStat != nil { return 0, errStat } return fInfo.Size(), nil } // GetCreateTime 获取创建时间 func GetCreateTime(path string) (time.Time, error) { return GetModifyTime(path) } // GetModifyTime 获取修改时间 func GetModifyTime(path string) (time.Time, error) { f, err := OpenFile(path) if err != nil { return time.Time{}, err } fInfo, errStat := f.Stat() f.Close() if errStat != nil { return time.Time{}, errStat } return fInfo.ModTime(), nil } // RemoveFile 删除文件 func RemoveFile(file string) error { if !IsExist(file) { return PathNotExist("RemoveFile", file) } return os.Remove(file) } // RemoveAll 删除文件 func RemoveAll(file string) error { if !IsExist(file) { return PathNotExist("RemoveAll", file) } return os.RemoveAll(file) } // Rename 重命名 func Rename(old, newName string) error { path := path.Clean(old) if strings.Index(path, "\\") > -1 { return os.Rename(old, old[:strings.LastIndex(old, "\\")+1]+newName) } return os.Rename(old, old[:strings.LastIndex(old, "/")+1]+newName) } // MoveFilesAcrossDisk 移动文件|文件夹,可跨分区移动(源路径, 目标路径, 重复覆盖, 重复忽略, 操作回调) 操作结果 func MoveFilesAcrossDisk(src, dst string, replace, ignore bool, callback MoveCallback) error { src = path.Clean(src) dst = path.Clean(dst) if src == dst && len(src) > 0 { return nil } if !IsExist(src) { return PathNotExist("MoveFilesAcrossDisk", src) } // 尝试本分区移动 return MoveFiles(src, dst, replace, ignore, func(srcPath, dstPath string, mverror error) error { // 尝试跨分区移动 if IsAcrossDiskError(mverror) { return MoveFileByCopying(srcPath, dstPath, replace, ignore, callback) } return callback(srcPath, dstPath, mverror) }) } // MoveFiles 移动文件|夹, 如果存在的话就列表后逐一移动 (源路径, 目标路径, 重复覆盖, 重复忽略, 操作回调) 操作结果 func MoveFiles(src, dst string, replace, ignore bool, callback MoveCallback) error { if src == dst && len(src) > 0 { return nil } if !IsExist(src) { return PathNotExist("MoveFiles", src) } if IsExist(dst) { srcIsfile := IsFile(src) dstIsfile := IsFile(dst) var err error // src&dst都是文件夹, 则考虑合并规则, 处理里面的文件 if !srcIsfile && !dstIsfile { list, _ := GetDirList(src) for i := 0; i < len(list); i++ { err = MoveFiles(src+"/"+list[i], dst+"/"+list[i], replace, ignore, callback) if err != nil { return err // 返回终止信号 } } if IsExist(src) { return callback(src, dst, os.RemoveAll(src)) } return nil } // 非合并模式只考虑删除目标位置 if ignore { // 如果忽略则不返回错误 return callback(src, dst, err) } else if replace { // 如果覆盖, 则先删除目标位置 if dstIsfile { err = os.Remove(dst) } else { err = os.RemoveAll(dst) } } else { err = PathExist("MoveFiles", dst) } if nil != err { return callback(src, dst, err) } return callback(src, dst, os.Rename(src, dst)) } // 如果目标文件/夹不存在就直接移动 return callback(src, dst, os.Rename(src, dst)) } // MoveFileByCopying 移动文件夹 - 跨分区-拷贝 func MoveFileByCopying(src, dst string, replace, ignore bool, callback MoveCallback) error { if src == dst && len(src) > 0 { return nil } if IsFile(src) { var err1 error err := CopyFile(src, dst, replace, ignore) if err != nil { err1 = callback(src, dst, err) } if err1 != nil { return err1 } else if err != nil { return nil } return os.Remove(src) } // 复制文件夹 err := CopyFiles(path.Clean(src), path.Clean(dst), replace, ignore, func(srcPath, dstPath string, err error) error { if err == nil && IsFile(srcPath) { err = os.Remove(srcPath) } return callback(srcPath, dstPath, err) }) // 最后的清理 if err == nil { err = os.RemoveAll(src) } return err } // CopyFile 复制文件(源路径, 目标路径, 重复覆盖, 重复忽略) func CopyFile(src, dst string, replace, ignore bool) error { if src == dst && len(src) > 0 { return nil } if !IsFile(src) { return PathNotExist("CopyFile", src) } if IsExist(dst) { if replace { var err error if IsFile(src) { err = os.Remove(dst) } else { err = os.RemoveAll(dst) } if err != nil { return err } } else if ignore { return nil } else { return PathExist("CopyFile", dst) } } RSrc, err := OpenFile(src) defer func() { if nil != RSrc { RSrc.Close() } }() if err != nil { return err } WDst, err := GetWriter(dst) defer func() { if nil != WDst { WDst.Close() } }() if err != nil { return err } _, err = io.Copy(WDst, RSrc) return err } // CopyFiles 复制文件夹 (源路径, 目标路径, 重复覆盖, 重复忽略, 操作回调) 返回错误即可终止后续拷贝 // 如果callback返回错误非空, 该文件则为处理失败, 终止其他操作 // 如果callback返回nil则继续往下拷贝, 无论是否真的出错 func CopyFiles(src, dst string, replace, ignore bool, callback CopyCallback) error { if src == dst && len(src) > 0 { return nil } if !IsExist(src) { return callback(src, dst, PathNotExist("CopyFiles", src)) } if IsFile(dst) { return callback(src, dst, PathExist("CopyFiles", dst)) } srcLen := len(src) return filepath.Walk(src, func(s string, f os.FileInfo, err error) error { d := dst + s[srcLen:] if err == nil { if f.IsDir() { if !IsDir(d) { err = os.Mkdir(d, os.ModePerm) } } else { err = CopyFile(s, d, replace, ignore) } } return callback(s, d, err) }) } // ReadFileAsJSON 读取Json文件 func ReadFileAsJSON(path string, v interface{}) error { if len(path) == 0 { return PathNotExist("ReadFileAsJSON", path) } fp, err := os.OpenFile(path, os.O_RDONLY, 0) defer func() { if nil != fp { fp.Close() } }() if err == nil { st, stErr := fp.Stat() if stErr == nil { data := make([]byte, st.Size()) _, err = fp.Read(data) if err == nil { return json.Unmarshal(data, v) } } else { err = stErr } } return err } // WriteFileAsJSON 写入Json文件 func WriteFileAsJSON(path string, v interface{}) error { if len(path) == 0 { return PathNotExist("WriteFileAsJSON", path) } fp, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) defer func() { if nil != fp { fp.Close() } }() if err == nil { data, err := json.Marshal(v) if err == nil { _, err := fp.Write(data) return err } return err } return err } // WriteTextFile 写入文本文件 func WriteTextFile(path, text string) error { if len(path) == 0 { return PathNotExist("WriteFile", path) } fp, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) defer func() { if nil != fp { fp.Close() } }() if err == nil { if err == nil { _, err := fp.Write([]byte(text)) return err } return err } return err } // PathExist 路径已经存在的错误 func PathExist(op, path string) error { return &os.PathError{ Op: op, Path: path, Err: os.ErrExist, } } // PathNotExist 路径不存在的错误 func PathNotExist(op, path string) error { return &os.PathError{ Op: op, Path: path, Err: os.ErrNotExist, } } // IsExistError 是否是目标位置已经存在的错误 func IsExistError(err error) bool { if nil == err { return false } var cpErr error switch err := err.(type) { case *os.PathError: cpErr = err.Err } if cpErr == nil { return false } return cpErr.Error() == os.ErrExist.Error() } // IsNotExistError 是否是目标位置不存在的错误 func IsNotExistError(err error) bool { var cpErr error switch err := err.(type) { case *os.PathError: cpErr = err.Err } if cpErr == nil { return false } return cpErr.Error() == os.ErrNotExist.Error() } // IsAcrossDiskError 是否是跨磁盘错误 func IsAcrossDiskError(err error) bool { var cpErr error switch err := err.(type) { case *os.LinkError: cpErr = err.Err } if cpErr == nil { return false } return cpErr.Error() == "The system cannot move the file to a different disk drive." }
ZRY551-DevelopGroup/MCMod_IKnowIt
build/tmp/expandedArchives/forge-1.16.5-36.2.19_mapped_official_1.16.5-sources.jar_96953985799bf045b80c10dc6b54685a/net/minecraft/data/DirectoryCache.java
<gh_stars>1-10 package net.minecraft.data; import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class DirectoryCache { private static final Logger LOGGER = LogManager.getLogger(); private final Path path; private final Path cachePath; private int hits; private final Map<Path, String> oldCache = Maps.newHashMap(); private final Map<Path, String> newCache = Maps.newHashMap(); private final Set<Path> keep = Sets.newHashSet(); public DirectoryCache(Path p_i49352_1_, String p_i49352_2_) throws IOException { this.path = p_i49352_1_; Path path = p_i49352_1_.resolve(".cache"); Files.createDirectories(path); this.cachePath = path.resolve(p_i49352_2_); this.walkOutputFiles().forEach((p_209395_1_) -> { String s = this.oldCache.put(p_209395_1_, ""); }); if (Files.isReadable(this.cachePath)) { IOUtils.readLines(Files.newInputStream(this.cachePath), Charsets.UTF_8).forEach((p_208315_2_) -> { int i = p_208315_2_.indexOf(32); this.oldCache.put(p_i49352_1_.resolve(p_208315_2_.substring(i + 1)), p_208315_2_.substring(0, i)); }); } } public void purgeStaleAndWrite() throws IOException { this.removeStale(); Writer writer; try { writer = Files.newBufferedWriter(this.cachePath); } catch (IOException ioexception) { LOGGER.warn("Unable write cachefile {}: {}", this.cachePath, ioexception.toString()); return; } IOUtils.writeLines(this.newCache.entrySet().stream().map((p_208319_1_) -> { return (String)p_208319_1_.getValue() + ' ' + this.path.relativize(p_208319_1_.getKey()).toString().replace('\\', '/'); //Forge: Standardize file paths. }).sorted(java.util.Comparator.comparing(a -> a.split(" ")[1])).collect(Collectors.toList()), System.lineSeparator(), writer); writer.close(); LOGGER.debug("Caching: cache hits: {}, created: {} removed: {}", this.hits, this.newCache.size() - this.hits, this.oldCache.size()); } @Nullable public String getHash(Path p_208323_1_) { return this.oldCache.get(p_208323_1_); } public void putNew(Path p_208316_1_, String p_208316_2_) { this.newCache.put(p_208316_1_, p_208316_2_); if (Objects.equals(this.oldCache.remove(p_208316_1_), p_208316_2_)) { ++this.hits; } } public boolean had(Path p_208320_1_) { return this.oldCache.containsKey(p_208320_1_); } public void keep(Path p_218456_1_) { this.keep.add(p_218456_1_); } private void removeStale() throws IOException { this.walkOutputFiles().forEach((p_208322_1_) -> { if (this.had(p_208322_1_) && !this.keep.contains(p_208322_1_)) { try { Files.delete(p_208322_1_); } catch (IOException ioexception) { LOGGER.debug("Unable to delete: {} ({})", p_208322_1_, ioexception.toString()); } } }); } private Stream<Path> walkOutputFiles() throws IOException { return Files.walk(this.path).filter((p_209397_1_) -> { return !Objects.equals(this.cachePath, p_209397_1_) && !Files.isDirectory(p_209397_1_); }); } }
arunrapolu4491/representation-grant-app
api/api/migrations/0009_auto_20210212_0815.py
<gh_stars>0 # Generated by Django 3.1.6 on 2021-02-12 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("api", "0008_user_location"), ] operations = [ migrations.RemoveField( model_name="application", name="protected_child_name", ), migrations.RemoveField( model_name="application", name="protected_party_name", ), migrations.RemoveField( model_name="application", name="respondent_name", ), migrations.AddField( model_name="application", name="date_of_will", field=models.DateTimeField(blank=True, null=True), ), migrations.AddField( model_name="application", name="deceased_date_of_death", field=models.DateTimeField(blank=True, null=True), ), migrations.AddField( model_name="application", name="deceased_name", field=models.JSONField(blank=True, null=True), ), ]
ppavlidis/aspiredb
aspiredb/src/main/java/ubc/pavlab/aspiredb/server/dao/RemotePaging.java
<reponame>ppavlidis/aspiredb /* * The aspiredb project * * Copyright (c) 2012 University of British Columbia * * 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 ubc.pavlab.aspiredb.server.dao; import java.util.Collection; import java.util.Set; import org.springframework.transaction.annotation.Transactional; import ubc.pavlab.aspiredb.server.exceptions.BioMartServiceException; import ubc.pavlab.aspiredb.server.exceptions.NeurocartaServiceException; import ubc.pavlab.aspiredb.shared.query.AspireDbFilterConfig; public interface RemotePaging<T> { @Transactional(readOnly = true) public Collection<? extends T> load( Set<AspireDbFilterConfig> filters ) throws BioMartServiceException, NeurocartaServiceException; @Transactional(readOnly = true) public Page<? extends T> loadPage( int offset, int limit, String sortProperty, String sortDirection, Set<AspireDbFilterConfig> filters ) throws BioMartServiceException, NeurocartaServiceException; }
roman-sd/java-a-to-z
chapter_005/src/test/java/ru/sdroman/pro/list/loop/LoopListTest.java
package ru.sdroman.pro.list.loop; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * Test LoopList class. * @author sdroman * @since 04.17 */ public class LoopListTest { /** * Test hasCycle method. */ @Test public void hasCycleTest() { LoopList list = new LoopList(); final LoopList.Node<Integer> first = new LoopList.Node<>(1); final LoopList.Node<Integer> two = new LoopList.Node<>(2); final LoopList.Node<Integer> third = new LoopList.Node<>(3); final LoopList.Node<Integer> four = new LoopList.Node<>(4); first.setNext(two); first.setNext(third); first.setNext(four); first.setNext(first); assertTrue(list.hasCycle(first)); } }
joker-pper/rdt-v2
rdt-core/src/main/java/com/joker17/redundant/operation/AbstractComplexOperation.java
<filename>rdt-core/src/main/java/com/joker17/redundant/operation/AbstractComplexOperation.java package com.joker17.redundant.operation; import com.joker17.redundant.core.RdtConfiguration; import com.joker17.redundant.model.*; import java.util.*; public abstract class AbstractComplexOperation extends AbstractOperation { protected Map<ClassModel, Map<ComplexAnalysis, Map<String, Object>>> classModelLogicalConditionCacheMap = new HashMap<ClassModel, Map<ComplexAnalysis, Map<String, Object>>>(16); public AbstractComplexOperation(RdtConfiguration configuration) { super(configuration); } @Override protected void updateMultiCore(ClassModel classModel, ChangedVo changedVo) { super.updateMultiCore(classModel, changedVo); updateModifyComplex(classModel, changedVo); } /** * 复杂数据的处理 * * @param classModel * @param vo */ protected void updateModifyComplex(final ClassModel classModel, final ChangedVo vo) { //获取classModel相关的非base关系类 Set<Class> complexClassSet = classModel.getChangedComplexClassSet(); if (!complexClassSet.isEmpty()) { final List<String> changedPropertys = vo.getChangedPropertys(); for (Class complexClass : complexClassSet) { //获取complexClass所拥有的复杂关系对象组合 List<ComplexAnalysis> complexAnalysisList = configuration.getComplexAnalysisList(complexClass); ClassModel complexClassModel = getClassModel(complexClass); for (final ComplexAnalysis complexAnalysis : complexAnalysisList) { if (complexAnalysis.getHasMany()) { //包含many时,即存在数组/集合的子对象 configuration.doModifyDescribeHandle(classModel, complexClassModel, new RdtConfiguration.ModifyDescribeCallBack() { @Override public void execute(ClassModel classModel, ClassModel modifyClassModel, ModifyDescribe describe) { ModifyDescribe currentDescribe = configuration.getModifyDescribe(describe, changedPropertys); //获取当前的修改条件 if (currentDescribe != null) { updateModifyDescribeMany(classModel, modifyClassModel, complexAnalysis, currentDescribe, vo); } } }); configuration.doModifyRelyDescribeHandle(classModel, complexClassModel, new RdtConfiguration.ModifyRelyDescribeCallBack() { @Override public void execute(ClassModel classModel, ClassModel modifyClassModel, Column relyColumn, int group, ModifyRelyDescribe describe) { ModifyRelyDescribe currentDescribe = configuration.getModifyRelyDescribe(describe, changedPropertys); if (currentDescribe != null) { updateModifyRelyDescribeMany(classModel, modifyClassModel, complexAnalysis, currentDescribe, vo, relyColumn, group); } } }); } else { //全部为one时 configuration.doModifyDescribeHandle(classModel, complexClassModel, new RdtConfiguration.ModifyDescribeCallBack() { @Override public void execute(ClassModel classModel, ClassModel modifyClassModel, ModifyDescribe describe) { ModifyDescribe currentDescribe = configuration.getModifyDescribe(describe, changedPropertys); //获取当前的修改条件 if (currentDescribe != null) { updateModifyDescribeOne(classModel, modifyClassModel, complexAnalysis, currentDescribe, vo); } } }); configuration.doModifyRelyDescribeHandle(classModel, complexClassModel, new RdtConfiguration.ModifyRelyDescribeCallBack() { @Override public void execute(ClassModel classModel, ClassModel modifyClassModel, Column relyColumn, int group, ModifyRelyDescribe describe) { ModifyRelyDescribe currentDescribe = configuration.getModifyRelyDescribe(describe, changedPropertys); if (currentDescribe != null) { updateModifyRelyDescribeOne(classModel, modifyClassModel, complexAnalysis, currentDescribe, vo, relyColumn, group); } } }); } } } } } /** * 处理当前保存实体值变化时所要修改相关实体类的字段数据的业务逻辑 * * @param classModel 触发更新的实体 * @param complexClassModel 当前处理的complexClassModel * @param complexAnalysis * @param describe 对应的修改信息 * @param vo */ protected void updateModifyDescribeOne(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ModifyDescribe describe, final ChangedVo vo) { ClassModel modifyClassModel = getModifyDescribeOneModifyClassModel(complexClassModel, complexAnalysis); //获取当前要修改的base model Exception exception = null; try { updateModifyDescribeOneImpl(classModel, complexClassModel, complexAnalysis, modifyClassModel, describe, vo); } catch (Exception e) { exception = e; } updateModifyDescribeOneLogOutput(classModel, complexClassModel, modifyClassModel, complexAnalysis, describe, vo, exception); if (exception != null) { handlerUpdateThrowException(exception); } } protected abstract ClassModel getModifyDescribeOneModifyClassModel(ClassModel complexClassModel, ComplexAnalysis complexAnalysis); protected abstract String getModifyDescribeOneProperty(ClassModel classModel, ClassModel complexClassModel, ComplexAnalysis complexAnalysis, ModifyCondition modifyCondition); protected abstract String getModifyDescribeOneProperty(ClassModel classModel, ClassModel complexClassModel, ComplexAnalysis complexAnalysis, ModifyColumn column); protected abstract void updateModifyDescribeOneImpl(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ClassModel modifyClassModel, final ModifyDescribe describe, final ChangedVo vo); protected void updateModifyRelyDescribeOne(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ModifyRelyDescribe describe, final ChangedVo vo, final Column relyColumn, final int group) { ClassModel modifyClassModel = getModifyRelyDescribeOneModifyClassModel(complexClassModel, complexAnalysis); Exception exception = null; try { updateModifyRelyDescribeOneImpl(classModel, complexClassModel, complexAnalysis, modifyClassModel, describe, vo, relyColumn, group); } catch (Exception e) { exception = e; } updateModifyRelyDescribeOneLogOutput(classModel, complexClassModel, modifyClassModel, complexAnalysis, describe, vo, relyColumn, group, exception); if (exception != null) { handlerUpdateThrowException(exception); } } protected void updateModifyDescribeOneLogOutput(final ClassModel classModel, final ClassModel complexClassModel, final ClassModel modifyClassModel, final ComplexAnalysis complexAnalysis, final ModifyDescribe describe, final ChangedVo vo, Exception exception) { boolean hasException = exception != null; if (isLoggerSupport() || hasException) { RdtLog rdtLog = new RdtLog(); final Map<String, Object> conditionLogMap = rdtLog.getCondition(); final Map<String, Object> updateLogMap = rdtLog.getUpdate(); configuration.doModifyConditionHandle(vo, describe, new RdtConfiguration.ModifyConditionCallBack() { @Override public void execute(ModifyCondition modifyCondition, int position, String targetProperty, Object targetPropertyVal) { String property = getModifyDescribeOneProperty(classModel, complexClassModel, complexAnalysis, modifyCondition); conditionLogMap.put(getPropertyMark(property, targetProperty), targetPropertyVal); } }); configuration.doLogicalModelHandle(modifyClassModel, properties.getUpdateMultiWithLogical(), new RdtConfiguration.LogicalModelCallBack() { @Override public void execute(ClassModel dataModel, LogicalModel logicalModel) { String logicalProperty = logicalModel.getColumn().getProperty(); List<Object> values = logicalModel.getValues(); conditionLogMap.put(logicalProperty, values); } }); doComplexClassLogicalConditionHandle(classModel, complexClassModel, modifyClassModel, complexAnalysis, properties.getUpdateMultiWithLogical(), new ComplexClassLogicalConditionCallBack() { @Override public void execute(String logicalProperty, Object logicalValue) { conditionLogMap.put(logicalProperty, logicalValue); } }); configuration.doModifyColumnHandle(vo, describe, new RdtConfiguration.ModifyColumnCallBack() { @Override public void execute(ModifyColumn modifyColumn, int position, String targetProperty, Object targetPropertyVal) { String property = getModifyDescribeOneProperty(classModel, complexClassModel, complexAnalysis, modifyColumn); updateLogMap.put(getPropertyMark(property, targetProperty), targetPropertyVal); } }); if (hasException) { logger.warn("{} modify about {}【{}={}】data with complex【{}】 has error, index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate()), exception); } else { loggerSupport("{} modify about {}【{}={}】data with complex【{}】, index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate())); } } } protected void updateModifyRelyDescribeOneLogOutput(final ClassModel classModel, final ClassModel complexClassModel, final ClassModel modifyClassModel, final ComplexAnalysis complexAnalysis, final ModifyRelyDescribe describe, final ChangedVo vo, final Column relyColumn, final int group, final Exception exception) { boolean hasException = exception != null; if (isLoggerSupport() || hasException) { RdtLog rdtLog = new RdtLog(); final Map<String, Object> conditionLogMap = rdtLog.getCondition(); final Map<String, Object> updateLogMap = rdtLog.getUpdate(); configuration.doModifyConditionHandle(vo, describe, new RdtConfiguration.ModifyConditionCallBack() { @Override public void execute(ModifyCondition modifyCondition, int position, String targetProperty, Object targetPropertyVal) { String property = getModifyRelyDescribeOneProperty(classModel, complexClassModel, complexAnalysis, modifyCondition); conditionLogMap.put(getPropertyMark(property, targetProperty), targetPropertyVal); } }); doComplexClassLogicalConditionHandle(classModel, complexClassModel, modifyClassModel, complexAnalysis, properties.getUpdateMultiWithLogical(), new ComplexClassLogicalConditionCallBack() { @Override public void execute(String logicalProperty, Object logicalValue) { conditionLogMap.put(logicalProperty, logicalValue); } }); configuration.doModifyColumnHandle(vo, describe, new RdtConfiguration.ModifyColumnCallBack() { @Override public void execute(ModifyColumn modifyColumn, int position, String targetProperty, Object targetPropertyVal) { String property = getModifyRelyDescribeOneProperty(classModel, complexClassModel, complexAnalysis, modifyColumn); updateLogMap.put(getPropertyMark(property, targetProperty), targetPropertyVal); } }); String relyProperty = getModifyRelyDescribeOneProperty(classModel, complexClassModel, complexAnalysis, relyColumn); rdtLog.putConditionTop(getModelTypeProcessingCriteriaMap(describe, relyProperty)); if (hasException) { logger.warn("{} modify about {}【{}={}】data with complex【{}】and rely column - 【name: {}, group: {} 】has error , index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), relyColumn.getProperty(), group, describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate()), exception); } else { loggerSupport("{} modify about {}【{}={}】data with complex【{}】and rely column - 【name: {}, group: {} 】 , index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), relyColumn.getProperty(), group, describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate())); } } } protected abstract ClassModel getModifyRelyDescribeOneModifyClassModel(ClassModel complexClassModel, ComplexAnalysis complexAnalysis); protected abstract String getModifyRelyDescribeOneProperty(ClassModel classModel, ClassModel complexClassModel, ComplexAnalysis complexAnalysis, ModifyCondition modifyCondition); protected abstract String getModifyRelyDescribeOneProperty(ClassModel classModel, ClassModel complexClassModel, ComplexAnalysis complexAnalysis, ModifyColumn modifyColumn); protected abstract String getModifyRelyDescribeOneProperty(ClassModel classModel, ClassModel complexClassModel, ComplexAnalysis complexAnalysis, Column column); protected abstract void updateModifyRelyDescribeOneImpl(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ClassModel modifyClassModel, final ModifyRelyDescribe describe, final ChangedVo vo, final Column relyColumn, final int group); protected void updateModifyDescribeMany(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ModifyDescribe describe, final ChangedVo vo) { ClassModel modifyClassModel = getModifyDescribeManyModifyClassModel(complexClassModel, complexAnalysis); RdtLog rdtLog = new RdtLog(); try { updateModifyDescribeManyImpl(classModel, complexClassModel, complexAnalysis, modifyClassModel, describe, vo, rdtLog); loggerSupport("{} modify about {}【{}={}】data with complex【{}】, index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate())); } catch (Exception e) { logger.warn("{} modify about {}【{}={}】data with complex【{}】has error, index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate()), e); handlerUpdateThrowException(e); } } protected abstract ClassModel getModifyDescribeManyModifyClassModel(ClassModel complexClassModel, ComplexAnalysis complexAnalysis); protected abstract void updateModifyDescribeManyImpl(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ClassModel modifyClassModel, final ModifyDescribe describe, final ChangedVo vo, RdtLog rdtLog); protected void updateModifyRelyDescribeMany(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ModifyRelyDescribe describe, final ChangedVo vo, final Column relyColumn, final int group) { ClassModel modifyClassModel = getModifyRelyDescribeManyModifyClassModel(complexClassModel, complexAnalysis); RdtLog rdtLog = new RdtLog(); try { updateModifyRelyDescribeManyImpl(classModel, complexClassModel, complexAnalysis, modifyClassModel, describe, vo, relyColumn, group, rdtLog); loggerSupport("{} modify about {}【{}={}】data with complex【{}】and rely column - 【name: {}, group: {} 】 , index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), relyColumn.getProperty(), group, describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate())); } catch (Exception e) { logger.warn("{} modify about {}【{}={}】data with complex【{}】and rely column - 【name: {}, group: {} 】has error, index: {}, conditions: {}, updates: {}", modifyClassModel.getClassName(), classModel.getClassName(), vo.getPrimaryId(), vo.getPrimaryIdVal(), complexAnalysis.getPrefix(), relyColumn.getProperty(), group, describe.getIndex(), rdtResolver.toJson(rdtLog.getCondition()), rdtResolver.toJson(rdtLog.getUpdate()), e); handlerUpdateThrowException(e); } } protected abstract ClassModel getModifyRelyDescribeManyModifyClassModel(ClassModel complexClassModel, ComplexAnalysis complexAnalysis); protected abstract void updateModifyRelyDescribeManyImpl(final ClassModel classModel, final ClassModel complexClassModel, final ComplexAnalysis complexAnalysis, final ClassModel modifyClassModel, final ModifyRelyDescribe describe, final ChangedVo vo, final Column relyColumn, final int group, RdtLog rdtLog); protected Map<ComplexAnalysis, Map<String, Object>> getComplexAnalysisLogicalConditionMap(final ClassModel classModel) { Map<ComplexAnalysis, Map<String, Object>> complexAnalysisLogicalConditionMap = classModelLogicalConditionCacheMap.get(classModel); if (complexAnalysisLogicalConditionMap == null) { synchronized (this) { complexAnalysisLogicalConditionMap = classModelLogicalConditionCacheMap.get(classModel); if (complexAnalysisLogicalConditionMap == null) { complexAnalysisLogicalConditionMap = new HashMap<ComplexAnalysis, Map<String, Object>>(); classModelLogicalConditionCacheMap.put(classModel, complexAnalysisLogicalConditionMap); } } } return complexAnalysisLogicalConditionMap; } /** * 获取当前参数所对应的逻辑状态值条件(不包含第一层modifyClassModel的数据) * @param classModel * @param complexClassModel * @param modifyClassModel * @param complexAnalysis * @return */ protected Map<String, Object> getComplexClassLogicalConditionMap(final ClassModel classModel, final ClassModel complexClassModel, final ClassModel modifyClassModel, final ComplexAnalysis complexAnalysis) { Map<ComplexAnalysis, Map<String, Object>> complexAnalysisLogicalConditionMap = getComplexAnalysisLogicalConditionMap(classModel); Map<String, Object> resultMap = complexAnalysisLogicalConditionMap.get(complexAnalysis); if (resultMap == null) { synchronized (this) { resultMap = complexAnalysisLogicalConditionMap.get(complexAnalysis); if (resultMap == null) { resultMap = new LinkedHashMap<String, Object>(16); final Map<String, Object> finalConditionMap = resultMap; doWithComplexClassLogicalModelHandle(classModel, complexClassModel, modifyClassModel, complexAnalysis, new doWithComplexClassLogicalModelCallBack() { @Override void run(ClassModel currentClassModel, LogicalModel logicalModel, int position, Object logicalValues) { String logicalProperty = getLogicalProperty(classModel, complexClassModel, modifyClassModel, currentClassModel, complexAnalysis, logicalModel, position); finalConditionMap.put(logicalProperty, logicalValues); } }); complexAnalysisLogicalConditionMap.put(complexAnalysis, finalConditionMap); } } } return resultMap; } protected abstract class doWithComplexClassLogicalModelCallBack { abstract void run(ClassModel currentClassModel, LogicalModel logicalModel, int position, Object logicalValues); } /** * 处理当前classModel与complexAnalysis之间的多组逻辑条件关系 * @param classModel * @param complexClassModel * @param modifyClassModel * @param complexAnalysis * @param callback */ protected void doWithComplexClassLogicalModelHandle(final ClassModel classModel, final ClassModel complexClassModel, final ClassModel modifyClassModel, final ComplexAnalysis complexAnalysis, final doWithComplexClassLogicalModelCallBack callback) { List<Class> classList = complexAnalysis.getCurrentTypeList(); int size = classList.size(); for (int i = 0; i < size; i ++) { ClassModel currentClassModel = getClassModel(classList.get(i)); final int position = i; configuration.doLogicalModelHandle(currentClassModel, true, new RdtConfiguration.LogicalModelCallBack() { @Override public void execute(ClassModel dataModel, LogicalModel logicalModel) { if (callback != null) { List<Object> values = logicalModel.getValues(); callback.run(dataModel, logicalModel, position, values); } } }); } } /** * 根据当前参数获取逻辑条件的property(基于modifyClassModel的逻辑状态属性) * @param classModel * @param complexClassModel * @param modifyClassModel * @param currentClassModel * @param complexAnalysis * @param logicalModel * @param position * @return */ protected String getLogicalProperty(ClassModel classModel, ClassModel complexClassModel, ClassModel modifyClassModel, ClassModel currentClassModel, ComplexAnalysis complexAnalysis, LogicalModel logicalModel, int position) { StringBuilder sb = new StringBuilder(); List<String> propertyList = complexAnalysis.getPropertyList(); for (int i = 0; i < position + 1; i ++) { sb.append(propertyList.get(i)); sb.append("."); } sb.append(logicalModel.getColumn().getProperty()); return sb.toString(); } protected abstract class ComplexClassLogicalConditionCallBack { public abstract void execute(String logicalProperty, Object logicalValue); } protected void doComplexClassLogicalConditionHandle(final ClassModel classModel, final ClassModel complexClassModel, final ClassModel modifyClassModel, final ComplexAnalysis complexAnalysis, boolean logical, ComplexClassLogicalConditionCallBack callback) { if (logical) { Map<String, Object> resultMap = getComplexClassLogicalConditionMap(classModel, complexClassModel, modifyClassModel, complexAnalysis); if (!resultMap.isEmpty()) { for (String logicalProperty : resultMap.keySet()) { callback.execute(logicalProperty, resultMap.get(logicalProperty)); } } } else { callback = null; } } }
danielstegmeier/assertj-swing
assertj-swing/src/main/java/org/assertj/swing/awt/AWT.java
<filename>assertj-swing/src/main/java/org/assertj/swing/awt/AWT.java /* * 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. * * Copyright 2012-2018 the original author or authors. */ package org.assertj.swing.awt; import static java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment; import static java.awt.event.InputEvent.BUTTON3_MASK; import static org.assertj.core.util.Preconditions.checkNotNull; import static org.assertj.swing.edt.GuiActionRunner.execute; import static org.assertj.swing.util.Platform.isWindows; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import org.assertj.swing.annotation.RunsInCurrentThread; import org.assertj.swing.annotation.RunsInEDT; import org.assertj.swing.util.ToolkitProvider; /** * Utility methods related to AWT. * * @author <NAME> */ public class AWT { private static final String ROOT_FRAME_CLASSNAME = SwingUtilities.class.getName() + "$"; private static final ToolkitProvider TOOLKIT_PROVIDER = ToolkitProvider.instance(); /** * Indicates whether the given point, relative to the given {@code JComponent}, is inside the screen boundaries. * * @param c the given {@code JComponent}. * @param p the point to verify. * @return {@code true} if the point is inside the screen boundaries; {@code false} otherwise. */ @RunsInCurrentThread public static boolean isPointInScreenBoundaries(@Nonnull JComponent c, @Nonnull Point p) { Point where = translate(c, p.x, p.y); return isPointInScreenBoundaries(where); } /** * Indicates whether the given point is inside the screen boundaries. * * @param p the point to verify. * @return {@code true} if the point is inside the screen boundaries; {@code false} otherwise. */ public static boolean isPointInScreenBoundaries(@Nonnull Point p) { for (GraphicsDevice screen : getLocalGraphicsEnvironment().getScreenDevices()) { for (GraphicsConfiguration conf : screen.getConfigurations()) { if (conf.getBounds().contains(p)) { return true; } } } return false; } /** * <p> * Translates the given coordinates to the location on screen of the given AWT or Swing {@code Component}. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code Component}. * @param x X coordinate. * @param y Y coordinate. * @return the translated coordinates. */ @RunsInCurrentThread @Nullable public static Point translate(@Nonnull Component c, int x, int y) { Point p = locationOnScreenOf(c); if (p == null) { return null; } p.translate(x, y); return p; } /** * Returns a point at the center of the visible area of the given AWT or Swing {@code Component}. * * @param c the given {@code Component}. * @return a point at the center of the visible area of the given {@code Component}. */ @RunsInEDT @Nonnull public static Point visibleCenterOf(@Nonnull final Component c) { Point center = execute(() -> { if (c instanceof JComponent) { return centerOfVisibleRect((JComponent) c); } return centerOf(c); }); return checkNotNull(center); } /** * <p> * Returns a point at the center of the given AWT or Swing {@code Component}. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code Component}. * @return a point at the center of the given {@code Component}. */ @RunsInCurrentThread @Nonnull public static Point centerOf(@Nonnull Component c) { Dimension size = c.getSize(); return new Point(size.width / 2, size.height / 2); } /** * <p> * Returns a point at the center of the visible rectangle of the given {@code JComponent}. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code JComponent}. * @return a point at the center of the visible rectangle of the given {@code JComponent}. */ @RunsInCurrentThread @Nonnull public static Point centerOfVisibleRect(@Nonnull JComponent c) { Rectangle r = c.getVisibleRect(); return centerOf(checkNotNull(r)); } /** * <p> * Returns a point at the center of the given {@code Rectangle}. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param r the given {@code Rectangle}. * @return a point at the center of the given {@code Rectangle}. */ @RunsInCurrentThread @Nonnull public static Point centerOf(@Nonnull Rectangle r) { return new Point((r.x + (r.width / 2)), (r.y + (r.height / 2))); } /** * <p> * Returns the insets of the given AWT or Swing {@code Container}, or an empty one if no insets can be found. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code Container}. * @return the insets of the given {@code Container}, or an empty one if no insets can be found. */ @RunsInCurrentThread @Nonnull public static Insets insetsFrom(@Nonnull Container c) { try { Insets insets = c.getInsets(); if (insets != null) { return insets; } } catch (Exception e) { } return new Insets(0, 0, 0, 0); } /** * Returns {@code true} if the given component is an Applet viewer. * * @param c the component to check. * @return {@code true} if the given component is an Applet viewer, {@code false} otherwise. */ public static boolean isAppletViewer(@Nullable Component c) { return c != null && "sun.applet.AppletViewer".equals(c.getClass().getName()); } /** * Returns whether the given component is the default Swing hidden frame. * * @param c the component to check. * @return {@code true} if the given component is the default hidden frame, {@code false} otherwise. */ public static boolean isSharedInvisibleFrame(@Nullable Component c) { if (c == null) { return false; } // Must perform an additional check, since applets may have their own version in their AppContext return c instanceof Frame && (c == JOptionPane.getRootFrame() || c.getClass().getName().startsWith(ROOT_FRAME_CLASSNAME)); } /** * <p> * Returns whether the given AWT or Swing {@code Component} is a heavy-weight pop-up, that is, a container for a * {@code JPopupMenu} that is implemented with a heavy-weight component (usually an AWT or Swing {@code Window}). * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code Component}. * @return {@code true} if the given {@code Component} is a heavy-weight pop-up; {@code false} otherwise. */ @RunsInCurrentThread public static boolean isHeavyWeightPopup(@Nonnull Component c) { if (!(c instanceof Window) || c instanceof Dialog || c instanceof Frame) { return false; } String name = obtainNameSafely(c); if ("###overrideRedirect###".equals(name) || "###focusableSwingPopup###".equals(name)) { return true; } String typeName = c.getClass().getName(); return typeName.contains("PopupFactory$WindowPopup") || typeName.contains("HeavyWeightWindow"); } @RunsInCurrentThread @Nullable private static String obtainNameSafely(@Nonnull Component c) { // Work around some components throwing exceptions if getName is called prematurely try { return c.getName(); } catch (Throwable e) { return null; } } /** * <p> * Returns the invoker, if any, of the given AWT or Swing {@code Component}; or {@code null}, if the {@code Component} * is not on a pop-up of any sort. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given {@code Component}. * @return the invoker, if any, of the given {@code Component}; or {@code null}, if the {@code Component} is not on a * pop-up of any sort. */ @RunsInCurrentThread @Nullable public static Component invokerOf(final @Nonnull Component c) { if (c instanceof JPopupMenu) { return ((JPopupMenu) c).getInvoker(); } Container parent = c.getParent(); return parent != null ? invokerOf(parent) : null; } /** * <p> * Wrapper for {@code Component.getLocationOnScreen}. * </p> * * <p> * <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event * dispatch thread (EDT). Client code must call this method from the EDT. * </p> * * @param c the given AWT or Swing {@code Component}. * @return the a point specifying the {@code Component}'s top-left corner in the screen's coordinate space. */ @RunsInCurrentThread @Nonnull public static Point locationOnScreenOf(@Nonnull Component c) { return new Point(c.getLocationOnScreen()); } /** * Returns whether the platform registers a pop-up on mouse press. * * @return {@code true} if the platform registers a pop-up on mouse press, {@code false} otherwise. */ public static boolean popupOnPress() { // Only w32 is pop-up on release return !isWindows(); } /** * @return the {@code InputEvent} mask for the pop-up trigger button. */ public static int popupMask() { return BUTTON3_MASK; } private AWT() { } }
acidicMercury8/xray-1.6
src/editors/PPEditor/effect.cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "effect.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //--------------------------------------------------------------------------- Effect::Effect (Graphics::TBitmap *host) { m_Host = host; m_BaseColor = new ColorParam (host); m_AddColor = new ColorParam (host); m_GrayColor = new ColorParam (host); m_Created = false; m_Edit = ee_none; m_Time = 0.0f; } //--------------------------------------------------------------------------- Effect::~Effect () { delete m_GrayColor; delete m_AddColor; delete m_BaseColor; } //--------------------------------------------------------------------------- void Effect::clear () { m_BaseColor->clear (); m_AddColor->clear (); m_GrayColor->clear (); } //--------------------------------------------------------------------------- void Effect::create (float time) { m_BaseColor->create(time); m_AddColor->create(time); m_GrayColor->create(time); m_Time = time; m_Created = true; } //--------------------------------------------------------------------------- void Effect::draw () { if (m_Created == false) return; m_BaseColor->draw (); m_AddColor->draw (); m_GrayColor->draw (); } //--------------------------------------------------------------------------- void Effect::add_point (int _xpos, int _ypos) { if (m_Edit == ee_none) return; float ftime = (float)_xpos / (float)m_Host->Width; float fvalue = (float)_ypos - (float)m_Host->Height * 0.5f; switch (m_Edit) { case ee_base_color: break; case ee_add_color: break; case ee_gray_color: break; } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //---------------------------------------------------------------------------
bradchesney79/illacceptanything
linux/sound/soc/codecs/adau1781-i2c.c
<filename>linux/sound/soc/codecs/adau1781-i2c.c /* * Driver for ADAU1381/ADAU1781 CODEC * * Copyright 2014 Analog Devices Inc. * Author: <NAME> <<EMAIL>> * * Licensed under the GPL-2. */ #include <linux/i2c.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/regmap.h> #include <sound/soc.h> #include "adau1781.h" static int adau1781_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct regmap_config config; config = adau1781_regmap_config; config.val_bits = 8; config.reg_bits = 16; return adau1781_probe(&client->dev, devm_regmap_init_i2c(client, &config), id->driver_data, NULL); } static int adau1781_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); return 0; } static const struct i2c_device_id adau1781_i2c_ids[] = { { "adau1381", ADAU1381 }, { "adau1781", ADAU1781 }, { } }; MODULE_DEVICE_TABLE(i2c, adau1781_i2c_ids); static struct i2c_driver adau1781_i2c_driver = { .driver = { .name = "adau1781", .owner = THIS_MODULE, }, .probe = adau1781_i2c_probe, .remove = adau1781_i2c_remove, .id_table = adau1781_i2c_ids, }; module_i2c_driver(adau1781_i2c_driver); MODULE_DESCRIPTION("ASoC ADAU1381/ADAU1781 CODEC I2C driver"); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_LICENSE("GPL");
IAGT-Amazing-Software/android-java-clean-architecture
presentation/src/main/java/com/innopro/android/sample/presentation/view/fragment/UserDetailsFragment.java
package com.innopro.android.sample.presentation.view.fragment; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.hannesdorfmann.fragmentargs.FragmentArgs; import com.hannesdorfmann.fragmentargs.annotation.Arg; import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs; import com.innopro.android.sample.domain.User; import com.innopro.android.sample.presentation.R; import com.innopro.android.sample.presentation.R2; import com.innopro.android.sample.presentation.internal.di.components.UserComponent; import com.innopro.android.sample.presentation.presenter.UserDetailsPresenter; import com.innopro.android.sample.presentation.view.UserDetailsView; import com.squareup.picasso.Picasso; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Fragment that shows details of a certain user. */ @FragmentWithArgs public class UserDetailsFragment extends BaseFragment implements UserDetailsView { //region Constants private static final String TAG = UserDetailsFragment.class.getSimpleName(); //endregion //region Fields @BindView(R2.id.iv_cover) ImageView iv_cover; @BindView(R2.id.tv_fullname) TextView tv_fullname; @BindView(R2.id.tv_email) TextView tv_email; @BindView(R2.id.tv_followers) TextView tv_followers; @BindView(R2.id.tv_description) TextView tv_description; @BindView(R2.id.rl_progress) RelativeLayout rl_progress; @BindView(R2.id.rl_retry) RelativeLayout rl_retry; @BindView(R2.id.bt_retry) Button bt_retry; @Arg private int userId; @Inject UserDetailsPresenter userDetailsPresenter; //endregion //region Constructors & Initialization public UserDetailsFragment() { setRetainInstance(true); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentArgs.inject(this); this.getComponent(UserComponent.class).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View fragmentView = inflater.inflate(R.layout.fragment_user_details, container, false); ButterKnife.bind(this, fragmentView); return fragmentView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.userDetailsPresenter.setView(this); if (savedInstanceState == null) { this.loadUserDetails(); } } //endregion //region Methods for/from SuperClass/Interfaces @Override public void onResume() { super.onResume(); this.userDetailsPresenter.resume(); } @Override public void onPause() { super.onPause(); this.userDetailsPresenter.pause(); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); this.userDetailsPresenter.destroy(); } @Override public void renderUser(User user) { if (user != null) { Picasso.with(getContext()).load(user.getCoverUrl()).fit().into(this.iv_cover); this.tv_fullname.setText(user.getFullName()); this.tv_email.setText(user.getEmail()); this.tv_followers.setText(String.valueOf(user.getFollowers())); this.tv_description.setText(user.getDescription()); } } @Override public void showLoading() { this.rl_progress.setVisibility(View.VISIBLE); } @Override public void hideLoading() { this.rl_progress.setVisibility(View.GONE); } @Override public void showRetry() { this.rl_retry.setVisibility(View.VISIBLE); } @Override public void hideRetry() { this.rl_retry.setVisibility(View.GONE); } @Override public void showError(String message) { this.showToastMessage(message); } @Override public Context context() { return getActivity().getApplicationContext(); } //endregion //region Methods /** * Loads all users. */ private void loadUserDetails() { if (this.userDetailsPresenter != null) { this.userDetailsPresenter.initialize(userId); } } @OnClick(R2.id.bt_retry) void onButtonRetryClick() { UserDetailsFragment.this.loadUserDetails(); } //endregion //region Inner and Anonymous Classes //endregion //region Getter & Setter /** * Variable Setters */ public void setUserId(int userId) { this.userId = userId; } //endregion }
hyper-ml/hyperflow
server/pkg/base/logging.go
package base import ( "fmt" //log "github.com/sirupsen/logrus" ) // Log : Log messages func Log(format string, args ...interface{}) { //log.Infof(format, args) fmt.Println(format, args) } // Info : Log Info messages func Info(format string, args ...interface{}) { //log.Infof(format, args) fmt.Println(format, args) } // Warn : Log warning messages func Warn(format string, args ...interface{}) { //log.Warnf(format, args) fmt.Println(format, args) } // Error : Log Error messages func Error(format string, args ...interface{}) { //log.Errorf(format, args) fmt.Println(format, args) } // Debug : Log Debug messages func Debug(format string, args ...interface{}) { //log.Debugf(format, args) fmt.Println(format, args) } // Out : Log output messages func Out(format string, args ...interface{}) { fmt.Println(format, args) } // Println : Print messages func Println(format string, args ...interface{}) { fmt.Println(format, args) }
openstreetview/ios
OpenStreetView/OSVNavigationController.h
<gh_stars>10-100 // // OSVNavigationController.h // OpenStreetView // // Created by <NAME> on 08/07/16. // Copyright © 2016 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface OSVNavigationController : UINavigationController @end
James51332/Papaya
platform/opengl/OpenGLVertexArray.cpp
#include "papayapch.h" #include "OpenGLVertexArray.h" #include "OpenGLLoader.h" namespace Papaya { OpenGLVertexArray::OpenGLVertexArray() { glGenVertexArrays(1, &m_RendererID); } OpenGLVertexArray::~OpenGLVertexArray() { glDeleteVertexArrays(1, &m_RendererID); } void OpenGLVertexArray::SetVertexBuffer(const Ref<Buffer>& buffer) { glBindVertexArray(m_RendererID); // OpenGL sucks buffer->Bind(); } void OpenGLVertexArray::SetIndexBuffer(const Ref<Buffer>& buffer) { m_IndexBuffer = buffer; } void OpenGLVertexArray::Bind() { glBindVertexArray(m_RendererID); m_IndexBuffer->Bind(); } void OpenGLVertexArray::Unbind() { glBindVertexArray(0); } } // namespace Papaya
Georgi2704/pricelist-fastapi-boilerplate
migrations/versions/schema/7f1d088444e7_.py
"""empty message Revision ID: 7f1d088444e7 Revises: <PASSWORD> Create Date: 2020-10-09 15:56:01.365057 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "7f1d088444e7" down_revision = "7<PASSWORD>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column("orders", sa.Column("table_id", postgresql.UUID(as_uuid=True), nullable=True)) op.create_foreign_key(None, "orders", "shop_tables", ["table_id"], ["id"]) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, "orders", type_="foreignkey") op.drop_column("orders", "table_id") # ### end Alembic commands ###
2994265077/speedment
runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/component/transaction/Transaction.java
<filename>runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/component/transaction/Transaction.java<gh_stars>1-10 /** * * Copyright (c) 2006-2018, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.component.transaction; import com.speedment.runtime.core.exception.TransactionException; /** * * @author <NAME> * @since 3.0.17 */ public interface Transaction { /** * Makes all changes made since the previous commit/rollback permanent and * releases any transaction domain locks currently affected by this * <code>Transaction</code> object. * * @throws TransactionException if an exception is thrown by the underlying * transaction aware object (e.g. an SqlException is thrown) */ void commit() throws TransactionException; /** * Undoes all changes made in the current transaction and releases any * transaction domain locks currently affected by this * <code>Transaction</code> object. * * @throws TransactionException if an exception is thrown by the underlying * transaction aware object (e.g. an SqlException is thrown) */ void rollback() throws TransactionException; /** * Attaches the current thread to this Transaction. * <p> * After this call, data operations executed by the current thread will be * issued within this transaction's scope. * <p> * NB: Not all databases support transaction operations carried out by by a * plurality of threads. * * @throws IllegalStateException if the current thread is already associated * with another Transaction within any transaction domain. */ void attachCurrentThread(); /** * Detaches the current thread from this Transaction. If the current thread * is not attached to this Transaction, then this method is a no-operation. * <p> * After this call, data operations executed by the current thread will be * issued separated from this transaction's scope. */ void detachCurrentThread(); // /** // * Closes this transaction, rolling back any uncommitted updates, detatching // * all attached threads and relinquishing any underlying resources. // */ // void close(); }
ljz663/tencentcloud-sdk-java
src/main/java/com/tencentcloudapi/dayu/v20180709/models/ModifyDDoSSwitchRequest.java
<gh_stars>100-1000 /* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.dayu.v20180709.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ModifyDDoSSwitchRequest extends AbstractModel{ /** * 大禹子产品代号(basic表示基础防护) */ @SerializedName("Business") @Expose private String Business; /** * =get表示读取DDoS防护状态;=set表示修改DDoS防护状态; */ @SerializedName("Method") @Expose private String Method; /** * 基础防护的IP,只有当Business为基础防护时才需要填写此字段; */ @SerializedName("Ip") @Expose private String Ip; /** * 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)] */ @SerializedName("BizType") @Expose private String BizType; /** * 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)] */ @SerializedName("DeviceType") @Expose private String DeviceType; /** * 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); */ @SerializedName("InstanceId") @Expose private String InstanceId; /** * 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值: "bj": 华北地区(北京) "cd": 西南地区(成都) "cq": 西南地区(重庆) "gz": 华南地区(广州) "gzopen": 华南地区(广州Open) "hk": 中国香港 "kr": 东南亚地区(首尔) "sh": 华东地区(上海) "shjr": 华东地区(上海金融) "szjr": 华南地区(深圳金融) "sg": 东南亚地区(新加坡) "th": 东南亚地区(泰国) "de": 欧洲地区(德国) "usw": 美国西部(硅谷) "ca": 北美地区(多伦多) "jp": 日本 "hzec": 杭州 "in": 印度 "use": 美东地区(弗吉尼亚) "ru": 俄罗斯 "tpe": 中国台湾 "nj": 南京 */ @SerializedName("IPRegion") @Expose private String IPRegion; /** * 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段; */ @SerializedName("Status") @Expose private Long Status; /** * Get 大禹子产品代号(basic表示基础防护) * @return Business 大禹子产品代号(basic表示基础防护) */ public String getBusiness() { return this.Business; } /** * Set 大禹子产品代号(basic表示基础防护) * @param Business 大禹子产品代号(basic表示基础防护) */ public void setBusiness(String Business) { this.Business = Business; } /** * Get =get表示读取DDoS防护状态;=set表示修改DDoS防护状态; * @return Method =get表示读取DDoS防护状态;=set表示修改DDoS防护状态; */ public String getMethod() { return this.Method; } /** * Set =get表示读取DDoS防护状态;=set表示修改DDoS防护状态; * @param Method =get表示读取DDoS防护状态;=set表示修改DDoS防护状态; */ public void setMethod(String Method) { this.Method = Method; } /** * Get 基础防护的IP,只有当Business为基础防护时才需要填写此字段; * @return Ip 基础防护的IP,只有当Business为基础防护时才需要填写此字段; */ public String getIp() { return this.Ip; } /** * Set 基础防护的IP,只有当Business为基础防护时才需要填写此字段; * @param Ip 基础防护的IP,只有当Business为基础防护时才需要填写此字段; */ public void setIp(String Ip) { this.Ip = Ip; } /** * Get 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)] * @return BizType 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)] */ public String getBizType() { return this.BizType; } /** * Set 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)] * @param BizType 只有当Business为基础防护时才需要填写此字段,IP所属的产品类型,取值[public(CVM产品),bm(黑石产品),eni(弹性网卡),vpngw(VPN网关), natgw(NAT网关),waf(Web应用安全产品),fpc(金融产品),gaap(GAAP产品), other(托管IP)] */ public void setBizType(String BizType) { this.BizType = BizType; } /** * Get 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)] * @return DeviceType 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)] */ public String getDeviceType() { return this.DeviceType; } /** * Set 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)] * @param DeviceType 只有当Business为基础防护时才需要填写此字段,IP所属的产品子类,取值[cvm(CVM),lb(负载均衡器),eni(弹性网卡),vpngw(VPN),natgw(NAT),waf(WAF),fpc(金融),gaap(GAAP),other(托管IP),eip(黑石弹性IP)] */ public void setDeviceType(String DeviceType) { this.DeviceType = DeviceType; } /** * Get 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); * @return InstanceId 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); */ public String getInstanceId() { return this.InstanceId; } /** * Set 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); * @param InstanceId 只有当Business为基础防护时才需要填写此字段,IP所属的资源实例ID,当绑定新IP时必须填写此字段;例如是弹性网卡的IP,则InstanceId填写弹性网卡的ID(eni-*); */ public void setInstanceId(String InstanceId) { this.InstanceId = InstanceId; } /** * Get 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值: "bj": 华北地区(北京) "cd": 西南地区(成都) "cq": 西南地区(重庆) "gz": 华南地区(广州) "gzopen": 华南地区(广州Open) "hk": 中国香港 "kr": 东南亚地区(首尔) "sh": 华东地区(上海) "shjr": 华东地区(上海金融) "szjr": 华南地区(深圳金融) "sg": 东南亚地区(新加坡) "th": 东南亚地区(泰国) "de": 欧洲地区(德国) "usw": 美国西部(硅谷) "ca": 北美地区(多伦多) "jp": 日本 "hzec": 杭州 "in": 印度 "use": 美东地区(弗吉尼亚) "ru": 俄罗斯 "tpe": 中国台湾 "nj": 南京 * @return IPRegion 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值: "bj": 华北地区(北京) "cd": 西南地区(成都) "cq": 西南地区(重庆) "gz": 华南地区(广州) "gzopen": 华南地区(广州Open) "hk": 中国香港 "kr": 东南亚地区(首尔) "sh": 华东地区(上海) "shjr": 华东地区(上海金融) "szjr": 华南地区(深圳金融) "sg": 东南亚地区(新加坡) "th": 东南亚地区(泰国) "de": 欧洲地区(德国) "usw": 美国西部(硅谷) "ca": 北美地区(多伦多) "jp": 日本 "hzec": 杭州 "in": 印度 "use": 美东地区(弗吉尼亚) "ru": 俄罗斯 "tpe": 中国台湾 "nj": 南京 */ public String getIPRegion() { return this.IPRegion; } /** * Set 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值: "bj": 华北地区(北京) "cd": 西南地区(成都) "cq": 西南地区(重庆) "gz": 华南地区(广州) "gzopen": 华南地区(广州Open) "hk": 中国香港 "kr": 东南亚地区(首尔) "sh": 华东地区(上海) "shjr": 华东地区(上海金融) "szjr": 华南地区(深圳金融) "sg": 东南亚地区(新加坡) "th": 东南亚地区(泰国) "de": 欧洲地区(德国) "usw": 美国西部(硅谷) "ca": 北美地区(多伦多) "jp": 日本 "hzec": 杭州 "in": 印度 "use": 美东地区(弗吉尼亚) "ru": 俄罗斯 "tpe": 中国台湾 "nj": 南京 * @param IPRegion 只有当Business为基础防护时才需要填写此字段,表示IP所属的地域,取值: "bj": 华北地区(北京) "cd": 西南地区(成都) "cq": 西南地区(重庆) "gz": 华南地区(广州) "gzopen": 华南地区(广州Open) "hk": 中国香港 "kr": 东南亚地区(首尔) "sh": 华东地区(上海) "shjr": 华东地区(上海金融) "szjr": 华南地区(深圳金融) "sg": 东南亚地区(新加坡) "th": 东南亚地区(泰国) "de": 欧洲地区(德国) "usw": 美国西部(硅谷) "ca": 北美地区(多伦多) "jp": 日本 "hzec": 杭州 "in": 印度 "use": 美东地区(弗吉尼亚) "ru": 俄罗斯 "tpe": 中国台湾 "nj": 南京 */ public void setIPRegion(String IPRegion) { this.IPRegion = IPRegion; } /** * Get 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段; * @return Status 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段; */ public Long getStatus() { return this.Status; } /** * Set 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段; * @param Status 可选字段,防护状态值,取值[0(关闭),1(开启)];当Method为get时可以不填写此字段; */ public void setStatus(Long Status) { this.Status = Status; } public ModifyDDoSSwitchRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public ModifyDDoSSwitchRequest(ModifyDDoSSwitchRequest source) { if (source.Business != null) { this.Business = new String(source.Business); } if (source.Method != null) { this.Method = new String(source.Method); } if (source.Ip != null) { this.Ip = new String(source.Ip); } if (source.BizType != null) { this.BizType = new String(source.BizType); } if (source.DeviceType != null) { this.DeviceType = new String(source.DeviceType); } if (source.InstanceId != null) { this.InstanceId = new String(source.InstanceId); } if (source.IPRegion != null) { this.IPRegion = new String(source.IPRegion); } if (source.Status != null) { this.Status = new Long(source.Status); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Business", this.Business); this.setParamSimple(map, prefix + "Method", this.Method); this.setParamSimple(map, prefix + "Ip", this.Ip); this.setParamSimple(map, prefix + "BizType", this.BizType); this.setParamSimple(map, prefix + "DeviceType", this.DeviceType); this.setParamSimple(map, prefix + "InstanceId", this.InstanceId); this.setParamSimple(map, prefix + "IPRegion", this.IPRegion); this.setParamSimple(map, prefix + "Status", this.Status); } }
tienthegainz/OutOfStockSystem
frontend/src/App.js
import React, { useState, useEffect } from "react"; import { BrowserRouter as Router, Switch, Route, } from "react-router-dom"; import { io } from "socket.io-client"; import ProductWatcherPage from './pages/product_watcher/ProductWatcher'; import CameraPage from './pages/camera/Camera'; import NavBar from "./components/NavBar/NavBar"; import "./App.css"; import LogPage from "./pages/log/Log"; import ProductPage from "./pages/product/Product"; import LoginPage from "./pages/login/Login"; import { useDispatch, useSelector } from 'react-redux'; import UserPage from "./pages/employee/Employee"; import { notification } from 'antd'; import allActions from "./actions"; import Notification from "react-web-notification"; const ENDPOINT = "http://0.0.0.0:5001" const App = () => { const userInfo = useSelector(state => state.currentUser); const notiInfo = useSelector(state => state.notification); const dispatch = useDispatch(); const [notiMessage, setNotiMessage] = useState({ title: "", message: "", display: false }); const openNotification = (title, message) => { notification.error({ message: title, description: message, duration: 3, placement: 'bottomRight' }); }; useEffect(() => { if (notiInfo.trigger) { openNotification(notiInfo.title, notiInfo.message); dispatch(allActions.notiActions.cancel()); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [notiInfo]); useEffect(() => { const camera_socket = io(ENDPOINT); camera_socket.on('noti', data => { console.log({ ...data, display: true }); setNotiMessage({ ...data, display: true }); }); // CLEAN UP THE EFFECT if (camera_socket) return () => camera_socket.disconnect(); }, []); return (<React.Fragment> {notiMessage.display ? <Notification ignore={false} timeout={0} title={notiMessage.title} options={ { body: notiMessage.message } } /> : null} {userInfo.isLoggedIn ? <Router> <NavBar /> <Switch> <Route exact path="/log"> <LogPage /> </Route> <Route exact path="/camera"> <CameraPage /> </Route> <Route exact path="/product"> <ProductPage /> </Route> <Route exact path="/product"> <ProductPage /> </Route> <Route exact path="/user"> <UserPage /> </Route> <Route exact path={["/", "/watcher"]} > <ProductWatcherPage /> </Route> </Switch> </Router> : <LoginPage />} </React.Fragment > ); } export default App;
Azork/wiremock
src/test/java/com/github/tomakehurst/wiremock/admin/AdminUriTemplateTest.java
/* * Copyright (C) 2011 <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 com.github.tomakehurst.wiremock.admin; import com.github.tomakehurst.wiremock.admin.model.PathParams; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class AdminUriTemplateTest { @Test public void extractsSinglePathParameter() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}"); PathParams pathParams = template.parse("/things/11-22-33"); assertThat(pathParams.get("id"), is("11-22-33")); } @Test(expected = IllegalArgumentException.class) public void throwsIllegalArgumentExceptionIfAttemptingParsingOnNonMatchingUrl() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}"); template.parse("/things/stuff/11-22-33"); } @Test public void matchesWhenUrlIsEquivalentToTemplate() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}/otherthings/{subId}"); assertThat(template.matches("/things/11-22-33/otherthings/12378"), is(true)); } @Test public void nonMatchWhenUrlIsShorterThanTemplate() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}/otherthings/{subId}"); assertThat(template.matches("/things/11-22-33/otherthings"), is(false)); } @Test public void nonMatchWhenUrlPartIsMismatch() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}/otherthings/{subId}"); assertThat(template.matches("/things/11-22-33/other-stuff/1234"), is(false)); } @Test public void rendersWithParameters() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}/otherthings/{subId}"); PathParams pathParams = new PathParams() .add("id", "123") .add("subId", "456"); String path = template.render(pathParams); assertThat(path, is("/things/123/otherthings/456")); } @Test public void rendersWithoutParameters() { AdminUriTemplate template = new AdminUriTemplate("/things/stuff"); String path = template.render(PathParams.empty()); assertThat(path, is("/things/stuff")); } @Test(expected = IllegalArgumentException.class) public void throwsErrorWhenNotAllParametersAreBound() { AdminUriTemplate template = new AdminUriTemplate("/things/{id}/otherthings/{subId}"); template.render(new PathParams().add("id", "123")); } }
dliberat/advent-of-code-2020
day05/main.go
package main import ( "fmt" "io/ioutil" "sort" "strings" ) type boardingPass struct { code int } func (bp *boardingPass) row() int { return bp.code >> 3 } func (bp *boardingPass) col() int { return bp.code & 7 } func (bp *boardingPass) sid() int { return bp.row()*8 + bp.col() } func (bp *boardingPass) toString() string { code := bp.code s := make([]byte, 10) for i := 9; i >= 7; i-- { if code%2 == 1 { s[i] = 'R' } else { s[i] = 'L' } code = code >> 1 } for i := 6; i >= 0; i-- { if code%2 == 1 { s[i] = 'B' } else { s[i] = 'F' } code = code >> 1 } return string(s) } func makeBoardingPass(txt string) boardingPass { code := 0 for i := 0; i < len(txt); i++ { code = code << 1 if txt[i] == 'B' || txt[i] == 'R' { code++ } } return boardingPass{code: code} } func readInput(fname string) string { data, err := ioutil.ReadFile(fname) if err != nil { panic("Cannot read input data.") } s := string(data) return strings.TrimRight(s, "\n") } func part1(txt string) int { passes := strings.Split(txt, "\n") max := 0 for _, pass := range passes { p := makeBoardingPass(pass) if p.sid() > max { max = p.sid() } } return max } func part2(txt string) int { split := strings.Split(txt, "\n") sids := make([]int, len(split)) for i, p := range split { pass := makeBoardingPass(p) sids[i] = pass.sid() } sort.Ints(sids) // find the gap in a sequence of ints for i := 1; i < len(sids)-1; i++ { if sids[i]-sids[i-1] == 2 { return sids[i] - 1 } } return 0 } func main() { txt := readInput("input.txt") p1 := part1(txt) fmt.Println("[PART 1] Highest ID on a boarding pass:", p1) p2 := part2(txt) fmt.Println("[PART 2] Your seat ID is:", p2) }
teberhardt/byps
java/bypsgen/src/byps/gen/cs/GenApiClass.java
package byps.gen.cs; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import byps.BException; import byps.BJsonObject; import byps.BRegistry; import byps.gen.api.ErrorInfo; import byps.gen.api.GeneratorException; import byps.gen.api.MemberInfo; import byps.gen.api.MethodInfo; import byps.gen.api.RemoteInfo; import byps.gen.api.SerialInfo; import byps.gen.api.TypeInfo; import byps.gen.js.PrintHelper; import byps.gen.utils.CodePrinter; import byps.gen.utils.Utils; class GenApiClass { static Logger log = LoggerFactory.getLogger(GenApiClass.class); static void generate(PrintContext pctxt, SerialInfo serInfo) throws IOException { log.debug("generate(" + serInfo); if (serInfo.isCollectionType()) { // No API class for List<>... } else if (serInfo.isArrayType()) { // No API class for int[]... } else if (serInfo.isStubType()) { // Stub API class is generated by GenRemoteStub } else if (serInfo.typeId < pctxt.classDB.getRegistry().getMinTypeIdUser()){ // No API class for RemoteException ... } else { log.info("Generate API class for type " + serInfo.typeId + ": " + serInfo); CodePrinter pr = pctxt.getPrinterForApiClass(serInfo, "", serInfo.isResultClass() || serInfo.isRequestClass()); new GenApiClass(pctxt, serInfo, pr).generate(); pr.close(); } log.debug(")generate"); } private GenApiClass(PrintContext pctxt, SerialInfo serInfo, CodePrinter pr) { this.pctxt = pctxt; this.serInfo = serInfo; this.pr = pr; this.methodInfo = serInfo.methodInfo; } private void printMember(MemberInfo minfo) throws IOException { log.debug("printMember"); if (minfo.type.typeId == BRegistry.TYPEID_VOID) { // Type void can be used by method return values } else { // For final static members, we do not generate properties, // we make the field definition public. So the comment lines // are printed before the field definition. if (minfo.isStatic) { pctxt.printComments(pr, minfo.comments); } // Members are is usually declared with protected access. // But for sealed classes - which cannot have sub-classes and // thus protected does not make sense - members are declared private. String access = "protected "; if (serInfo.isInline) { access = "private "; } else if (serInfo.isRequestClass() || serInfo.isResultClass()){ access = "internal "; } else if (minfo.isStatic) { access = "public "; } String finalKeyword = ""; if (minfo.isFinal) { if (minfo.type.isPointerType()) { finalKeyword = "readonly static "; } else { finalKeyword = "const "; } } String newKeyword = ""; if (serInfo.baseInfo != null && serInfo.baseInfo.findMember(minfo.name, null) != null) { newKeyword = "new "; } String memberName = ""; if (minfo.isStatic) { memberName = pctxt.makePublicMemberName(minfo.name); } else { memberName = pctxt.makeDataMemberName(minfo.name); } String typeName = pctxt.toCSharp(minfo.type).toString(serInfo.pack); CodePrinter mpr = pr.print(access).print(newKeyword).print(finalKeyword).print(typeName).print(" ").print(memberName); String value = minfo.value; if (value != null) { mpr.print(" = "); if (value.startsWith("\"")) value = value.substring(1, value.length()-1); mpr.print(printConstValue(minfo.type, value)); } mpr.print(";"); if (minfo.isTransient) mpr.print(" // transient"); mpr.println(); mpr.println(); } log.debug(")printMember"); } private String printConstValue(TypeInfo tinfo, Object value) throws BException, GeneratorException { StringBuilder sbuf = new StringBuilder(); if (tinfo.dims.length() != 0) { BJsonObject js = BJsonObject.fromString((String)value); sbuf.append(makeNewArrayInstance(tinfo, js)); } else if (tinfo.qname.equals("java.lang.String")) { String s = (String)value; sbuf.append("\""); for (int i = 0; i < s.length(); i++) { sbuf.append( pctxt.printStringChar(s.charAt(i)) ); } sbuf.append("\""); } else if (tinfo.qname.equals("char")) { String s = (String)value; sbuf.append("\'"); sbuf.append( pctxt.printStringChar(s.charAt(0)) ); sbuf.append("\'"); } else if (tinfo.qname.equals("boolean")) { if (value instanceof Number) value = ((Number)value).longValue(); sbuf.append(value); } else if (tinfo.qname.equals("byte")) { if (value instanceof Number) value = ((Number)value).longValue(); sbuf.append("(byte)").append(value); } else if (tinfo.qname.equals("short")) { if (value instanceof Number) value = ((Number)value).longValue(); sbuf.append("(short)").append(value); } else if (tinfo.qname.equals("int")) { if (value instanceof Number) value = ((Number)value).longValue(); sbuf.append(value); } else if (tinfo.qname.equals("long")) { if (value instanceof Number) { value = ((Number)value).longValue(); } else if (value instanceof String) { String svalue = (String)value; if (svalue.endsWith(".")) svalue = svalue.substring(0, svalue.length()-1); value = Long.parseLong(svalue); } sbuf.append(value).append("L"); } else if (tinfo.qname.equals("double")) { sbuf.append(value); } else if (tinfo.qname.equals("float")) { sbuf.append(value).append("f"); } else if (tinfo.isPointerType() && (value instanceof BJsonObject)) { sbuf.append(makeNewInstance(tinfo, (BJsonObject)value)); } else if (value != null) { BJsonObject js = BJsonObject.fromString((String)value); sbuf.append(makeNewInstance(tinfo, js)); } return sbuf.toString(); } private String makeNewArrayInstance(TypeInfo tinfo, BJsonObject js) throws BException, GeneratorException { if (js == null) return "null"; StringBuilder sbuf = new StringBuilder(); String cstype = pctxt.toCSharp(tinfo).toString(serInfo.pack); sbuf.append("new ").append(cstype); sbuf.append(makeArrayLevel(tinfo, 1, js)); return sbuf.toString(); } private String makeArrayLevel(TypeInfo tinfo, int dim, BJsonObject js) throws BException, GeneratorException { StringBuilder sbuf = new StringBuilder(); sbuf.append("{"); for (int i = 0; i < js.size(); i++) { if (i != 0) sbuf.append(","); if (dim < tinfo.dims.length()/2) { BJsonObject jsElm = (BJsonObject)js.get(i); sbuf.append(makeArrayLevel(tinfo, dim+1, jsElm)); } else { Object value = js.get(i); TypeInfo elmInfo = new TypeInfo(tinfo.name, tinfo.qname, "", null, tinfo.isEnum, tinfo.isFinal, tinfo.isInline); sbuf.append(printConstValue(elmInfo, value)); } } sbuf.append("}"); return sbuf.toString(); } private String makeNewInstance(TypeInfo tinfo, BJsonObject params) throws GeneratorException, BException { if (params == null) return "null"; StringBuilder sbuf = new StringBuilder(); // Lookup full SerialInfo of given tinfo SerialInfo sinfo = null; for (SerialInfo s : pctxt.classDB.getSerials()) { if (s.toString().equals(tinfo.toString())) { sinfo = s; break; } } if (sinfo == null) { ErrorInfo errInfo = new ErrorInfo(); errInfo.className = tinfo.toString(); errInfo.msg = "Internal error, typeId=" + tinfo.typeId + " not found in list of serials."; throw new GeneratorException(errInfo); } boolean first = true; sbuf.append("new ").append(sinfo.toString(serInfo.pack)).append("("); for (MemberInfo minfo : sinfo.members) { if (minfo.isStatic) continue; if (!first) sbuf.append(", "); else first = false; if (minfo.type.dims.length() != 0) { sbuf.append(makeNewArrayInstance(minfo.type, (BJsonObject)params.get(minfo.name))); } else if (minfo.type.isPointerType()) { sbuf.append(makeNewInstance(minfo.type, (BJsonObject)params.get(minfo.name))); } else { sbuf.append(printConstValue(minfo.type, params.get(minfo.name))); } } sbuf.append(")"); return sbuf.toString(); } private void printGetSet(MemberInfo minfo) throws IOException { if (minfo.isStatic) return; log.debug("printGetSet"); pctxt.printComments(pr, minfo.comments); String memberType = pctxt.toCSharp(minfo.type).toString(serInfo.pack); String memberName = pctxt.makeDataMemberName(minfo.name); if (!memberType.equals("void")) { CodePrinter mpr = pr.print("public "); if (minfo.isStatic) mpr.print("static "); mpr.print(memberType).print(" ") .println(pctxt.getterForMember(minfo.name, true, minfo.type, true)); pr.print("{").println(); pr.beginBlock(); pr.println("get"); pr.println("{"); pr.beginBlock(); if (memberType.equals("java.lang.String")) { pr.print("if (").print(memberName).print(" == null) ") .print("_").print(minfo.name).print(" = \"\";") .println(); } pr.print("return ").print(memberName).println(";"); pr.endBlock(); pr.println("}"); // end get if (!minfo.isFinal) { pr.println("set"); pr.println("{"); pr.beginBlock(); pr.print("this.").print(memberName).println(" = value;"); pctxt.printSetChangedMembers(pr, serInfo, minfo); if (serInfo.isResultClass()) { pr.println("if (resp != null) resp.ready(this);"); } pr.endBlock(); pr.println("}"); // end set } pr.endBlock(); pr.println("}"); // end member pr.println(); } else if (serInfo.isResultClass()) { pr.print("public void ") .print("set").print(Utils.firstCharToUpper(minfo.name)) .println("()"); pr.println("{"); pr.beginBlock(); pr.println("if (resp != null) resp.ready(this);"); pr.endBlock(); pr.println("}"); } pr.println(); log.debug(")printGetSet"); } private void printConstructors() throws IOException { log.debug("printConstructors"); pr.print("public ").print(serInfo.name).println("() {"); pr.print("}"); pr.println(); pr.println(); if (isValueClass()) { List<MemberInfo> constrMembers = new ArrayList<MemberInfo>(); for (MemberInfo minfo : serInfo.members) { if (minfo.type.typeId == BRegistry.TYPEID_VOID) continue; if (minfo.isStatic) continue; constrMembers.add(minfo); } if (constrMembers.size() != 0) { // Construtor with initializer list CodePrinter mpr = pr.print("public ").print(serInfo.name).print("("); boolean first = true; for (MemberInfo minfo : constrMembers) { if (minfo.type.typeId == BRegistry.TYPEID_VOID) continue; if (minfo.isStatic) continue; if (!first) mpr.print(", "); else first = false; String typeName = pctxt.toCSharp(minfo.type).toString(serInfo.pack); mpr.print(typeName).print(" @").print(minfo.name); } mpr.println(") {"); pr.beginBlock(); for (MemberInfo minfo : constrMembers) { if (minfo.type.typeId == BRegistry.TYPEID_VOID) continue; if (minfo.isStatic) continue; String memberName = pctxt.makeDataMemberName(minfo.name); pr.print("this.").print(memberName).print(" = @").print(minfo.name).println(";"); } pr.endBlock(); pr.print("}"); pr.println(); pr.println(); } // Copy-Construtor { CodePrinter mpr = pr.print("public ").print(serInfo.name).print("(").print(serInfo.name).print(" rhs)"); if (serInfo.baseInfo != null) { mpr.print(" : base(rhs)"); } mpr.println(); pr.println("{"); pr.beginBlock(); for (MemberInfo minfo : constrMembers) { if (minfo.type.typeId == BRegistry.TYPEID_VOID) continue; if (minfo.isStatic) continue; String memberName = pctxt.makeDataMemberName(minfo.name); pr.print("this.").print(memberName).print(" = rhs.").print(memberName).println(";"); } pr.endBlock(); pr.print("}"); pr.println(); } } log.debug(")printConstructors"); } private boolean isValueClass() { return true; } private void printRemoteId() throws IOException { log.debug("printRemoteId"); pr.print("public override int getRemoteId() { return ").print(methodInfo.remoteInfo.typeId).println("; }"); log.debug(")printRemoteId"); } private void printExecuteAsync() throws GeneratorException { pr.checkpoint(); pr.println("try {"); pr.beginBlock(); String methodName = pctxt.makePublicMemberName(methodInfo.name); String remoteType = methodInfo.remoteInfo.toString(serInfo.pack); pr.print("").print(remoteType).print(" __byps__remoteT = (").print(remoteType).print(")__byps__remote;"); pr.println(); String rtype = pctxt.getReturnTypeAsObjType(methodInfo, serInfo.pack); String outerResultType = "BAsyncResultSendMethod<" + rtype + ">"; String bresultClass = pctxt.renameClassPackage(methodInfo.resultInfo.toString(serInfo.pack)); pr.print(outerResultType).print(" __byps__outerResult = new ").print(outerResultType) .print("(__byps__asyncResult, new ").print(bresultClass) .print("());"); pr.println(); CodePrinter mpr = pr.print("__byps__remoteT.").print(methodName).print("").print("("); boolean first = true; for (MemberInfo pinfo : methodInfo.requestInfo.members) { if (first) first = false; else mpr.print(", "); String memberName = pctxt.makeDataMemberName(pinfo.name); mpr.print(memberName); } if (!first) mpr.print(", "); mpr.print("BAsyncResultHelper.ToDelegate(__byps__outerResult)"); mpr.println(");"); pr.endBlock(); pr.println("} catch (Exception e) {"); pr.beginBlock(); MemberInfo returnInfo = methodInfo.resultInfo.members.get(0); String nullValue = PrintHelper.getDefaultValueForType(returnInfo.type); pr.println("__byps__asyncResult.setAsyncResult(" + nullValue + ", e);"); pr.endBlock(); pr.println("}"); } private void printExecute() throws IOException { log.debug("printExecute"); pr.print("public override void ").print("execute(BRemote __byps__remote, BAsyncResultIF<Object> __byps__asyncResult) ").println("{"); pr.beginBlock(); printExecuteAsync(); pr.endBlock(); pr.print("}"); pr.println(); log.debug(")printExecute"); } private void printSetSession() throws IOException { if (methodInfo == null) return; RemoteInfo rinfo = methodInfo.remoteInfo; for (MemberInfo pinfo : methodInfo.requestInfo.members) { // Supply authentication parameter if (pctxt.isSessionParam(rinfo, pinfo)) { pr.checkpoint(); pr.println("public override void setSession(Object __byps__sess) {"); pr.beginBlock(); String memberName = pctxt.makeDataMemberName(pinfo.name); String authClassName = pctxt.renameClassPackage(rinfo.authParamClassName); pr.print(memberName).print(" = (").print(authClassName).println(")__byps__sess;"); pr.endBlock(); pr.println("}"); pr.println(); break; } } } private void printHashCode() throws IOException { log.debug("printHashCode("); pr.println("public override int GetHashCode() {"); pr.beginBlock(); if (serInfo.members.size() == 0) { pr.println("return 0;"); } else { boolean moreThanOneMember = serInfo.members.size() > 1; // print temporary variables for double values int countDoubles = 0; for (MemberInfo minfo : serInfo.members) { if (!minfo.type.isArrayType() && minfo.type.name.equals("double")) { String varName = "temp" + (++countDoubles); pr.print("final long ").print(varName).print(" = Double.doubleToLongBits(").print(minfo.name).println(");"); } } // compute hash // print line 31*(31*(31* ... CodePrinter mpr = pr.print("return "); for (int i = 0; i < serInfo.members.size()-1; i++) { mpr.print("31*("); } if (moreThanOneMember) pr.beginBlock(); // print hash values for doubles - use the temporary variables created above for (int i = 0; i < countDoubles; i++) { if (i != 0) mpr.print(" )"); if (moreThanOneMember) { pr.println(); mpr = pr.print(i != 0 ? " + " : " "); } String varName = "temp" + (i + 1); mpr.print("(int)(").print(varName).print(" ^ (").print(varName).print(" >>> 32))"); } // print hash values for non-double members for (int i = 0; i < serInfo.members.size(); i++) { MemberInfo minfo = serInfo.members.get(i); if (minfo.type.isArrayType() || !minfo.type.name.equals("double")) { boolean notFirst = (countDoubles != 0 || i != 0); if (notFirst) mpr.print(" )"); if (moreThanOneMember) { pr.println(); mpr = pr.print(notFirst ? " + " : " "); } printHashMember(mpr, minfo); } } mpr.println(";"); if (moreThanOneMember) pr.endBlock(); } pr.endBlock(); pr.println("}"); log.debug("printHashCode"); } private void printHashMember(CodePrinter pr, MemberInfo minfo) { TypeInfo tinfo = minfo.type; if (tinfo.isArrayType()) { pr.print("java.util.Arrays.hashCode(").print(minfo.name).print(")"); } else if (tinfo.isPointerType()) { pr.print("(").print(minfo.name).print("==null ? 0 : ").print(minfo.name).print(".hashCode())"); } else if (tinfo.name.equals("boolean")) { pr.print("(").print(minfo.name).print(" ? 1231 : 1237)"); } else if (tinfo.name.equals("byte") || tinfo.name.equals("char") || tinfo.name.equals("short") || tinfo.name.equals("int")) { pr.print(minfo.name); } else if (tinfo.name.equals("long")) { pr.print("(int)(").print(minfo.name).print(" ^ ").print("(").print(minfo.name).print(" >>> 32))"); } else if (tinfo.name.equals("float")) { pr.print("Float.floatToIntBits(").print(minfo.name).print(")"); } else if (tinfo.name.equals("void")) { // Type void can be used by methods pr.print("0"); } else { throw new IllegalStateException("printHashMember called for unexpected type: " + minfo.type.toString()); } } private void printEquals() throws IOException { log.debug("printEquals"); pr.println("public override boolean Equals(Object obj) {"); pr.beginBlock(); pr.println("if (this==obj) return true;"); pr.println("if (obj==null) return false;"); pr.println("if (getClass() != obj.getClass()) return false;"); if (serInfo.members.size() == 0) { pr.println("return true;"); } else { pr.println(); pr.print("final ").print(serInfo.name).print(" rhs = (").print(serInfo.name).print(")obj;").println(); CodePrinter mpr = pr.print("return "); for (int i = 0; i < serInfo.members.size(); i++) { MemberInfo minfo = serInfo.members.get(i); if (i != 0) { mpr.println(" &&"); mpr = pr.print(" "); } if (minfo.type.isArrayType()) { // Arrays.equals(arrayStruct2, other.arrayStruct2) && if (minfo.type.dims.length() == 2) { mpr.print("java.util.Arrays.equals(").print(minfo.name).print(", rhs.").print(minfo.name).print(")"); } else { mpr.print("java.util.Arrays.deepEquals(").print(minfo.name).print(", rhs.").print(minfo.name).print(")"); } } else if (minfo.type.isPointerType()) { // (listStruct1 == other.listStruct1 || (listStruct1 != null && listStruct1.equals(other.listStruct1))) String lhs = minfo.name; String rhs = "rhs." + minfo.name; mpr.print("(").print(lhs).print("==").print(rhs).print(" || ") .print("(").print(lhs).print("!=null && ").print(lhs).print(".equals(").print(rhs).print(")))"); } else if (minfo.type.name.equals("double")) { String lhs = "Double.doubleToLongBits(" + minfo.name + ")"; String rhs = "Double.doubleToLongBits(rhs." + minfo.name + ")"; mpr.print(lhs).print("==").print(rhs); } else if (minfo.type.name.equals("float")) { String lhs = "Float.floatToIntBits(" + minfo.name + ")"; String rhs = "Float.floatToIntBits(rhs." + minfo.name + ")"; mpr.print(lhs).print("==").print(rhs); } else if (minfo.type.name.equals("void")) { // Type void can be used by methods mpr.print("true"); } else { mpr.print(minfo.name).print("==rhs.").print(minfo.name); } } mpr.println(";"); } pr.endBlock(); pr.println("}"); log.debug(")printEquals"); } private void printSerialVersionUID() { log.debug("printSerialVersionUID"); String kw = ""; // final class? if (serInfo.isInline) { // -> cannot have a base class -> do not need new // see ClassDB.verify(SerialInfo) } else { // has base class? if (serInfo.baseInfo != null) { kw = "new "; } } pr.print("public static readonly ").print(kw).print("long serialVersionUID = " + serInfo.typeId + "L;"); log.debug(")printSerialVersionUID"); } private void generate() throws IOException { pctxt.printDoNotModify(pr); pr.println("using System;"); pr.println("using System.Collections.Generic;"); pr.println("using byps;"); pr.println(); pr.print("namespace ").println(pctxt.renamePackage(serInfo.pack)); pr.println("{"); pr.beginBlock(); pr.println(); pctxt.printComments(pr, serInfo.comments); if (serInfo.isEnum){ generateEnum(); } else { generateClass(); } pr.endBlock(); pr.println("} // end namespace"); } private ArrayList<MemberInfo> sortEnumMembersByOrdinal(List<MemberInfo> members) { ArrayList<MemberInfo> m = new ArrayList<MemberInfo>(members); Collections.sort(m, new Comparator<MemberInfo>() { @Override public int compare(MemberInfo o1, MemberInfo o2) { int v1 = Integer.parseInt(o1.value); int v2 = Integer.parseInt(o2.value); return v1 - v2; } }); return m; } private void generateEnum() throws IOException { pr.print("public enum ").print(serInfo.name).println(); pr.println("{"); pr.beginBlock(); ArrayList<MemberInfo> membersByOrdinal = sortEnumMembersByOrdinal(serInfo.members); for (MemberInfo minfo : membersByOrdinal) { pctxt.printComments(pr, minfo.comments); pr.print(minfo.name).print(", // ordinal=").print(minfo.value).println(); } pr.endBlock(); pr.println("} // end enum"); } private void generateClass() throws IOException { log.debug("generate"); String sfinal = serInfo.isFinal ? "sealed " : ""; CodePrinter mpr = pr.print("public ").print(sfinal).print("class ").print(serInfo.name); if (serInfo.isResultClass()) { String rtype = pctxt.getReturnTypeAsObjType(methodInfo, serInfo.pack); String baseClass = "BMethodResult<" + rtype + ">"; mpr.print(" : ").print(baseClass).print(", BSerializable"); } else if (serInfo.isRequestClass()) { mpr.print(" : BMethodRequest, BSerializable"); } else { if (serInfo.baseInfo != null) { TypeInfo csinfo = pctxt.toCSharp(serInfo.baseInfo); String baseName = csinfo.toString(serInfo.pack); mpr.print(" : ").print(baseName).print(", BSerializable"); } else { mpr.print(" : BSerializable"); } } mpr.println(); pr.println("{"); pr.println(); pr.beginBlock(); if (!serInfo.isResultClass() && !serInfo.isRequestClass()) { pr.println("#region Constructors"); pr.println(); printConstructors(); pr.println(); pr.println("#endregion"); pr.println(); } if (!serInfo.isResultClass() && !serInfo.isRequestClass()) { pr.println("#region Properties"); pr.println(); for (MemberInfo minfo : serInfo.members) { printGetSet(minfo); } pr.println("#endregion"); pr.println(); } else { // Result Klasse erbt beide Elemente (result, exception) von BMethodResult } if (serInfo.isRequestClass()) { pr.println("#region Execute"); pr.println(); printRemoteId(); pr.println(); printSetSession(); printExecute(); pr.println(); pr.println("#endregion"); pr.println(); } // Generate hashCode() and equals() if (pctxt.isGenerateHashCodeAndEquals() && methodInfo == null) { printHashCode(); pr.println(); printEquals(); pr.println(); } if (!serInfo.isResultClass()) { pr.println("#region Fields"); pr.println(); for (MemberInfo minfo : serInfo.members) { printMember(minfo); } pr.println("#endregion"); pr.println(); } else { // Result Klasse erbt beide Elemente (result, exception) von BMethodResult } pr.println(); printSerialVersionUID(); pr.println(); pr.endBlock(); pr.println("} // end class"); log.debug(")generate"); } private final SerialInfo serInfo; private final CodePrinter pr; private final MethodInfo methodInfo; private final PrintContext pctxt; }
dhwanisanmukhani/competitive-coding
codeforces/bit++.cpp
#include <iostream> using namespace std; int main() { int n,answer=0; cin>>n; string s; for(int i=1;i<=n;i++) { cin>>s; if (s=="++X"||s=="X++") { answer++; } else { answer--; } } cout<<answer<<endl; return 0; }
elikary/tois2021
librec-2.0.0/core/src/main/java/net/librec/recommender/cf/ranking/RankSGDRecommender.java
/** * Copyright (C) 2016 LibRec * <p> * This file is part of LibRec. * LibRec is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * LibRec is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with LibRec. If not, see <http://www.gnu.org/licenses/>. */ package net.librec.recommender.cf.ranking; import net.librec.annotation.ModelData; import net.librec.common.LibrecException; import net.librec.math.algorithm.Randoms; import net.librec.math.structure.MatrixEntry; import net.librec.math.structure.SparseMatrix; import net.librec.recommender.MatrixFactorizationRecommender; import net.librec.util.Lists; import java.util.*; /** * Jahrer and Toscher, Collaborative Filtering Ensemble for Ranking, JMLR, 2012 (KDD Cup 2011 Track 2). * * @author guoguibing and <NAME> */ @ModelData({"isRanking", "ranksgd", "userFactors", "itemFactors", "trainMatrix"}) public class RankSGDRecommender extends MatrixFactorizationRecommender { // item sampling probabilities sorted ascendingly protected List<Map.Entry<Integer, Double>> itemProbs; @Override protected void setup() throws LibrecException { super.setup(); // compute item sampling probability Map<Integer, Double> itemProbsMap = new HashMap<>(); for (int j = 0; j < numItems; j++) { int users = trainMatrix.columnSize(j); // sample items based on popularity double prob = (users + 0.0) / numRates; if (prob > 0) itemProbsMap.put(j, prob); } itemProbs = Lists.sortMap(itemProbsMap); } @Override protected void trainModel() throws LibrecException { List<Set<Integer>> userItemsSet = getUserItemsSet(trainMatrix); for (int iter = 1; iter <= numIterations; iter++) { loss = 0.0d; // for each rated user-item (u,i) pair for (MatrixEntry matrixEntry : trainMatrix) { int userIdx = matrixEntry.row(); int posItemIdx = matrixEntry.column(); double posRating = matrixEntry.get(); int negItemIdx = -1; while (true) { // draw an item j with probability proportional to popularity double sum = 0, rand = Randoms.random(); for (Map.Entry<Integer, Double> itemProb : itemProbs) { int itemIdx = itemProb.getKey(); double prob = itemProb.getValue(); sum += prob; if (sum >= rand) { negItemIdx = itemIdx; break; } } // ensure that it is unrated by user u if (!userItemsSet.get(userIdx).contains(negItemIdx)) break; } double negRating = 0; // compute predictions double posPredictRating = predict(userIdx, posItemIdx), negPredictRating = predict(userIdx, negItemIdx); double error = (posPredictRating - negPredictRating) - (posRating - negRating); loss += error * error; // update vectors double sgd = learnRate * error; for (int factorIdx = 0; factorIdx < numFactors; factorIdx++) { double userFactorValue = userFactors.get(userIdx, factorIdx); double posItemFactorValue = itemFactors.get(posItemIdx, factorIdx); double negItemFactorValue = itemFactors.get(negItemIdx, factorIdx); userFactors.add(userIdx, factorIdx, -sgd * (posItemFactorValue - negItemFactorValue)); itemFactors.add(posItemIdx, factorIdx, -sgd * userFactorValue); itemFactors.add(negItemIdx, factorIdx, sgd * userFactorValue); } } loss *= 0.5d; if (isConverged(iter) && earlyStop) { break; } updateLRate(iter); } } private List<Set<Integer>> getUserItemsSet(SparseMatrix sparseMatrix) { List<Set<Integer>> userItemsSet = new ArrayList<>(); for (int userIdx = 0; userIdx < numUsers; ++userIdx) { userItemsSet.add(new HashSet<>(sparseMatrix.getColumns(userIdx))); } return userItemsSet; } }
XploreX/cgpa-book-server
utility/error-util/basicErrorHandler.js
<filename>utility/error-util/basicErrorHandler.js<gh_stars>1-10 /** * Print error and throws * @param {Error} err * @param {String} message * @throws */ function basicErrorHandler(err, message = null) { if (message) { console.log(message); } else { console.log('Error occured'); } throw err; } module.exports = basicErrorHandler;
djordje/express-gateway
test/plugins/schema.test.js
const path = require('path'); const should = require('should'); const pluginsLoader = require('../../lib/plugins'); // Caching fixture plugin, but redefining its properties for testing plugin load. const pluginName = 'express-gateway-plugin-test'; const pluginDirectory = path.join(__dirname, '../fixtures', pluginName); const testPlugin = require(pluginDirectory); testPlugin.schema = { $id: `http://express-gateway.io/schemas/plugin/${pluginName}.json`, required: ['schema-test-param'] }; testPlugin.init = (pluginContext) => { pluginContext.registerPolicy('schema-test-policy'); }; describe('Plugin schema validation on load', () => { it('fails loading when parameter undefined', () => { const missingParameterConfig = { config: { systemConfig: { plugins: { test: { package: pluginDirectory } } } } }; const loadedPlugins = pluginsLoader.load(missingParameterConfig); should(loadedPlugins).have.property('policies').empty(); }); it('loads plugin and registers policy successfully', () => { const config = { config: { systemConfig: { plugins: { test: { package: pluginDirectory, 'schema-test-param': 'defined' } } } } }; const loadedPlugins = pluginsLoader.load(config); should(loadedPlugins).have.property('policies', ['schema-test-policy']); }); });
JoyLau/joylau-mybatis
src/main/java/cn/joylau/mybatis/mapper/common/condition/DeleteByConditionMapper.java
<reponame>JoyLau/joylau-mybatis<gh_stars>1-10 /******************************************************************************* * Copyright (c) 2017 by JoyLau. All rights reserved ******************************************************************************/ package cn.joylau.mybatis.mapper.common.condition; import cn.joylau.mybatis.mapper.provider.ConditionProvider; import org.apache.ibatis.annotations.DeleteProvider; /** * 通用Mapper接口,Condition查询 * @param <T> 不能为空 */ public interface DeleteByConditionMapper<T> { /** * 根据Condition条件删除数据 * * @param condition * @return */ @DeleteProvider(type = ConditionProvider.class, method = "dynamicSQL") int deleteByCondition(Object condition); }
kue-ipc/nodecan
app/views/hardware_types/_hardware_type.json.jbuilder
json.extract! hardware_type, :id, :code, :name, :description, :category, :order, :created_at, :updated_at json.url hardware_type_url(hardware_type, format: :json)
IMSY-DKFZ/simpa
simpa/utils/serializer.py
<gh_stars>1-10 # SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ # SPDX-FileCopyrightText: 2021 <NAME> # SPDX-License-Identifier: MIT from abc import ABC, abstractmethod class SerializableSIMPAClass(ABC): """ TODO """ @abstractmethod def serialize(self) -> dict: pass @staticmethod @abstractmethod def deserialize(dictionary_to_deserialize: dict): pass
OctopusLian/leetcode-solutions
LCP/1.guess-numbers/guess-numbers_1-loop.go
func game(guess []int, answer []int) int { ans := 0 for i:=0;i<len(guess);i++ { if guess[i] == answer[i] { ans++ } } return ans }
c7yrus/alyson-v3
src/utils/data-query/test.js
import DataQuery from './DataQuery'; import store from '../../redux/store'; const query = [ { operator: 'getBE', id: 'GRP_DASHBOARD', as: 'dashboard', }, { operator: 'scope', path: 'dashboard.links', scope: { operator: 'getBE', basePath: 'baseEntities.data', as: 'be', id: '{{link.targetCode}}', }, }, { operator: 'map', fields: 'dashboard.links', }, { operator: 'sort', by: 'weight', direction: 'asc', }, { operator: 'map', fields: 'be', }, { operator: 'scope', path: 'links', scope: { operator: 'getBE', basePath: 'baseEntities.data', as: 'be', id: '{{link.targetCode}}', }, }, { operator: 'map', fields: { name: 'name', items: 'links', }, }, { operator: 'scope', path: 'items', scope: { operator: 'find', query: { be: { $exists: true }, }, }, }, { operator: 'scope', path: 'items', scope: { operator: 'map', fields: { linkValue: 'link.linkValue', item: 'be', }, }, }, { operator: 'scope', path: 'items', scope: { operator: 'populateLinkValues', field: 'item', as: 'links', }, }, { operator: 'scope', path: 'items', scope: { operator: 'populateAttributes', path: 'links', }, }, { operator: 'scope', path: 'items', scope: { operator: 'populateAttributes', path: 'item', single: true, }, }, // { // operator: 'populateAttributes', // path: 'item', // }, // { // operator: 'scope', // path: 'items', // scope: { // operator: 'map', // append: true, // fields: { // // }, // }, // } ]; window.testQuery = () => { const dataQuery = new DataQuery( store.getState().vertx ); const result = dataQuery.query( query ); return result; };
WCry/demo
spring-cloud/springcloud/service-api/seckill-api/src/main/java/com/zxp/seckill/pojo/dto/VerificationSecSkillOrder.java
<filename>spring-cloud/springcloud/service-api/seckill-api/src/main/java/com/zxp/seckill/pojo/dto/VerificationSecSkillOrder.java package com.zxp.seckill.pojo.dto; import com.zxp.seckill.pojo.SecKillGoodIdentify; import com.zxp.seckill.pojo.SecKillVerification; import com.zxp.user.pojo.UserIdentifies; import lombok.Data; import lombok.ToString; @ToString @Data public class VerificationSecSkillOrder implements SecKillGoodIdentify, UserIdentifies, SecKillVerification { private String openID; private Long secKillID; private String verificationID; private String verificationCode; }
zhangzhichaolove/MusicLake
app/src/main/java/com/cyl/musiclake/ui/music/online/activity/NeteasePlaylistActivity.java
<gh_stars>0 package com.cyl.musiclake.ui.music.online.activity; import android.os.Bundle; import android.support.annotation.Nullable; import com.cyl.musiclake.ui.music.online.base.BasePlaylistActivity; /** * 作者:yonglong on 2016/8/24 10:43 * 邮箱:<EMAIL> * 版本:2.5 */ @SuppressWarnings("ConstantConditions") public class NeteasePlaylistActivity extends BasePlaylistActivity { private static final String TAG = "BaiduMusicListActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter.getPlaylist(getIntent().getStringExtra("id"), this); } @Override protected void retryLoading() { super.retryLoading(); mPresenter.getPlaylist(getIntent().getStringExtra("id"), this); } @Override public String getToolBarTitle() { return getIntent().getStringExtra("title"); } }
cassiasamp/live-de-python
codigo/Live146/core/models.py
<filename>codigo/Live146/core/models.py from django.db import models class Todo(models.Model): title = models.CharField("Título", max_length=50) description = models.TextField("Descrição") done = models.BooleanField(default=False)
shaojiankui/iOS10-Runtime-Headers
protocols/TSKRenderingExporter.h
/* Generated by RuntimeBrowser. */ @protocol TSKRenderingExporter <TSKExporter> @required - (struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })boundsRect; - (bool)drawCurrentPageInContext:(struct CGContext { }*)arg1 viewScale:(double)arg2 unscaledClipRect:(struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })arg3 createPage:(bool)arg4; - (bool)exportToURL:(NSURL *)arg1 pageNumber:(unsigned long long)arg2 delegate:(id <TSKImportExportDelegate>)arg3 error:(id*)arg4; - (bool)hasMoreThanOnePageToPrint; - (bool)incrementPage; - (unsigned long long)pageCount; - (bool)paginate; - (void)performBlockWithImager:(void *)arg1; // needs 1 arg types, found 6: id /* block */, /* Warning: Unrecognized filer type: '<' using 'void*' */ void*, void, id /* block */, TSDImager *, void* - (bool)preparePage:(unsigned long long)arg1; - (double)progressForCurrentPage; - (bool)setInfosToCurrentPage; - (void)setPaginate:(bool)arg1; - (void)setup; - (void)teardown; - (struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })unscaledClipRect; @end
n0bis/Warcell
Warcell/OSGiCommon/src/main/java/warcell/common/data/entityparts/TimerPart.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package warcell.common.data.entityparts; import warcell.common.data.Entity; import warcell.common.data.GameData; public class TimerPart implements EntityPart { private float expiration; public TimerPart(float expiration) { this.expiration = expiration; } public float getExpiration() { return expiration; } public void setExpiration(float expiration) { this.expiration = expiration; } public void reduceExpiration(float delta) { this.expiration -= delta; } @Override public void process(GameData gameData, Entity entity) { if (expiration > 0) { reduceExpiration(gameData.getDelta()); } } }
guilhermejccavalcanti/ontop
client/protege/src/main/java/it/unibz/inf/ontop/protege/gui/treemodels/TreeModelFilter.java
<reponame>guilhermejccavalcanti/ontop<gh_stars>0 package it.unibz.inf.ontop.protege.gui.treemodels; /* * #%L * ontop-protege * %% * Copyright (C) 2009 - 2013 KRDB Research Centre. Free University of Bozen Bolzano. * %% * 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. * #L% */ /** * An abstract filter that can be used by TreeModels to discriminate certain * elements stored in the controller associated to the tree model. * * @param <T> * T is the class name of the kind of object that is taken as input * by an implementation of TreeModelFilter. */ public abstract class TreeModelFilter<T extends Object> { protected boolean bNegation; protected String[] vecKeyword; public void putNegation() { bNegation = true; } public void addStringFilter(String[] values) { vecKeyword = values; } /** * A matching function that returns true if the object complies to the * internal logic of the Filter. Instances of TreeModelFilter should define * their own logic. * * @param object * The object that needs to be matches * @return true if the object matches the internal logic, false otherwise */ public abstract boolean match(T object); }
hokaccha/kuroko2
app/controllers/kuroko2/job_definitions_controller.rb
<filename>app/controllers/kuroko2/job_definitions_controller.rb class Kuroko2::JobDefinitionsController < Kuroko2::ApplicationController before_action :set_definition, only: [:show, :edit, :update, :destroy] def index rel = Kuroko2::JobDefinition.joins(:admins).includes(:tags, :job_schedules, :admins) query = query_params[:q] if query.present? rel = rel.search_by(query) end @input_tags = query_params[:tag] || [] if @input_tags.present? rel = rel.tagged_by(@input_tags) end if query.present? || @input_tags.present? @related_tags = rel.includes(:tags).map(&:tags).flatten.uniq else @related_tags = Kuroko2::Tag.all end @definitions = rel.ordered.page(page_params[:page]) end def show @instances = @definition.job_instances.page(0) @schedules = @definition.job_schedules @suspend_schedules = @definition.job_suspend_schedules @schedule = Kuroko2::JobSchedule.new(job_definition: @definitions) @suspend_schedule = Kuroko2::JobSuspendSchedule.new(job_definition: @definitions) end def new dup_from = Kuroko2::JobDefinition.find_by(id: params[:dup_from]) if dup_from.present? @definition = dup_from.dup @definition.admins = dup_from.admins @definition.tags = dup_from.tags else @definition = Kuroko2::JobDefinition.new end @definition.admins << current_user unless @definition.admins.include?(current_user) end def create @definition = Kuroko2::JobDefinition.new(definition_params) @definition.admins = Kuroko2::User.active.with(admin_id_params) if @definition.save_and_record_revision(edited_user: current_user) current_user.stars.create(job_definition: @definition) redirect_to @definition, notice: 'Job Definition was successfully created.' else render :new end end def edit end def update success = ActiveRecord::Base.transaction do @definition.attributes = definition_params @definition.admins = Kuroko2::User.active.with(admin_id_params) @definition.save_and_record_revision(edited_user: current_user) end if success redirect_to @definition, notice: 'Job Definition was successfully updated.' else render :edit end end def destroy @definition.destroy redirect_to job_definitions_path, notice: 'Job Definition was successfully destroyed.' end private def admin_id_params params.require(:admin_assignments).permit(user_id: []). try!(:[], :user_id). try!(:reject, &:blank?). try!(:map, &:to_i) || [] end def definition_params params.require(:job_definition).permit(:name, :description, :script, :notify_cancellation, :hipchat_room, :hipchat_notify_finished, :suspended, :prevent_multi, :prevent_multi_on_failure, :hipchat_additional_text, :text_tags, :api_allowed, :slack_channel, :webhook_url) end def query_params params.permit(:q, tag: []) end def page_params params.permit(:page) end def set_definition @definition = Kuroko2::JobDefinition.find(params[:id]) end end
swxiao/bubble-foundation
bubble-foundation-mybatis/src/main/java/com/bubble/foundation/mybatis/support/MyBatisRepositoryImpl.java
<gh_stars>0 /** * Copyright 2015-2017 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.bubble.foundation.mybatis.support; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.util.Assert; import com.bubble.foundation.mybatis.AbstractEntity; import com.bubble.foundation.mybatis.MybatisRepository; /** * 持久化操作,MybatisRepository接口功能具体实现类</br> * * @author <NAME><<EMAIL>> * @since 2015年1月30日 */ public final class MyBatisRepositoryImpl<T extends AbstractEntity, ID extends Serializable> implements MybatisRepository<T, ID> { private static final String ID_MUST_NOT_BE_NULL = "The given id must not be null!"; private static final String ENTITY_MUST_NOT_BE_NULL = "The given entity must not be null!"; /** * sqlSessionTemplate */ private SqlSessionTemplate sqlSessionTemplate; /** * mappedNameSpaceId; */ private String mapperNamespaceId; /** * @param sqlSessionTemplate * @param mapperNamespaceId */ public MyBatisRepositoryImpl(SqlSessionTemplate sqlSessionTemplate, String mapperNamespaceId) { Assert.notNull(sqlSessionTemplate, "sqlSessionTemplate must not be null!"); Assert.notNull(mapperNamespaceId, "mappedNameSpaceId must not be null!"); this.sqlSessionTemplate = sqlSessionTemplate; this.mapperNamespaceId = mapperNamespaceId; } @Override public List<T> findAll() { return sqlSessionTemplate.selectList(getMapperId()); } @Override public T save(T entity) { Assert.notNull(entity, ENTITY_MUST_NOT_BE_NULL); int result = sqlSessionTemplate.insert(getMapperId(), entity); return result > 0 ? entity : null; } @Override public Iterable<T> save(Iterable<T> entities) { if (entities == null || !entities.iterator().hasNext()) { return Collections.emptyList(); } List<T> result = new ArrayList<T>(); for (T entity : entities) { result.add(save(entity)); } return result; } @Override public T findOne(ID id) { Assert.notNull(id, ID_MUST_NOT_BE_NULL); return sqlSessionTemplate.selectOne(getMapperId(), id); } @Override public boolean exists(ID id) { return findOne(id) == null ? false : true; } @Override public Iterable<T> findAll(Iterable<ID> ids) { if (ids == null || !ids.iterator().hasNext()) { return Collections.emptyList(); } List<T> results = new ArrayList<T>(); for (ID id : ids) { results.add(findOne(id)); } return results; } @Override public long count() { return findAll().size(); } public T update(T entity, boolean query) { Assert.notNull(entity, ID_MUST_NOT_BE_NULL); if (query) Assert.notNull(entity.getId(), ENTITY_MUST_NOT_BE_NULL); int result = sqlSessionTemplate.update(getMapperId(), entity); if (query) { return result > 0 ? findOne((ID) entity.getId()) : null; } else { return result > 0 ? entity : null; } } @Override public T saveOrUpdate(T entity) { Assert.notNull(entity, ENTITY_MUST_NOT_BE_NULL); ID id = (ID) entity.getId(); if (exists(id)) { return update(entity, true); } else { return save(entity); } } @Override public void delete(ID id) { Assert.notNull(id, ID_MUST_NOT_BE_NULL); sqlSessionTemplate.delete(getMapperId(), id); } @Override public void delete(T entity) { Assert.notNull(entity, ENTITY_MUST_NOT_BE_NULL); sqlSessionTemplate.delete(getMapperId(), entity); } @Override public void delete(Iterable<? extends T> entities) { Assert.notNull(entities, "The given Iterable of entities not be null!"); for (T entity : entities) { delete(entity); } } @Override public void deleteAll() { for (T element : findAll()) { delete(element); } } private final String getMapperId() { return mapperNamespaceId + "." + Thread.currentThread().getStackTrace()[2].getMethodName(); } }
Antor/BasicLearningSystem
basic-learning-system/src/main/java/com/gravityray/basiclearningsystem/catalogue/CourseCatalogueController.java
<reponame>Antor/BasicLearningSystem package com.gravityray.basiclearningsystem.catalogue; import com.gravityray.basiclearningsystem.enrolment.EnrolmentService; import org.apache.commons.lang3.StringUtils; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/catalogue/course") public class CourseCatalogueController { private static final String TARGET_CATALOGUE = "catalogue"; private static final String TARGET_PROFILE = "profile"; private final CourseCatalogueService courseCatalogueService; private final EnrolmentService enrolmentService; public CourseCatalogueController( CourseCatalogueService courseCatalogueService, EnrolmentService enrolmentService) { this.courseCatalogueService = courseCatalogueService; this.enrolmentService = enrolmentService; } @GetMapping public String catalogue(Model model, @AuthenticationPrincipal UserDetails userDetails) { String email = userDetails != null ? userDetails.getUsername() : null; model.addAttribute( "catalogue", courseCatalogueService.getCourseCatalogue(email)); return "catalogue"; } @GetMapping("/{courseId}/enrol") public String courseEnrolGet( @PathVariable long courseId, @RequestParam("target") String target, @AuthenticationPrincipal UserDetails userDetails, Model model) { model.addAttribute( "course", enrolmentService.getCourseEnrolmentInfo(courseId, userDetails.getUsername())); model.addAttribute("target", target); return "course_enrol"; } @PostMapping("{courseId}/enrol") public String courseEnrolPost( @PathVariable long courseId, @RequestParam("target") String target, @AuthenticationPrincipal UserDetails userDetails) { enrolmentService.enrolCourse(courseId, userDetails.getUsername()); return getTargetRedirect(target); } @GetMapping("/{courseId}/leave") public String courseLeaveGet( @PathVariable long courseId, @RequestParam("target") String target, @AuthenticationPrincipal UserDetails userDetails, Model model) { model.addAttribute( "course", enrolmentService.getCourseEnrolmentInfo(courseId, userDetails.getUsername())); model.addAttribute("target", target); return "course_leave"; } @PostMapping("/{courseId}/leave") public String courseLeavePost( @PathVariable long courseId, @RequestParam("target") String target, @AuthenticationPrincipal UserDetails userDetails) { enrolmentService.leaveCourse(courseId, userDetails.getUsername()); return getTargetRedirect(target); } private String getTargetRedirect(String target) { switch (StringUtils.defaultString(target)) { case TARGET_PROFILE: return "redirect:/profile/course"; case TARGET_CATALOGUE: default: return "redirect:/catalogue/course"; } } }
bitcrystal/temp
build_deps/deps/qrencode-3.4.3/tests/create_mqr_frame_pattern.c
<filename>build_deps/deps/qrencode-3.4.3/tests/create_mqr_frame_pattern.c<gh_stars>10-100 /* * This tool creates a frame pattern data for debug purpose used by * test_qrspec. test_qrspec and create_frame_pattern uses the same function * of libqrencode. This means the test is meaningless if test_qrspec is run * with a pattern data created by create_frame_pattern of the same version. * In order to test it correctly, create a pattern data by the tool of the * previous version, or use the frame data attached to the package. */ #include <stdio.h> #include <string.h> #include <png.h> #include "common.h" #include "../mqrspec.h" void append_pattern(int version, FILE *fp) { int width; unsigned char *frame; frame = MQRspec_newFrame(version); width = MQRspec_getWidth(version); fwrite(frame, 1, width * width, fp); free(frame); } static int writePNG(unsigned char *frame, int width, const char *outfile) { static FILE *fp; png_structp png_ptr; png_infop info_ptr; unsigned char *row, *p, *q; int x, y, xx, yy, bit; int realwidth; const int margin = 0; const int size = 1; realwidth = (width + margin * 2) * size; row = (unsigned char *)malloc((realwidth + 7) / 8); if(row == NULL) { fprintf(stderr, "Failed to allocate memory.\n"); exit(EXIT_FAILURE); } if(outfile[0] == '-' && outfile[1] == '\0') { fp = stdout; } else { fp = fopen(outfile, "wb"); if(fp == NULL) { fprintf(stderr, "Failed to create file: %s\n", outfile); perror(NULL); exit(EXIT_FAILURE); } } png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(png_ptr == NULL) { fclose(fp); fprintf(stderr, "Failed to initialize PNG writer.\n"); exit(EXIT_FAILURE); } info_ptr = png_create_info_struct(png_ptr); if(info_ptr == NULL) { fclose(fp); fprintf(stderr, "Failed to initialize PNG write.\n"); exit(EXIT_FAILURE); } if(setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); fprintf(stderr, "Failed to write PNG image.\n"); exit(EXIT_FAILURE); } png_init_io(png_ptr, fp); png_set_IHDR(png_ptr, info_ptr, realwidth, realwidth, 1, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); /* top margin */ memset(row, 0xff, (realwidth + 7) / 8); for(y=0; y<margin * size; y++) { png_write_row(png_ptr, row); } /* data */ p = frame; for(y=0; y<width; y++) { bit = 7; memset(row, 0xff, (realwidth + 7) / 8); q = row; q += margin * size / 8; bit = 7 - (margin * size % 8); for(x=0; x<width; x++) { for(xx=0; xx<size; xx++) { *q ^= (*p & 1) << bit; bit--; if(bit < 0) { q++; bit = 7; } } p++; } for(yy=0; yy<size; yy++) { png_write_row(png_ptr, row); } } /* bottom margin */ memset(row, 0xff, (realwidth + 7) / 8); for(y=0; y<margin * size; y++) { png_write_row(png_ptr, row); } png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); free(row); return 0; } void write_pattern_image(int version, const char *filename) { int width; unsigned char *frame; static char str[256]; frame = MQRspec_newFrame(version); width = MQRspec_getWidth(version); snprintf(str, 256, "%s-M%d.png", filename, version); writePNG(frame, width, str); free(frame); } void write_pattern(const char *filename) { FILE *fp; int i; fp = fopen(filename, "wb"); if(fp == NULL) { perror("Failed to open a file to write:"); abort(); } for(i=1; i<=MQRSPEC_VERSION_MAX; i++) { append_pattern(i, fp); write_pattern_image(i, filename); } fclose(fp); } int main(int argc, char **argv) { if(argc < 2) { printf("Create empty frame patterns.\nUsage: %s FILENAME\n", argv[0]); exit(0); } write_pattern(argv[1]); return 0; }
AgileVentures/project_unify
app/services/user_service.rb
<reponame>AgileVentures/project_unify class UserService include Godmin::Resources::ResourceService attrs_for_index :user_name, :mentor, :private, :skill_list attrs_for_show :user_name, :introduction, :mentor, :gender, :private, :email, :skill_list, :created_at attrs_for_form :user_name, :email, :gender, :mentor, :private, :password, :password_confirmation, :introduction, :skill_list filter :user_name filter :skill_list batch_action :destroy, confirm: true def filter_user_name(resources, value) resources.where('user_name LIKE ?', "%#{value}%") end def filter_skill_list(resources, value) resources.tagged_with(value) end def update_resource(resource, params) if params[:password].blank? params.delete(:password) params.delete(:password_confirmation) end resource.update(params) end def resources_relation super.all_profiles end end
OakCityLabs/ios_system
shell_cmds/uname/uname.c
<gh_stars>100-1000 /* $NetBSD: uname.c,v 1.10 1998/11/09 13:24:05 kleink Exp $ */ /* * Copyright (c) 1994 <NAME>, 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: * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Winning Strategies, Inc. * 4. The name of Winning Strategies, Inc. may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> #ifndef lint __RCSID("$NetBSD: uname.c,v 1.10 1998/11/09 13:24:05 kleink Exp $"); #endif /* not lint */ #include <sys/param.h> #include <limits.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <err.h> #ifdef __APPLE__ #include <string.h> #include <TargetConditionals.h> #endif /* __APPLE__ */ #include <sys/sysctl.h> #include <sys/utsname.h> #include <errno.h> #include "ios_error.h" #ifdef __APPLE__ // #include <get_compat.h> // #else /* !__APPLE__ */ #define COMPAT_MODE(a,b) (1) #endif /* __APPLE__ */ int uname_main __P((int, char **)); static void usage __P((void)); /* Note that PRINT_MACHINE_ARCH is excluded from PRINT_ALL! */ #define PRINT_SYSNAME 0x01 #define PRINT_NODENAME 0x02 #define PRINT_RELEASE 0x04 #define PRINT_VERSION 0x08 #define PRINT_MACHINE 0x10 #define PRINT_MACHINE_ARCH 0x20 #define PRINT_ALL \ (PRINT_SYSNAME|PRINT_NODENAME|PRINT_RELEASE|PRINT_VERSION|PRINT_MACHINE) int uname_main(argc, argv) int argc; char **argv; { struct utsname u; #ifndef __APPLE__ char machine_arch[SYS_NMLN]; #endif /* !__APPLE__ */ int c; int space = 0; int print_mask = 0; optind = 1; opterr = 1; optreset = 1; (void)setlocale(LC_ALL, ""); while ((c = getopt(argc,argv,"amnprsv")) != -1) { switch (c) { case 'a': print_mask |= PRINT_ALL; #ifdef __APPLE__ if (!COMPAT_MODE("bin/uname", "Unix2003")) { print_mask |= PRINT_MACHINE_ARCH; } #endif /* __APPLE__ */ break; case 'm': print_mask |= PRINT_MACHINE; break; case 'n': print_mask |= PRINT_NODENAME; break; case 'p': print_mask |= PRINT_MACHINE_ARCH; break; case 'r': print_mask |= PRINT_RELEASE; break; case 's': print_mask |= PRINT_SYSNAME; break; case 'v': print_mask |= PRINT_VERSION; break; default: usage(); /* NOTREACHED */ } } if (optind != argc) { usage(); /* NOTREACHED */ } if (!print_mask) { print_mask = PRINT_SYSNAME; } if (uname(&u) != 0) { err(EXIT_FAILURE, "uname"); /* NOTREACHED */ } #ifndef __APPLE__ if (print_mask & PRINT_MACHINE_ARCH) { int mib[2] = { CTL_HW, HW_MACHINE_ARCH }; size_t len = sizeof (machine_arch); if (sysctl(mib, sizeof (mib) / sizeof (mib[0]), machine_arch, &len, NULL, 0) < 0) err(EXIT_FAILURE, "sysctl"); } #endif /* !__APPLE__ */ #ifdef __APPLE__ /* * Let's allow the user to override the output of uname via the shell environment. * This is a useful feature for cross-compiling (eg. during an OS bringup). * Otherwise, you have to hack your kernel with the desired strings. */ { char *s; s = getenv ("UNAME_SYSNAME"); if (s) strncpy (u.sysname, s, sizeof (u.sysname)); s = getenv ("UNAME_NODENAME"); if (s) strncpy (u.nodename, s, sizeof (u.nodename)); s = getenv ("UNAME_RELEASE"); if (s) strncpy (u.release, s, sizeof (u.release)); s = getenv ("UNAME_VERSION"); if (s) strncpy (u.version, s, sizeof (u.version)); #if TARGET_OS_SIMULATOR // iOS simulator pretends to be a Mac, so we make it explicit here: s = getenv("SIMULATOR_MODEL_IDENTIFIER"); if (s) strncpy (u.machine, s, sizeof (u.machine)); #endif // but we can still override it with environment variables: s = getenv ("UNAME_MACHINE"); if (s) strncpy (u.machine, s, sizeof (u.machine)); } #endif /* __APPLE__ */ if (print_mask & PRINT_SYSNAME) { space++; fputs(u.sysname, thread_stdout); } if (print_mask & PRINT_NODENAME) { if (space++) putchar(' '); fputs(u.nodename, thread_stdout); } if (print_mask & PRINT_RELEASE) { if (space++) putchar(' '); fputs(u.release, thread_stdout); } if (print_mask & PRINT_VERSION) { if (space++) putchar(' '); fputs(u.version, thread_stdout); } if (print_mask & PRINT_MACHINE) { if (space++) putchar(' '); fputs(u.machine, thread_stdout); } if (print_mask & PRINT_MACHINE_ARCH) { if (space++) putchar(' '); #ifndef __APPLE__ fputs(machine_arch, thread_stdout); #else #if defined(__ppc__) || defined(__ppc64__) fputs("powerpc", thread_stdout); #elif defined(__i386__) || defined(__x86_64__) fputs("i386", thread_stdout); #elif defined(__arm__) || defined(__arm64__) fputs("arm", thread_stdout); #else fputs("unknown", thread_stdout); #endif #endif /* __APPLE__ */ } putchar('\n'); exit(EXIT_SUCCESS); /* NOTREACHED */ } static void usage() { fprintf(thread_stderr, "usage: uname [-amnprsv]\n"); exit(EXIT_FAILURE); }
elyase/polyaxon
polyaxon/api/activitylogs/views.py
from rest_framework.generics import ListAPIView, get_object_or_404 from rest_framework.permissions import IsAuthenticated from django.db.models import Q import activitylogs from api.activitylogs.serializers import ActivityLogsSerializer from constants import content_types from db.models.activitylogs import ActivityLog from db.models.projects import Project class HistoryLogsView(ListAPIView): """Activity logs list view.""" # Filter only for user write events queryset = ActivityLog.objects.order_by('-created_at').filter( event_type__in=activitylogs.default_manager.user_view_events() ) serializer_class = ActivityLogsSerializer permission_classes = (IsAuthenticated,) def filter_queryset(self, queryset): queryset = queryset.filter(actor=self.request.user) return super().filter_queryset(queryset=queryset) class ActivityLogsView(ListAPIView): """Activity logs list view.""" # Filter only for user write events queryset = ActivityLog.objects.order_by('-created_at').filter( event_type__in=activitylogs.default_manager.user_write_events() ) serializer_class = ActivityLogsSerializer permission_classes = (IsAuthenticated,) class ProjectActivityLogsView(ActivityLogsView): """Project activity logs list view.""" def filter_queryset(self, queryset): project_name = self.kwargs['name'] username = self.kwargs['username'] project = get_object_or_404(Project, user__username=username, name=project_name) project_id = '{}'.format(project.id) # Filter for project/all events queryset = queryset.filter( Q(content_type__model=content_types.PROJECT, context__id=project_id) | Q(**{'context__project.id': project_id}) ) return super().filter_queryset(queryset=queryset)
lnsp/traefik
integration/consul_catalog_test.go
package integration import ( "fmt" "net" "net/http" "os" "time" "github.com/go-check/check" "github.com/hashicorp/consul/api" "github.com/traefik/traefik/v2/integration/try" checker "github.com/vdemeester/shakers" ) type ConsulCatalogSuite struct { BaseSuite consulClient *api.Client consulAgentClient *api.Client consulURL string } func (s *ConsulCatalogSuite) SetUpSuite(c *check.C) { s.createComposeProject(c, "consul_catalog") s.composeUp(c) s.consulURL = "http://" + net.JoinHostPort(s.getComposeServiceIP(c, "consul"), "8500") var err error s.consulClient, err = api.NewClient(&api.Config{ Address: s.consulURL, }) c.Check(err, check.IsNil) // Wait for consul to elect itself leader err = s.waitToElectConsulLeader() c.Assert(err, checker.IsNil) s.consulAgentClient, err = api.NewClient(&api.Config{ Address: "http://" + net.JoinHostPort(s.getComposeServiceIP(c, "consul-agent"), "8500"), }) c.Check(err, check.IsNil) } func (s *ConsulCatalogSuite) waitToElectConsulLeader() error { return try.Do(15*time.Second, func() error { leader, err := s.consulClient.Status().Leader() if err != nil || len(leader) == 0 { return fmt.Errorf("leader not found. %w", err) } return nil }) } func (s *ConsulCatalogSuite) waitForConnectCA() error { return try.Do(15*time.Second, func() error { caroots, _, err := s.consulClient.Connect().CARoots(nil) if err != nil || len(caroots.Roots) == 0 { return fmt.Errorf("connect CA not fully initialized. %w", err) } return nil }) } func (s *ConsulCatalogSuite) registerService(reg *api.AgentServiceRegistration, onAgent bool) error { client := s.consulClient if onAgent { client = s.consulAgentClient } return client.Agent().ServiceRegister(reg) } func (s *ConsulCatalogSuite) deregisterService(id string, onAgent bool) error { client := s.consulClient if onAgent { client = s.consulAgentClient } return client.Agent().ServiceDeregister(id) } func (s *ConsulCatalogSuite) TestWithNotExposedByDefaultAndDefaultsSettings(c *check.C) { reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg1, false) c.Assert(err, checker.IsNil) reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP(c, "whoami2"), } err = s.registerService(reg2, false) c.Assert(err, checker.IsNil) reg3 := &api.AgentServiceRegistration{ ID: "whoami3", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP(c, "whoami3"), } err = s.registerService(reg3, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/default_not_exposed.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "whoami" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2", "Hostname: whoami3")) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 2*time.Second, try.StatusCodeIs(200), try.BodyContains( fmt.Sprintf(`"http://%s:80":"UP"`, reg1.Address), fmt.Sprintf(`"http://%s:80":"UP"`, reg2.Address), fmt.Sprintf(`"http://%s:80":"UP"`, reg3.Address), )) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami2", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami3", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestByLabels(c *check.C) { containerIP := s.getComposeServiceIP(c, "whoami1") reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/whoami`)", "traefik.http.routers.router1.service=service1", "traefik.http.services.service1.loadBalancer.server.url=http://" + containerIP, }, Port: 80, Address: containerIP, } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/default_not_exposed.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://127.0.0.1:8000/whoami", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2", "Hostname: whoami3")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestSimpleConfiguration(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestSimpleConfigurationWithWatch(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple_watch.toml", tempObjects) defer os.Remove(file) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) whoamiIP := s.getComposeServiceIP(c, "whoami1") reg.Check = &api.AgentServiceCheck{ CheckID: "some-ok-check", TCP: whoamiIP + ":80", Name: "some-ok-check", Interval: "1s", Timeout: "1s", } err = s.registerService(reg, false) c.Assert(err, checker.IsNil) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContainsOr("Hostname: whoami1")) c.Assert(err, checker.IsNil) reg.Check = &api.AgentServiceCheck{ CheckID: "some-failing-check", TCP: ":80", Name: "some-failing-check", Interval: "1s", Timeout: "1s", } err = s.registerService(reg, false) c.Assert(err, checker.IsNil) err = try.Request(req, 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestRegisterServiceWithoutIP(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{"traefik.enable=true"}, Port: 80, Address: "", } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/http/services", nil) c.Assert(err, checker.IsNil) err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("whoami@consulcatalog", "\"http://127.0.0.1:80\": \"UP\"")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestDefaultConsulService(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) // Start traefik cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "whoami.consul.localhost" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulServiceWithTCPLabels(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) // Start a container with some tags reg := &api.AgentServiceRegistration{ ID: "whoamitcp", Name: "whoamitcp", Tags: []string{ "traefik.tcp.Routers.Super.Rule=HostSNI(`my.super.host`)", "traefik.tcp.Routers.Super.tls=true", "traefik.tcp.Services.Super.Loadbalancer.server.port=8080", }, Port: 8080, Address: s.getComposeServiceIP(c, "whoamitcp"), } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) // Start traefik cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`my.super.host`)")) c.Assert(err, checker.IsNil) who, err := guessWho("127.0.0.1:8000", "my.super.host", true) c.Assert(err, checker.IsNil) c.Assert(who, checker.Contains, "whoamitcp") err = s.deregisterService("whoamitcp", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulServiceWithLabels(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) // Start a container with some tags reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.http.Routers.Super.Rule=Host(`my.super.host`)", }, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg1, false) c.Assert(err, checker.IsNil) // Start another container by replacing a '.' by a '-' reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: []string{ "traefik.http.Routers.SuperHost.Rule=Host(`my-super.host`)", }, Port: 80, Address: s.getComposeServiceIP(c, "whoami2"), } err = s.registerService(reg2, false) c.Assert(err, checker.IsNil) // Start traefik cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "my-super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1")) c.Assert(err, checker.IsNil) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "my.super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami2")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami2", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestSameServiceIDOnDifferentConsulAgent(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/default_not_exposed.toml", tempObjects) defer os.Remove(file) // Start a container with some tags tags := []string{ "traefik.enable=true", "traefik.http.Routers.Super.service=whoami", "traefik.http.Routers.Super.Rule=Host(`my.super.host`)", } reg1 := &api.AgentServiceRegistration{ ID: "whoami", Name: "whoami", Tags: tags, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg1, false) c.Assert(err, checker.IsNil) reg2 := &api.AgentServiceRegistration{ ID: "whoami", Name: "whoami", Tags: tags, Port: 80, Address: s.getComposeServiceIP(c, "whoami2"), } err = s.registerService(reg2, true) c.Assert(err, checker.IsNil) // Start traefik cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/", nil) c.Assert(err, checker.IsNil) req.Host = "my.super.host" err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami1", "Hostname: whoami2")) c.Assert(err, checker.IsNil) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/rawdata", nil) c.Assert(err, checker.IsNil) err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr(s.getComposeServiceIP(c, "whoami1"), s.getComposeServiceIP(c, "whoami2"))) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami", true) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulServiceWithOneMissingLabels(c *check.C) { tempObjects := struct { ConsulAddress string DefaultRule string }{ ConsulAddress: s.consulURL, DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) // Start a container with some tags reg := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.random.value=my.super.host", }, Port: 80, Address: s.getComposeServiceIP(c, "whoami1"), } err := s.registerService(reg, false) c.Assert(err, checker.IsNil) // Start traefik cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/version", nil) c.Assert(err, checker.IsNil) req.Host = "my.super.host" // FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?) // TODO validate : run on 80 // Expected a 404 as we did not configure anything err = try.Request(req, 1500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulServiceWithHealthCheck(c *check.C) { whoamiIP := s.getComposeServiceIP(c, "whoami1") tags := []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/whoami`)", "traefik.http.routers.router1.service=service1", "traefik.http.services.service1.loadBalancer.server.url=http://" + whoamiIP, } reg1 := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: tags, Port: 80, Address: whoamiIP, Check: &api.AgentServiceCheck{ CheckID: "some-failed-check", TCP: "127.0.0.1:1234", Name: "some-failed-check", Interval: "1s", Timeout: "1s", }, } err := s.registerService(reg1, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://1192.168.3.11:8000/whoami", 2*time.Second, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) whoami2IP := s.getComposeServiceIP(c, "whoami2") reg2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami", Tags: tags, Port: 80, Address: whoami2IP, Check: &api.AgentServiceCheck{ CheckID: "some-ok-check", TCP: whoami2IP + ":80", Name: "some-ok-check", Interval: "1s", Timeout: "1s", }, } err = s.registerService(reg2, false) c.Assert(err, checker.IsNil) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) c.Assert(err, checker.IsNil) req.Host = "whoami" // FIXME Need to wait for up to 10 seconds (for consul discovery or traefik to boot up ?) err = try.Request(req, 10*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami2")) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami2", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulConnect(c *check.C) { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() c.Assert(err, checker.IsNil) connectIP := s.getComposeServiceIP(c, "connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=true", "traefik.http.routers.router1.rule=Path(`/`)", "traefik.http.routers.router1.service=service1", "traefik.http.services.service1.loadBalancer.server.url=https://" + connectIP, }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) c.Assert(err, checker.IsNil) whoamiIP := s.getComposeServiceIP(c, "whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/connect.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusOK)) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusOK)) c.Assert(err, checker.IsNil) err = s.deregisterService("uuid-api1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulConnect_ByDefault(c *check.C) { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() c.Assert(err, checker.IsNil) connectIP := s.getComposeServiceIP(c, "connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router1.rule=Path(`/`)", "traefik.http.routers.router1.service=service1", "traefik.http.services.service1.loadBalancer.server.url=https://" + connectIP, }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) c.Assert(err, checker.IsNil) whoamiIP := s.getComposeServiceIP(c, "whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami1", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) c.Assert(err, checker.IsNil) whoami2IP := s.getComposeServiceIP(c, "whoami2") regWhoami2 := &api.AgentServiceRegistration{ ID: "whoami2", Name: "whoami2", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=false", "traefik.http.routers.router2.rule=Path(`/whoami2`)", "traefik.http.routers.router2.service=whoami2", }, Port: 80, Address: whoami2IP, } err = s.registerService(regWhoami2, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/connect_by_default.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusOK)) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8000/whoami2", 10*time.Second, try.StatusCodeIs(http.StatusOK)) c.Assert(err, checker.IsNil) err = s.deregisterService("uuid-api1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami2", false) c.Assert(err, checker.IsNil) } func (s *ConsulCatalogSuite) TestConsulConnect_NotAware(c *check.C) { // Wait for consul to fully initialize connect CA err := s.waitForConnectCA() c.Assert(err, checker.IsNil) connectIP := s.getComposeServiceIP(c, "connect") reg := &api.AgentServiceRegistration{ ID: "uuid-api1", Name: "uuid-api", Tags: []string{ "traefik.enable=true", "traefik.consulcatalog.connect=true", "traefik.http.routers.router1.rule=Path(`/`)", "traefik.http.routers.router1.service=service1", "traefik.http.services.service1.loadBalancer.server.url=https://" + connectIP, }, Connect: &api.AgentServiceConnect{ Native: true, }, Port: 443, Address: connectIP, } err = s.registerService(reg, false) c.Assert(err, checker.IsNil) whoamiIP := s.getComposeServiceIP(c, "whoami1") regWhoami := &api.AgentServiceRegistration{ ID: "whoami1", Name: "whoami", Tags: []string{ "traefik.enable=true", "traefik.http.routers.router2.rule=Path(`/whoami`)", "traefik.http.routers.router2.service=whoami", }, Port: 80, Address: whoamiIP, } err = s.registerService(regWhoami, false) c.Assert(err, checker.IsNil) tempObjects := struct { ConsulAddress string }{ ConsulAddress: s.consulURL, } file := s.adaptFile(c, "fixtures/consul_catalog/connect_not_aware.toml", tempObjects) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) err = cmd.Start() c.Assert(err, checker.IsNil) defer s.killCmd(cmd) err = try.GetRequest("http://127.0.0.1:8000/", 10*time.Second, try.StatusCodeIs(http.StatusNotFound)) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8000/whoami", 10*time.Second, try.StatusCodeIs(http.StatusOK)) c.Assert(err, checker.IsNil) err = s.deregisterService("uuid-api1", false) c.Assert(err, checker.IsNil) err = s.deregisterService("whoami1", false) c.Assert(err, checker.IsNil) }
artzstudio/Boot
test/cdn/mylib/foo.min.js
<reponame>artzstudio/Boot Boot.log("Inside foo.min.js, defining <b>mylib/foo</b>, returning now."); Boot.define({ "foo": true });
zhxinyu/cosan
docs/html/class_cosan_1_1_evaluation.js
<reponame>zhxinyu/cosan var class_cosan_1_1_evaluation = [ [ "Evaluation", "class_cosan_1_1_evaluation.html#a043a5ff14b47ab96833ab24e7463edfb", null ] ];
shivam091/Java-Security
crypt/src/main/java/org/security/crypt/x509/RDNSequenceIterator.java
<reponame>shivam091/Java-Security<gh_stars>0 package org.security.crypt.x509; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import org.security.crypt.util.DERHelper; import org.security.crypt.x509.types.RelativeDistinguishedName; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERObject; /** * Iterates over an ASN.1 encoded RelativeDistinguishedName sequence in reverse * order as specified in section 2.1 of RFC 2253 for converting an ASN.1 * representation of an RDN sequence to a string. * * @author shivam * */ public class RDNSequenceIterator implements Iterator<RelativeDistinguishedName>, Iterable<RelativeDistinguishedName> { /** RDN sequence. */ private final ASN1Sequence sequence; /** Current iterator position. */ private int position; /** * Creates a new instance from the bytes comprising an encoded ASN.1 * sequence of RDN types. * * @param encodedRDNSequence * ASN.1 encoded sequence as a byte array. */ public RDNSequenceIterator(final byte[] encodedRDNSequence) { this(toASN1Sequence(encodedRDNSequence)); } /** * Creates a new instance from an ASN.1 sequence of RDNs. * * @param rdnSequence * ASN.1 sequence containing AttributeValueAndType items * representing RDNs. */ public RDNSequenceIterator(final ASN1Sequence rdnSequence) { sequence = rdnSequence; position = sequence.size() - 1; } /** {@inheritDoc} */ public boolean hasNext() { return position > -1; } /** {@inheritDoc} */ public RelativeDistinguishedName next() { if (!hasNext()) { throw new NoSuchElementException("Reached end of iterator."); } final DEREncodable enc = sequence.getObjectAt(position--); if (!(enc instanceof ASN1Set)) { throw new IllegalStateException("Next item is not an ASN.1 set."); } return RelativeDistinguishedName.fromASN1Set((ASN1Set) enc); } /** * Not supported. * * @throws UnsupportedOperationException * In all cases. */ public void remove() { throw new UnsupportedOperationException("Remove not supported."); } /** {@inheritDoc} */ public Iterator<RelativeDistinguishedName> iterator() { return this; } /** * Creates an ASN.1 sequence from the given byte array. * * @param data * Encoded bytes of an ASN.1 sequence. * * @return ASN.1 sequence object. * * @throws IllegalArgumentException * If data is not encoded bytes of an ASN.1 sequence. */ private static ASN1Sequence toASN1Sequence(final byte[] data) { DERObject obj; try { obj = DERHelper.toDERObject(data, false); } catch (IOException e) { throw new IllegalArgumentException( "Error creating ASN.1 sequence from encoded bytes.", e); } if (obj instanceof ASN1Sequence) { return (ASN1Sequence) obj; } else { throw new IllegalArgumentException( "Encoded data is not an ASN.1 sequence."); } } }
IEEE-VIT/Techloop-A-Plus
Users/goelashwin36/Task 1/app/src/main/java/com/example/ash/login/MainActivity.java
<filename>Users/goelashwin36/Task 1/app/src/main/java/com/example/ash/login/MainActivity.java<gh_stars>10-100 package com.example.ash.login; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button= findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this, LoginPageActivity.class); startActivity(intent); } }); } public void onClick(View view){ Intent intent=new Intent(MainActivity.this, LoginPageActivity.class); startActivity(intent); } }
apostolidhs/wiregoose
plugins/email/basic.module.js
'use strict'; KlarkModule(module, 'emailBasicTmpl', ( _, $passportJwt, krkModelsUser, config ) => { const {SECURE_APP_URL} = config; const logoUrl = `${SECURE_APP_URL}/public/assets/img/logo-170-nologo.png`; return { template }; function template({ styling = '', contentTitle = '', contentBody = '', ctaUrl = '', ctaTitle = '' }) { return ` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="format-detection" content="telephone=no"> <style type="text/css"> * { font-family: sans-serif; } body { width: 100% !important; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0; mso-line-height-rule: exactly; } table td { border-collapse: collapse; } table td { border-collapse: collapse; } img { outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; } a img { border: none; } a { text-decoration: blink; color: white; } @media only screen and (max-device-width: 480px) { table[id="outercontainer_div"] { max-width: 480px !important; } table[id="nzInnerTable"], table[class="nzpImageHolder"], table[class="imageGroupHolder"] { width: 100% !important; min-width: 320px !important; } table[class="nzpImageHolder"] td, td[class="table_seperator"], td[class="table_column"] { display: block !important; width: 100% !important; } table[class="nzpImageHolder"] img { /* width: 100% !important; */ } table[class="nzpButt"] { display: block !important; width: auto !important; } #nzInnerTable td, #outercontainer_div td { padding: 0px !important; margin: 0px !important; } #nzpButt td { padding: 7px !important; } } ${styling} </style> </head> <body style="padding: 0; margin: 0; -webkit-font-smoothing:antialiased; -webkit-text-size-adjust:none; background: #EEEEEE;" data-gr-c-s-loaded="true"> <table width="100%" cellpadding="30" id="outercontainer_div"> <tbody> <tr> <td align="center"> <table width="600" bgcolor="#FFFFFF" cellpadding="15" cellspacing="0" id="nzInnerTable" border="0" style="border: 1px solid #FFFFFF;"> <tbody> <tr> <td> <div id="innerContent" style="padding:10px;"> <table width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 0px;" class="nzpImageHolder"> <tbody> <tr> <td align="center"> <div style="padding: 0px;"> <a href="${SECURE_APP_URL}" target="_blank"> <img src="${logoUrl}" class="bigImg editableImg" id="img-2" width="100" border="0" alt="" title=""> </a> </div> </td> </tr> </tbody> </table> <table width="100%" cellspacing="0" cellpadding="0" style="padding: 0px; padding-top: 0px; padding-bottom: 15px;"> <tbody> <tr> <td> <table width="100%" cellpadding="0" cellspacing="0" style=""> <tbody> <tr> <td bgcolor=""> <div id="txtHolder-3" class="txtEditorClass" style="color: #000000; font-size: 26px; font-family: &#39;Impact&#39;; text-align: Left"> <div style="text-align: center;"> <a href="${SECURE_APP_URL}" style="font-size: xx-large;color: #000000;">wiregoose.com</a> </div> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table width="100%" cellspacing="0" cellpadding="0" style="padding: 0px; padding-top: 0px; padding-bottom: 25px;"> <tbody> <tr> <td> <table width="100%" cellpadding="0" cellspacing="0" style=""> <tbody> <tr> <td bgcolor=""> <div id="txtHolder-4" class="txtEditorClass" style="color: #666666; font-size: 14px; font-family: &#39;Arial&#39;; text-align: Left"> <span style="font-weight: bold; font-size: large;">${contentTitle}</span> <br> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table width="100%" cellspacing="0" cellpadding="0" style="padding: 0px; padding-top: 0px; padding-bottom: 25px;"> <tbody> <tr> <td> <table width="100%" cellpadding="0" cellspacing="0" style=""> <tbody> <tr> <td bgcolor=""> <div id="txtHolder-5" class="txtEditorClass" style="color: #666666; font-size: 14px; font-family: &#39;Arial&#39;; text-align: Left"> <span style="color: rgb(51, 51, 51); font-family: &quot;Helvetica Neue&quot;, Arial, Helvetica; font-size: 15px; background-color: rgb(255, 255, 255);">${contentBody}</span> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table width="100%" cellspacing="0" cellpadding="0" style="padding-bottom: 0px;"> <tbody> <tr> <td> <table cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr> <td bgcolor=""> <table cellpadding="10" cellspacing="0" align="Center" id="nzpButt"> <tbody> <tr> <td bgcolor="#337ab7" style=" border-radius: 3px;color: #ffffff; text-align: center; font-size: 26pxpx; font-family: &#39;Sans Serif&#39;; cursor: pointer; text-decoration: none;"> <a href="${ctaUrl}" target="_blank" style=" color: #ffffff; text-align: center; font-size: 26pxpx; font-family: &#39;Sans Serif&#39; cursor: pointer; text-decoration: none;"> <span style="font-size: 22px; color: #ffffff;font-weight: 100;">${ctaTitle}</span> </a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </body> </html> `; } });
ghidalgo3/s_mach.similar
src/test/scala/s_mach/similar/SMach_Similar_ObjectTests.scala
package s_mach.similar import org.scalatest.{FlatSpec,Matchers} import breeze.linalg.{DenseVector, DenseMatrix} import s_mach.similar.TestObjects._ import s_mach.similar.impl.SimilarOps import SimilarOps._ /** * Created by Gustavo on 1/27/15. */ class SMach_Similar_ObjectTests extends FlatSpec with Matchers { }
BusyStudent/Btk
include/Btk/async.hpp
<gh_stars>1-10 #if !defined(BTK_ASYNC_HPP_) #define BTK_ASYNC_HPP_ #include <tuple> #include <memory> #include "object.hpp" #include "defs.hpp" namespace Btk{ BTKAPI void DeferCall(void(* fn)(void*),void *data); namespace Impl{ template<bool has_signal,class RetT> struct AsyncSignal; template<class RetT> struct AsyncSignal<true,RetT>{ using type = Signal<void(RetT &)>; type signal;//< The Signals }; template<> struct AsyncSignal<true,void>{ using type = Signal<void()>; type signal; }; //Empty signal template<class RetT> struct AsyncSignal<false,RetT>{ using type = void; }; //A struct to store task value template<class RetT> struct AsyncResultHolder{ union Data{ //erase the destructor RetT data; bool data__unused; Data(){ data__unused = false; } ~Data(){} }data; void cleanup(){ if constexpr(not std::is_destructible<RetT>()){ data.data.~RetT(); } }; template<class T> void store(T &&t){ new (&data.data)T(std::forward<T>(t)); }; }; //A specialization for ref template<class RetT> struct AsyncResultHolder<RetT&>{ union Data{ //erase the destructor std::remove_reference_t<RetT> data; bool data__unused; Data(){ data__unused = false; } ~Data(){} }data; void cleanup(){}; template<class T> void store(T &&t){ data.data = &t; }; }; template<> struct AsyncResultHolder<void>{ void cleanup(){ }; }; /** * @brief The async base,It store the return value and the signal * * @tparam HasSignal The value should we enable signal * @tparam Callable * @tparam Args */ template<bool HasSignal,class Callable,class ...Args> struct AsyncBase: public AsyncSignal<HasSignal,std::invoke_result_t<Callable,Args...>>, AsyncResultHolder<std::invoke_result_t<Callable,Args...>>, std::tuple<Args...>{ public: //< The async task has signal static constexpr int has_signal = HasSignal; /** * @brief Construct a new Async Base object * * @param args The args */ AsyncBase(Args &&...args): std::tuple<Args...>(std::forward<Args>(args)...){}; }; /** * @brief A RAII class for impl Invoker * * @tparam HasSiganlArg Is The signal arg is not empty? * @tparam T The invoker type */ template<bool HasSiganlArg,class T> struct AsyncGuard; template<class T> struct AsyncGuard<true,T>{ //The invoker T *invoker; bool need_cleanup = true; bool need_delete = true; //< need We cleanup for the invoker AsyncGuard(T *i){ invoker = i; } AsyncGuard(const AsyncGuard &) = delete; ~AsyncGuard(){ if(need_cleanup){ invoker->cleanup(); } if(need_delete){ delete invoker; } } /** * @brief Relase both * */ void release(){ need_cleanup = false; need_delete = false; }; }; /** * @brief The specialization of no signal arg * * @tparam T The invoker type */ template<class T> struct AsyncGuard<false,T>{ T *invoker; bool need_delete = true; //< need We cleanup for the invoker AsyncGuard(T *i){ invoker = i; } AsyncGuard(const AsyncGuard &) = delete; ~AsyncGuard(){ if(need_delete){ delete invoker; } } void release(){ need_delete = false; }; }; template<class T> struct AsyncScopePtr{ T *invoker; AsyncScopePtr(T *ptr){ invoker = ptr; }; AsyncScopePtr(const AsyncScopePtr &) = delete; ~AsyncScopePtr(){ invoker->cleanup(); delete invoker; }; }; /** * @brief The AsyncInvoker * * @tparam Callable The callable type * @tparam Args The args types */ template<bool HasSignal,class Callable,class ...Args> struct AsyncInvoker:public AsyncBase<HasSignal,Callable,Args...>{ /** * @brief The signal * * @note It will be emit after exec */ Callable callable; //Create a invoker AsyncInvoker(Callable &&_callable,Args &&..._args): AsyncBase<HasSignal,Callable,Args...>(std::forward<Args>(_args)...), callable(std::forward<Callable>(_callable)){ }; /** * @brief The result type * */ using result_type = std::invoke_result_t<Callable,Args...>; /** * @brief Is the signal has args * */ static constexpr bool signal_has_args = not std::is_same<result_type,void>(); /** * @brief Invoke the callable * * @return The callable's result */ result_type invoke(){ return std::apply(callable, static_cast<std::tuple<Args...>&&>(*this)); } /** * @brief Run the invoker * */ void run(){ if constexpr(not HasSignal){ //It doesnnot have signal ,just Invoke it self std::unique_ptr<AsyncInvoker> ptr(this); invoke(); } else if constexpr(std::is_same<result_type,void>()){ AsyncGuard<signal_has_args,AsyncInvoker> guard(this); invoke(); if(not this->signal.empty()){ //Emit this signal on main thread DeferCall(EmitSignal,this); //relase the guard guard.release(); } } else{ AsyncGuard<signal_has_args,AsyncInvoker> guard(this); //< We didnot have the value //< So we set the flags to false guard.need_cleanup = false; this->store(invoke()); //< Ok,we store the value guard.need_cleanup = true; if(not this->signal.empty()){ //Emit this signal on main thread DeferCall(EmitSignal,this); guard.release(); } } }; /** * @brief Emit the signal impl * */ template<class T = std::enable_if<HasSignal>> void emit(){ if constexpr(std::is_same<result_type,void>()){ std::unique_ptr<AsyncInvoker> ptr(this); this->signal.emit(); } else{ //Add Guard AsyncScopePtr<AsyncInvoker> guard(this); if constexpr(std::is_reference<result_type>()){ //Is ref //So the Holder's value is a point this->signal.emit(*(this->data.data)); } else{ this->signal.emit(this->data.data); } } }; /** * @brief The main entry for invoker * * @param __self The invoker's ptr */ static void Run(void *__self){ static_cast<AsyncInvoker*>(__self)->run(); }; /** * @brief Emit Signal in main thread * * @param __self The invoker ptr */ template<class T = std::enable_if<HasSignal>> static void EmitSignal(void *__self){ static_cast<AsyncInvoker*>(__self)->emit(); }; }; /** * @brief Lauch a AsyncInvoker right now * * @param invoker the invoker pointer * @param run the invoker entry */ BTKAPI void RtLauch(void *invoker,void(*run)(void*invoker)); BTKAPI void DeferLauch(void *invoker,void(*run)(void*invoker)); }; enum class Lauch{ Async = 0, Defered = 1 }; /** * @brief A type to tell the async * don't emit the signal in main thread * */ struct _NoSignal{ }; constexpr _NoSignal NoSignal{}; /** * @brief The AsyncTask * * @tparam HasSignal If the task has signal * @tparam Callable The callable type * @tparam Args The args type */ template<bool HasSignal,class Callable,class ...Args> class AsyncTask{ public: using result_type = typename std::invoke_result_t<Callable,Args...>; using signal_type = typename Impl::AsyncSignal<HasSignal,result_type>::type; using invoker_type = typename Impl::AsyncInvoker<HasSignal,Callable,Args...>; //< The type of invoker AsyncTask(Callable &&callable,Args&& ...args){ invoker = new invoker_type( std::forward<Callable>(callable), std::forward<Args>(args)... ); }; AsyncTask(AsyncTask &&task){ invoker = task.invoker; task.invoker = nullptr; }; AsyncTask(const AsyncTask &) = delete; ~AsyncTask(){ lauch(); }; /** * @brief Lauch the asyn task * * @param lauch Lauch flag */ void lauch(Lauch lauch = Lauch::Async){ if(invoker != nullptr){ if(lauch == Lauch::Async){ Impl::RtLauch(invoker,invoker_type::Run); } else{ Impl::DeferLauch(invoker,invoker_type::Run); } invoker = nullptr; } }; /** * @brief a use full operator to connect signal * @note It only useable only it has signal * @return The signal or void*(NoSignal) */ signal_type *operator ->() const noexcept{ if constexpr(HasSignal){ return &(invoker->signal); } else{ return nullptr; } }; private: invoker_type *invoker; }; /** * @brief Create a Async Task * * @tparam T The callable type * @tparam Args The args type * @param callable The callable * @param args The args * @return AsyncTask object */ template<class T,class ...Args> AsyncTask<true,T,Args...> Async(T &&callable,Args ...args){ return AsyncTask<true,T,Args...>( std::forward<T>(callable), std::forward<Args>(args)... ); }; /** * @brief Create a Async Task(No signal) * * @tparam T The callable type * @tparam Args The args type * @param nosignal A flag of nosignal * @param callable The callable * @param args The args * @return AsyncTask object(No signal) */ template<class T,class ...Args> AsyncTask<false,T,Args...> Async(_NoSignal,T &&callable,Args ...args){ return AsyncTask<false,T,Args...>( std::forward<T>(callable), std::forward<Args>(args)... ); }; void AsyncInit(); void AsyncQuit(); }; #endif // BTK_ASYNC_HPP_
gil9red/SimplePyScripts
textwrap__examples/dedent_examples.py
<reponame>gil9red/SimplePyScripts #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from textwrap import dedent text = """\ Съешь ещё этих мягких французских булок, да выпей же чаю """ print(repr(text)) print(repr(dedent(text))) print() def foo(): """ Съешь ещё этих мягких французских булок, да выпей же чаю """ print(repr(foo.__doc__)) print(repr(dedent(foo.__doc__)))
cadovid/Pandemia2019
src/java/card/EventCard.java
<gh_stars>1-10 package card; public class EventCard extends Card { // TODO: Define possible events public EventCard() { // RAWR - Super class has neither city nor color attributes // this.city = null; // this.color = null; } }
PierrickVoulet/google-ads-java
google-ads/src/main/java/com/google/ads/googleads/v3/resources/RecommendationProto.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v3/resources/recommendation.proto package com.google.ads.googleads.v3.resources; public final class RecommendationProto { private RecommendationProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationImpact_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationImpact_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationMetrics_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationMetrics_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_CampaignBudgetRecommendationOption_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_CampaignBudgetRecommendationOption_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_TextAdRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_TextAdRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_TargetCpaOptInRecommendationOption_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_TargetCpaOptInRecommendationOption_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_CallExtensionRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_CallExtensionRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeConversionsOptInRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeConversionsOptInRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_SearchPartnersOptInRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_SearchPartnersOptInRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_EnhancedCpcOptInRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_EnhancedCpcOptInRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_SitelinkExtensionRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_SitelinkExtensionRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_MoveUnusedBudgetRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_MoveUnusedBudgetRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeClicksOptInRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeClicksOptInRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_OptimizeAdRotationRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_OptimizeAdRotationRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_CalloutExtensionRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_CalloutExtensionRecommendation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordMatchTypeRecommendation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordMatchTypeRecommendation_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n6google/ads/googleads/v3/resources/reco" + "mmendation.proto\022!google.ads.googleads.v" + "3.resources\032-google/ads/googleads/v3/com" + "mon/criteria.proto\032/google/ads/googleads" + "/v3/common/extensions.proto\0326google/ads/" + "googleads/v3/enums/keyword_match_type.pr" + "oto\0327google/ads/googleads/v3/enums/recom" + "mendation_type.proto\032Igoogle/ads/googlea" + "ds/v3/enums/target_cpa_opt_in_recommenda" + "tion_goal.proto\032*google/ads/googleads/v3" + "/resources/ad.proto\032\037google/api/field_be" + "havior.proto\032\031google/api/resource.proto\032" + "\036google/protobuf/wrappers.proto\032\034google/" + "api/annotations.proto\"\356,\n\016Recommendation" + "\022F\n\rresource_name\030\001 \001(\tB/\340A\005\372A)\n\'googlea" + "ds.googleapis.com/Recommendation\022[\n\004type" + "\030\002 \001(\0162H.google.ads.googleads.v3.enums.R" + "ecommendationTypeEnum.RecommendationType" + "B\003\340A\003\022[\n\006impact\030\003 \001(\0132F.google.ads.googl" + "eads.v3.resources.Recommendation.Recomme" + "ndationImpactB\003\340A\003\022f\n\017campaign_budget\030\005 " + "\001(\0132\034.google.protobuf.StringValueB/\340A\003\372A" + ")\n\'googleads.googleapis.com/CampaignBudg" + "et\022Y\n\010campaign\030\006 \001(\0132\034.google.protobuf.S" + "tringValueB)\340A\003\372A#\n!googleads.googleapis" + ".com/Campaign\022X\n\010ad_group\030\007 \001(\0132\034.google" + ".protobuf.StringValueB(\340A\003\372A\"\n googleads" + ".googleapis.com/AdGroup\0222\n\tdismissed\030\r \001" + "(\0132\032.google.protobuf.BoolValueB\003\340A\003\022}\n\036c" + "ampaign_budget_recommendation\030\004 \001(\0132N.go" + "ogle.ads.googleads.v3.resources.Recommen" + "dation.CampaignBudgetRecommendationB\003\340A\003" + "H\000\022n\n\026keyword_recommendation\030\010 \001(\0132G.goo" + "gle.ads.googleads.v3.resources.Recommend" + "ation.KeywordRecommendationB\003\340A\003H\000\022m\n\026te" + "xt_ad_recommendation\030\t \001(\0132F.google.ads." + "googleads.v3.resources.Recommendation.Te" + "xtAdRecommendationB\003\340A\003H\000\022\177\n target_cpa_" + "opt_in_recommendation\030\n \001(\0132N.google.ads" + ".googleads.v3.resources.Recommendation.T" + "argetCpaOptInRecommendationB\003\340A\003H\000\022\223\001\n*m" + "aximize_conversions_opt_in_recommendatio" + "n\030\013 \001(\0132X.google.ads.googleads.v3.resour" + "ces.Recommendation.MaximizeConversionsOp" + "tInRecommendationB\003\340A\003H\000\022\203\001\n\"enhanced_cp" + "c_opt_in_recommendation\030\014 \001(\0132P.google.a" + "ds.googleads.v3.resources.Recommendation" + ".EnhancedCpcOptInRecommendationB\003\340A\003H\000\022\211" + "\001\n%search_partners_opt_in_recommendation" + "\030\016 \001(\0132S.google.ads.googleads.v3.resourc" + "es.Recommendation.SearchPartnersOptInRec" + "ommendationB\003\340A\003H\000\022\211\001\n%maximize_clicks_o" + "pt_in_recommendation\030\017 \001(\0132S.google.ads." + "googleads.v3.resources.Recommendation.Ma" + "ximizeClicksOptInRecommendationB\003\340A\003H\000\022\206" + "\001\n#optimize_ad_rotation_recommendation\030\020" + " \001(\0132R.google.ads.googleads.v3.resources" + ".Recommendation.OptimizeAdRotationRecomm" + "endationB\003\340A\003H\000\022\201\001\n callout_extension_re" + "commendation\030\021 \001(\0132P.google.ads.googlead" + "s.v3.resources.Recommendation.CalloutExt" + "ensionRecommendationB\003\340A\003H\000\022\203\001\n!sitelink" + "_extension_recommendation\030\022 \001(\0132Q.google" + ".ads.googleads.v3.resources.Recommendati" + "on.SitelinkExtensionRecommendationB\003\340A\003H" + "\000\022{\n\035call_extension_recommendation\030\023 \001(\013" + "2M.google.ads.googleads.v3.resources.Rec" + "ommendation.CallExtensionRecommendationB" + "\003\340A\003H\000\022\202\001\n!keyword_match_type_recommenda" + "tion\030\024 \001(\0132P.google.ads.googleads.v3.res" + "ources.Recommendation.KeywordMatchTypeRe" + "commendationB\003\340A\003H\000\022\202\001\n!move_unused_budg" + "et_recommendation\030\025 \001(\0132P.google.ads.goo" + "gleads.v3.resources.Recommendation.MoveU" + "nusedBudgetRecommendationB\003\340A\003H\000\032\343\001\n\024Rec" + "ommendationImpact\022b\n\014base_metrics\030\001 \001(\0132" + "G.google.ads.googleads.v3.resources.Reco" + "mmendation.RecommendationMetricsB\003\340A\003\022g\n" + "\021potential_metrics\030\002 \001(\0132G.google.ads.go" + "ogleads.v3.resources.Recommendation.Reco" + "mmendationMetricsB\003\340A\003\032\251\002\n\025Recommendatio" + "nMetrics\0226\n\013impressions\030\001 \001(\0132\034.google.p" + "rotobuf.DoubleValueB\003\340A\003\0221\n\006clicks\030\002 \001(\013" + "2\034.google.protobuf.DoubleValueB\003\340A\003\0225\n\013c" + "ost_micros\030\003 \001(\0132\033.google.protobuf.Int64" + "ValueB\003\340A\003\0226\n\013conversions\030\004 \001(\0132\034.google" + ".protobuf.DoubleValueB\003\340A\003\0226\n\013video_view" + "s\030\005 \001(\0132\034.google.protobuf.DoubleValueB\003\340" + "A\003\032\207\004\n\034CampaignBudgetRecommendation\022F\n\034c" + "urrent_budget_amount_micros\030\001 \001(\0132\033.goog" + "le.protobuf.Int64ValueB\003\340A\003\022J\n recommend" + "ed_budget_amount_micros\030\002 \001(\0132\033.google.p" + "rotobuf.Int64ValueB\003\340A\003\022\216\001\n\016budget_optio" + "ns\030\003 \003(\0132q.google.ads.googleads.v3.resou" + "rces.Recommendation.CampaignBudgetRecomm" + "endation.CampaignBudgetRecommendationOpt" + "ionB\003\340A\003\032\301\001\n\"CampaignBudgetRecommendatio" + "nOption\022>\n\024budget_amount_micros\030\001 \001(\0132\033." + "google.protobuf.Int64ValueB\003\340A\003\022[\n\006impac" + "t\030\002 \001(\0132F.google.ads.googleads.v3.resour" + "ces.Recommendation.RecommendationImpactB" + "\003\340A\003\032\240\001\n\025KeywordRecommendation\022A\n\007keywor" + "d\030\001 \001(\0132+.google.ads.googleads.v3.common" + ".KeywordInfoB\003\340A\003\022D\n\032recommended_cpc_bid" + "_micros\030\002 \001(\0132\033.google.protobuf.Int64Val" + "ueB\003\340A\003\032\304\001\n\024TextAdRecommendation\0226\n\002ad\030\001" + " \001(\0132%.google.ads.googleads.v3.resources" + ".AdB\003\340A\003\0228\n\rcreation_date\030\002 \001(\0132\034.google" + ".protobuf.StringValueB\003\340A\003\022:\n\017auto_apply" + "_date\030\003 \001(\0132\034.google.protobuf.StringValu" + "eB\003\340A\003\032\375\004\n\034TargetCpaOptInRecommendation\022" + "\207\001\n\007options\030\001 \003(\0132q.google.ads.googleads" + ".v3.resources.Recommendation.TargetCpaOp" + "tInRecommendation.TargetCpaOptInRecommen" + "dationOptionB\003\340A\003\022G\n\035recommended_target_" + "cpa_micros\030\002 \001(\0132\033.google.protobuf.Int64" + "ValueB\003\340A\003\032\211\003\n\"TargetCpaOptInRecommendat" + "ionOption\022w\n\004goal\030\001 \001(\0162d.google.ads.goo" + "gleads.v3.enums.TargetCpaOptInRecommenda" + "tionGoalEnum.TargetCpaOptInRecommendatio" + "nGoalB\003\340A\003\022;\n\021target_cpa_micros\030\002 \001(\0132\033." + "google.protobuf.Int64ValueB\003\340A\003\022P\n&requi" + "red_campaign_budget_amount_micros\030\003 \001(\0132" + "\033.google.protobuf.Int64ValueB\003\340A\003\022[\n\006imp" + "act\030\004 \001(\0132F.google.ads.googleads.v3.reso" + "urces.Recommendation.RecommendationImpac" + "tB\003\340A\003\032p\n\033CallExtensionRecommendation\022Q\n" + "\026recommended_extensions\030\001 \003(\0132,.google.a" + "ds.googleads.v3.common.CallFeedItemB\003\340A\003" + "\032t\n&MaximizeConversionsOptInRecommendati" + "on\022J\n recommended_budget_amount_micros\030\001" + " \001(\0132\033.google.protobuf.Int64ValueB\003\340A\003\032#" + "\n!SearchPartnersOptInRecommendation\032 \n\036E" + "nhancedCpcOptInRecommendation\032x\n\037Sitelin" + "kExtensionRecommendation\022U\n\026recommended_" + "extensions\030\001 \003(\01320.google.ads.googleads." + "v3.common.SitelinkFeedItemB\003\340A\003\032\327\001\n\036Move" + "UnusedBudgetRecommendation\022A\n\026excess_cam" + "paign_budget\030\001 \001(\0132\034.google.protobuf.Str" + "ingValueB\003\340A\003\022r\n\025budget_recommendation\030\002" + " \001(\0132N.google.ads.googleads.v3.resources" + ".Recommendation.CampaignBudgetRecommenda" + "tionB\003\340A\003\032o\n!MaximizeClicksOptInRecommen" + "dation\022J\n recommended_budget_amount_micr" + "os\030\001 \001(\0132\033.google.protobuf.Int64ValueB\003\340" + "A\003\032\"\n OptimizeAdRotationRecommendation\032v" + "\n\036CalloutExtensionRecommendation\022T\n\026reco" + "mmended_extensions\030\001 \003(\0132/.google.ads.go" + "ogleads.v3.common.CalloutFeedItemB\003\340A\003\032\316" + "\001\n\036KeywordMatchTypeRecommendation\022A\n\007key" + "word\030\001 \001(\0132+.google.ads.googleads.v3.com" + "mon.KeywordInfoB\003\340A\003\022i\n\026recommended_matc" + "h_type\030\002 \001(\0162D.google.ads.googleads.v3.e" + "nums.KeywordMatchTypeEnum.KeywordMatchTy" + "peB\003\340A\003:c\352A`\n\'googleads.googleapis.com/R" + "ecommendation\0225customers/{customer}/reco" + "mmendations/{recommendation}B\020\n\016recommen" + "dationB\200\002\n%com.google.ads.googleads.v3.r" + "esourcesB\023RecommendationProtoP\001ZJgoogle." + "golang.org/genproto/googleapis/ads/googl" + "eads/v3/resources;resources\242\002\003GAA\252\002!Goog" + "le.Ads.GoogleAds.V3.Resources\312\002!Google\\A" + "ds\\GoogleAds\\V3\\Resources\352\002%Google::Ads:" + ":GoogleAds::V3::Resourcesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v3.common.CriteriaProto.getDescriptor(), com.google.ads.googleads.v3.common.ExtensionsProto.getDescriptor(), com.google.ads.googleads.v3.enums.KeywordMatchTypeProto.getDescriptor(), com.google.ads.googleads.v3.enums.RecommendationTypeProto.getDescriptor(), com.google.ads.googleads.v3.enums.TargetCpaOptInRecommendationGoalProto.getDescriptor(), com.google.ads.googleads.v3.resources.AdProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.protobuf.WrappersProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v3_resources_Recommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor, new java.lang.String[] { "ResourceName", "Type", "Impact", "CampaignBudget", "Campaign", "AdGroup", "Dismissed", "CampaignBudgetRecommendation", "KeywordRecommendation", "TextAdRecommendation", "TargetCpaOptInRecommendation", "MaximizeConversionsOptInRecommendation", "EnhancedCpcOptInRecommendation", "SearchPartnersOptInRecommendation", "MaximizeClicksOptInRecommendation", "OptimizeAdRotationRecommendation", "CalloutExtensionRecommendation", "SitelinkExtensionRecommendation", "CallExtensionRecommendation", "KeywordMatchTypeRecommendation", "MoveUnusedBudgetRecommendation", "Recommendation", }); internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationImpact_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationImpact_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationImpact_descriptor, new java.lang.String[] { "BaseMetrics", "PotentialMetrics", }); internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationMetrics_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(1); internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationMetrics_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_RecommendationMetrics_descriptor, new java.lang.String[] { "Impressions", "Clicks", "CostMicros", "Conversions", "VideoViews", }); internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(2); internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_descriptor, new java.lang.String[] { "CurrentBudgetAmountMicros", "RecommendedBudgetAmountMicros", "BudgetOptions", }); internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_CampaignBudgetRecommendationOption_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_CampaignBudgetRecommendationOption_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_CampaignBudgetRecommendation_CampaignBudgetRecommendationOption_descriptor, new java.lang.String[] { "BudgetAmountMicros", "Impact", }); internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(3); internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordRecommendation_descriptor, new java.lang.String[] { "Keyword", "RecommendedCpcBidMicros", }); internal_static_google_ads_googleads_v3_resources_Recommendation_TextAdRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(4); internal_static_google_ads_googleads_v3_resources_Recommendation_TextAdRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_TextAdRecommendation_descriptor, new java.lang.String[] { "Ad", "CreationDate", "AutoApplyDate", }); internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(5); internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_descriptor, new java.lang.String[] { "Options", "RecommendedTargetCpaMicros", }); internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_TargetCpaOptInRecommendationOption_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_TargetCpaOptInRecommendationOption_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_TargetCpaOptInRecommendation_TargetCpaOptInRecommendationOption_descriptor, new java.lang.String[] { "Goal", "TargetCpaMicros", "RequiredCampaignBudgetAmountMicros", "Impact", }); internal_static_google_ads_googleads_v3_resources_Recommendation_CallExtensionRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(6); internal_static_google_ads_googleads_v3_resources_Recommendation_CallExtensionRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_CallExtensionRecommendation_descriptor, new java.lang.String[] { "RecommendedExtensions", }); internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeConversionsOptInRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(7); internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeConversionsOptInRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeConversionsOptInRecommendation_descriptor, new java.lang.String[] { "RecommendedBudgetAmountMicros", }); internal_static_google_ads_googleads_v3_resources_Recommendation_SearchPartnersOptInRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(8); internal_static_google_ads_googleads_v3_resources_Recommendation_SearchPartnersOptInRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_SearchPartnersOptInRecommendation_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v3_resources_Recommendation_EnhancedCpcOptInRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(9); internal_static_google_ads_googleads_v3_resources_Recommendation_EnhancedCpcOptInRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_EnhancedCpcOptInRecommendation_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v3_resources_Recommendation_SitelinkExtensionRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(10); internal_static_google_ads_googleads_v3_resources_Recommendation_SitelinkExtensionRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_SitelinkExtensionRecommendation_descriptor, new java.lang.String[] { "RecommendedExtensions", }); internal_static_google_ads_googleads_v3_resources_Recommendation_MoveUnusedBudgetRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(11); internal_static_google_ads_googleads_v3_resources_Recommendation_MoveUnusedBudgetRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_MoveUnusedBudgetRecommendation_descriptor, new java.lang.String[] { "ExcessCampaignBudget", "BudgetRecommendation", }); internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeClicksOptInRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(12); internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeClicksOptInRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_MaximizeClicksOptInRecommendation_descriptor, new java.lang.String[] { "RecommendedBudgetAmountMicros", }); internal_static_google_ads_googleads_v3_resources_Recommendation_OptimizeAdRotationRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(13); internal_static_google_ads_googleads_v3_resources_Recommendation_OptimizeAdRotationRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_OptimizeAdRotationRecommendation_descriptor, new java.lang.String[] { }); internal_static_google_ads_googleads_v3_resources_Recommendation_CalloutExtensionRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(14); internal_static_google_ads_googleads_v3_resources_Recommendation_CalloutExtensionRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_CalloutExtensionRecommendation_descriptor, new java.lang.String[] { "RecommendedExtensions", }); internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordMatchTypeRecommendation_descriptor = internal_static_google_ads_googleads_v3_resources_Recommendation_descriptor.getNestedTypes().get(15); internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordMatchTypeRecommendation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v3_resources_Recommendation_KeywordMatchTypeRecommendation_descriptor, new java.lang.String[] { "Keyword", "RecommendedMatchType", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.ads.googleads.v3.common.CriteriaProto.getDescriptor(); com.google.ads.googleads.v3.common.ExtensionsProto.getDescriptor(); com.google.ads.googleads.v3.enums.KeywordMatchTypeProto.getDescriptor(); com.google.ads.googleads.v3.enums.RecommendationTypeProto.getDescriptor(); com.google.ads.googleads.v3.enums.TargetCpaOptInRecommendationGoalProto.getDescriptor(); com.google.ads.googleads.v3.resources.AdProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.protobuf.WrappersProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
vsch/idea-markdown
src/main/java/com/vladsch/md/nav/flex/highlighter/FlexmarkColorSettingsExtension.java
<gh_stars>100-1000 // Copyright (c) 2017-2020 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.highlighter; import com.vladsch.md.nav.flex.PluginBundle; import com.vladsch.md.nav.flex.settings.FlexmarkDebugSettings; import com.vladsch.md.nav.highlighter.MdHighlighterColors; import com.vladsch.md.nav.highlighter.api.MdColorSettingsExtension; import com.vladsch.md.nav.settings.MdApplicationSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlexmarkColorSettingsExtension implements MdColorSettingsExtension { @Nullable @Override public String getDemoText() { return null; } @Override public void addTextAttributes(@NotNull MdColorSettings colorSettings) { if (MdApplicationSettings.getInstance().getDebugSettings().getExtension(FlexmarkDebugSettings.KEY).getEnableFlexmarkFeatures()) { MdHighlighterColors highlighterColors = MdHighlighterColors.getInstance(); colorSettings.addTextAttributesKey(PluginBundle.message("colors.debug.format-text-block"), highlighterColors.DEBUG_FORMAT_TEXT_BLOCK_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.debug.format-prefix"), highlighterColors.DEBUG_FORMAT_PREFIX_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.debug.flexmark-ast"), highlighterColors.DEBUG_FLEXMARK_AST_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.debug.flexmark-source"), highlighterColors.DEBUG_FLEXMARK_SOURCE_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-marker"), highlighterColors.FLEXMARK_MARKER_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-section"), highlighterColors.FLEXMARK_EXAMPLE_SECTION_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-section-markers"), highlighterColors.FLEXMARK_EXAMPLE_SECTION_MARKER_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-number"), highlighterColors.FLEXMARK_EXAMPLE_NUMBER_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-options-keyword"), highlighterColors.FLEXMARK_EXAMPLE_OPTIONS_KEYWORD_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-keyword"), highlighterColors.FLEXMARK_EXAMPLE_EXAMPLE_KEYWORD_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-options-marker"), highlighterColors.FLEXMARK_EXAMPLE_OPTIONS_MARKER_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-param"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_PARAM_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-param-marker"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_PARAM_MARKER_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-built-in"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_BUILT_IN_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-ignore"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_IGNORE_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-fail"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_FAIL_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-option-disabled"), highlighterColors.FLEXMARK_EXAMPLE_OPTION_DISABLED_NAME_ATTR_KEY); colorSettings.addTextAttributesKey(PluginBundle.message("colors.flexmark-example-separator"), highlighterColors.FLEXMARK_EXAMPLE_SEPARATOR_ATTR_KEY); } } }
workflowfm/pew
pew/src/main/scala/com/workflowfm/pew/PiState.scala
package com.workflowfm.pew import scala.annotation.tailrec /** * This is the pi-calculus state of a running workflow. * * We separate inputs from outputs to make searching for matching channels more efficient. * We could have everything in one list like PiLib does. * * @param inputs a map of Input type continuations based on their primary channels * @param outputs a map of Output type continuations based on their primary channels * @param calls a list of processes that have been called but the inputs haven't arrived yet * @param threads a map of processes that have been called and whose results we want. The * calls to the actual processes should happen outside the PiState by a * process executor, so that things are kept clean and independent here. Each * call has a unique reference number so that results don't clash. * @param threadCtr an integer to help create unique reference numbers for threads * @param freshCtr an integer to help create unique (fresh) channel names * @param processes a map of available processes, both atomic and composite, so that we know * how to handle calls when they occur * @param resources a ChanMap of unhandled resources. We try to keep this as clean as possible, * so that it only contains resources that need to be received by a pending call * (though this is not guaranteed, we might get some leftover garbage in here as well). */ case class PiState( inputs: Map[Chan, Input], outputs: Map[Chan, Output], calls: List[PiFuture], threads: Map[Int, PiFuture], threadCtr: Int, freshCtr: Int, processes: Map[String, PiProcess], resources: ChanMap ) { /** * Introducing a term can have many different effects on the state. * e.g. an Input term is simply added to the inputs, but a PiCut term adds new terms to both * inputs and outputs and it affects freshCtr. * We also want to leave enough room for any future types of terms we might want to add. * We therefore defer the state effect to be determined by the Term itself. */ def withTerm(t: Term): PiState = { //System.err.println("*** Handling term: " + t) t.addTo(this) } def withTerms(t: Seq[Term]): PiState = (this /: t)(_ withTerm _) def withSub(c: Chan, a: PiObject): PiState = copy(resources = resources + (c, a)) def withSubs(m: Map[Chan, PiObject]): PiState = copy(resources = resources ++ m) def withSubs(l: Seq[(Chan, PiObject)]): PiState = copy(resources = resources ++ l) def withSubs(m: ChanMap): PiState = copy(resources = resources ++ m) def withProc(p: PiProcess): PiState = copy(processes = processes + (p.name -> p)) def withProcs(l: PiProcess*): PiState = (this /: l)(_ withProc _) def updateProcs(m: Map[String, PiProcess]): PiState = copy(processes = m) def updateProcs(f: PiProcess => PiProcess): PiState = copy(processes = processes.mapValues(f)) def withCalls(l: PiFuture*): PiState = copy(calls = l.toList ++ calls) def withThread(ref: Int, name: String, chan: Chan, args: Seq[PiResource]): PiState = withThreads( (ref, PiFuture(name, chan, args)) ) def withThreads(t: (Int, PiFuture)*): PiState = copy(threads = threads ++ (t map { x => x._1 -> x._2 })) def removeThread(ref: Int): PiState = copy(threads = threads - ref) def removeThreads(refs: Iterable[Int]): PiState = copy(threads = threads -- refs) def withTCtr(i: Int): PiState = copy(threadCtr = i) def incTCtr(): PiState = copy(threadCtr = threadCtr + 1) def withFCtr(i: Int): PiState = copy(freshCtr = i) def incFCtr(i: Int = 1): PiState = copy(freshCtr = freshCtr + i) private def removeIO(c: Chan): PiState = copy(inputs = inputs - c, outputs = outputs - c) /** * Performs either a single pi-calculus reduction or else handles the first available call with completed inputs. * The intersection of key sets detects common channels between inputs and outputs, which can then communicate. */ def reduce(): Option[PiState] = communicateFirst( inputs.keySet intersect outputs.keySet toList ) match { case Some(s) => Some(s) case None => executeFirst() } /** * Perform all possible reductions to the state. */ @tailrec final def fullReduce(): PiState = reduce() match { case None => this case Some(s) => { //System.err.println(s) s.fullReduce() } } /** * Performs the first possible communication from a list of common channels. */ @tailrec private def communicateFirst(l: List[Chan]): Option[PiState] = l match { case Nil => None case h :: t => communicate(h) match { case None => communicateFirst(t) case s => s } } /** * Attempts to perform a communication through channel k. * First uses the send method of the output to obtain the outputValue. * Then checks if the corresponding input can receive the outputValue. * It then uses the receive method of the input to pass the outputValue. * Finally it updates the state with continuations from both the input and output, * adds unhandled channel mappings to resources, and removes the input and output * from their respective maps. */ private def communicate(k: Chan) = { val (oterms, outputValue, newstate) = outputs.get(k).get.send(this) inputs.get(k) flatMap { i => if (!i.admits(outputValue)) None else { //System.err.println("*** Communicating [" + outputValue + "] through channel: " + k) val (iterms, newres) = inputs.get(k).get.receive(outputValue) Some(newstate withTerms oterms withTerms iterms withSubs newres removeIO k) } } } /** * Handles process calls. * For atomic process calls, we create an instantiated PiFuture and add it to the calls. * We also generate and add the process input terms. * For composite process calls we instantiate the body and add it as a term. */ def handleCall(c: PiCall): PiState = processes get c.name match { case None => { System.err.println("Failed to find process: " + c.name) this } case Some(p: MetadataAtomicProcess) => { //System.err.println("*** Handling atomic call: " + c.name) val m = p.mapFreshArgs(freshCtr + 1, c.args: _*) copy(calls = p.getFuture(freshCtr + 1, m) +: calls) withTerms p.getInputs( freshCtr + 1, m ) incFCtr () } case Some(p: CompositeProcess) => { //System.err.println("*** Handling composite call: " + c.name) val m = p.mapFreshArgs(freshCtr + 1, c.args: _*) this withTerm p.body.fresh(freshCtr + 1).sub(m) incFCtr () } } /** * By 'execute' we mean converting a call to a thread. * This means checking a process in the calls list about whether its inputs have arrived. * This executes the first process (if any) in calls whose inputs have arrived. */ def executeFirst(): Option[PiState] = { def executeFirstRec(l: List[PiFuture]): Option[(PiState, List[PiFuture])] = l match { case Nil => None case h :: t => execute(h) match { case None => executeFirstRec(t) match { case None => None case Some((s, r)) => Some((s, h :: r)) } case Some(s) => Some((s, t)) } } executeFirstRec(calls) match { case None => None case Some((s, l)) => Some(s.copy(calls = l)) } } /** * This converts a PiFuture in the calls list to an instatiated thread to be executed externally. * A unique thread id is generated using threadCtr. * We also remove the mappings of all free channels in the process inputs from the resources list. * These get used up in the process execution and are no longer needed. This helps keep the resources list clean. */ def execute(p: PiFuture): Option[PiState] = { //val frees = (processes get p.fun toSeq) flatMap (_.inputFrees()) val frees = p.args map (_.obj.frees) p.execute(resources) map { fut => copy( threads = threads + (threadCtr -> fut), threadCtr = threadCtr + 1, resources = resources -- (frees.flatten: _*) ) } } /** * This method should be used by the external executor to report the result of an executed thread and obtain the appropriate new state. * The PiFuture is removed from the threads list and its output Term is added, with the given object as the output resource. */ def result(ref: Int, res: PiObject): Option[PiState] = threads get ref map { fut => copy(threads = threads - ref) withTerm fut.toOutput(res) } /** * Executes a thread handling function over all threads. * Handler is expected to have side-effects (typically some Future trigger). * Handler should return true if a thread was handled successfully, false if it failed. * Returns the updated state containing only threads that were handled successfully. */ def handleThreads(handler: ((Int, PiFuture)) => Boolean): PiState = copy(threads = threads filter handler) } object PiState { def apply(t: Term*): PiState = PiState( Map(): Map[Chan, Input], Map(): Map[Chan, Output], List(), Map(): Map[Int, PiFuture], 0, 0, Map(): Map[String, PiProcess], ChanMap() ) withTerms t def apply(t: Seq[Term], l: Seq[(Chan, PiObject)]): PiState = PiState(t: _*) withSubs l } trait PiStateTester { def reduceOnce(t: ChannelTerm*): Option[PiState] = PiState(t: _*).reduce() def reduce(t: ChannelTerm*): PiState = reduceState(PiState(t: _*)) def reduceState(s: PiState): PiState = s.fullReduce() def reduceGet(r: String, t: ChannelTerm*): PiObject = reduceState(PiState(t: _*)).resources.obtain(Chan(r)) def fState(l: (Chan, PiObject)*): PiState = PiState(List(), l) }
5nefarious/icarous
Modules/ACCoRD/inc/PolycarpContain.h
/* * PolycarpContain - containment for 2D polygons * * Contact: <NAME> (<EMAIL>), <NAME> (<EMAIL>) * * Copyright (c) 2015-2017 United States Government as represented by * the National Aeronautics and Space Administration. No copyright * is claimed in the United States under Title 17, U.S.Code. All Other * Rights Reserved. */ #ifndef POLYCARPCONTAIN_H_ #define POLYCARPCONTAIN_H_ #include "Vect2.h" #include <vector> namespace larcfm { class PolycarpContain { public: class NumEdgesCross { public: int num; bool invalid; NumEdgesCross(int n, bool i) { num = n; invalid = i; } }; static bool near_any_edge(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static NumEdgesCross number_upshot_crosses(const std::vector<Vect2>& p,const Vect2& s); static int quadrant(const Vect2& s); static int winding_number(const std::vector<Vect2>& p,const Vect2& s); static std::vector<Vect2> fix_polygon(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static bool definitely_inside_prelim(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static bool definitely_inside(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static bool definitely_outside_prelim(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static bool definitely_outside(const std::vector<Vect2>& p,const Vect2& s,double BUFF); static bool nice_polygon_2D(const std::vector<Vect2>& p,double BUFF); }; } #endif
mzhg/PostProcessingWork
assimp/src/main/java/assimp/importer/xfile/XMaterial.java
package assimp.importer.xfile; import java.util.ArrayList; import java.util.List; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; /** Helper structure representing a XFile material */ public class XMaterial { String mName; boolean mIsReference; // if true, mName holds a name by which the actual material can be found in the material list final Vector4f mDiffuse = new Vector4f(); float mSpecularExponent; final Vector3f mSpecular = new Vector3f(); final Vector3f mEmissive = new Vector3f(); final List<XTexEntry> mTextures = new ArrayList<XTexEntry>(); int sceneIndex = -1; ///< the index under which it was stored in the scene's material list @Override public String toString() { return "XMaterial [mName=" + mName + ", mIsReference=" + mIsReference + ", mDiffuse=" + mDiffuse + ", mSpecularExponent=" + mSpecularExponent + ", mSpecular=" + mSpecular + ", mEmissive=" + mEmissive + ", mTextures=" + mTextures + ", sceneIndex=" + sceneIndex + "]"; } }
noecl1/multihammer
src/Controller/VentasController.java
package Controller; import Model.ComboBoxClass; import Model.Dialogs; import Model.Venta; import Model.VentasModel; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXTextField; import com.jfoenix.controls.JFXTreeTableColumn; import com.jfoenix.controls.JFXTreeTableView; import com.jfoenix.controls.RecursiveTreeItem; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import java.io.IOException; import java.net.URL; import java.text.DecimalFormat; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TableRow; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableRow; import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.util.StringConverter; import Reportes.PrintReport; import java.sql.SQLException; import net.sf.jasperreports.engine.JRException; public class VentasController implements Initializable { // Instanciaciòn/Declaraciòn de variables private final VentasModel modelo = new VentasModel(); final private Dialogs dialogs = new Dialogs(); ObservableList<Venta> productos = FXCollections.observableArrayList(); // Declaraciòn de componentes @FXML private JFXButton btnAgregar; @FXML private JFXButton btnCotizar; @FXML private JFXButton btnVenta; @FXML private JFXButton btnAgregarCliente; @FXML private JFXComboBox<ComboBoxClass> txtMaterial; @FXML private JFXComboBox<ComboBoxClass> txtUnidad; @FXML private JFXComboBox<ComboBoxClass> txtCliente; @FXML private JFXTextField txtCantidad; @FXML private JFXTreeTableView table; @FXML private Label labelTotal; @Override public void initialize(URL url, ResourceBundle rb) { // Crea la tabla createTable(); // Valida que la cantidad solo pueda recibir digitos. txtCantidad.textProperty().addListener((observable, oldValue, newValue) -> { if (!newValue.matches("\\d*")) { txtCantidad.setText(newValue.replaceAll("[^\\d]", "")); } }); // Que solo se despliegue el nombre txtMaterial.setConverter(new StringConverter<ComboBoxClass>() { @Override public String toString(ComboBoxClass object) { return object.getNombre(); } @Override public ComboBoxClass fromString(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // Que solo se despliegue el nombre txtMaterial.valueProperty().addListener((obs, oldval, newval) -> { if(newval != null) setUnidades(txtMaterial.getSelectionModel().getSelectedItem().getId()); }); txtUnidad.setConverter(new StringConverter<ComboBoxClass>() { @Override public String toString(ComboBoxClass object) { return object.getNombre(); } @Override public ComboBoxClass fromString(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // Que solo se despliegue el nombre txtCliente.setConverter(new StringConverter<ComboBoxClass>() { @Override public String toString(ComboBoxClass object) { return object.getNombre(); } @Override public ComboBoxClass fromString(String string) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // Asigna los valores al ComboBox de clientes setClientes(); // Asigna los valores al ComboBox de materiales setMateriales(); } // Crea la tabla public void createTable() { // Evento de doble click que despliega un mensaje para dar de baja lògica a la fila seleccionada table.setRowFactory( tv -> { TreeTableRow<Venta> row = new TreeTableRow<>(); row.setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (! row.isEmpty()) ) { Venta rowData = row.getItem(); if(dialogs.displayMessage((Stage) btnAgregar.getScene().getWindow(), "Eliminar producto", "¿Deseas eliminar este producto de la lista de venta?", "Si", "No")) { for(int x = 0; x < productos.size(); x++) { if(productos.get(x).getId_producto().equals(rowData.getId_producto())) { productos.remove(x); setTotal(); break; } } } } }); return row ; }); // Estructura de la tabla JFXTreeTableColumn<Venta, String> material = new JFXTreeTableColumn("Material"); material.setPrefWidth(250); material.setCellValueFactory((TreeTableColumn.CellDataFeatures<Venta, String> param) -> param.getValue().getValue().material); JFXTreeTableColumn<Venta, String> unidad = new JFXTreeTableColumn("Unidad"); unidad.setPrefWidth(200); unidad.setCellValueFactory((TreeTableColumn.CellDataFeatures<Venta, String> param) -> param.getValue().getValue().unidad); JFXTreeTableColumn<Venta, String> cantidad = new JFXTreeTableColumn("Cantidad"); cantidad.setPrefWidth(200); cantidad.setCellValueFactory((TreeTableColumn.CellDataFeatures<Venta, String> param) -> param.getValue().getValue().cantidad); JFXTreeTableColumn<Venta, String> precio = new JFXTreeTableColumn("Precio"); precio.setPrefWidth(200); precio.setCellValueFactory((TreeTableColumn.CellDataFeatures<Venta, String> param) -> param.getValue().getValue().precio); JFXTreeTableColumn<Venta, String> total = new JFXTreeTableColumn("Total"); total.setPrefWidth(300); total.setCellValueFactory((TreeTableColumn.CellDataFeatures<Venta, String> param) -> param.getValue().getValue().total); table.getColumns().setAll(material, unidad, cantidad, precio, total); } // Asigna los datos public void createTableView() { TreeItem<Venta> root = new RecursiveTreeItem<>(productos, RecursiveTreeObject::getChildren); table.setRoot(root); table.setShowRoot(false); } // Asigna los datos a Clientes public void setClientes() { txtCliente.setItems(modelo.getClientes()); } // Asigna los datos a Materiales public void setMateriales() { txtMaterial.setItems(modelo.getMateriales()); } // Asigna los datos a Unidades, dandole las unidades asignadas al material seleccionado public void setUnidades(String id_material) { txtUnidad.setItems(modelo.getUnidades(id_material)); txtUnidad.setDisable(false); } // Rellena el label de total con el total de los productos seleccionados public void setTotal() { float total = 0; for (Venta producto : productos) { total += Float.parseFloat(producto.getTotal().get()); } // Da formato al total DecimalFormat decFor = new DecimalFormat("########.##"); labelTotal.setText(String.valueOf(decFor.format(total))); } // Funciòn agregar @FXML private void btnAgregarAction() { // Valida que todos los campos tengan un valor if(!txtCantidad.getText().equals("") && !txtMaterial.getSelectionModel().isEmpty() && !txtUnidad.getSelectionModel().isEmpty()) { // Declaraciòn de variables Venta product = new Venta(); boolean existencia = false; int x; // Formato para solo dos decimales DecimalFormat decFor = new DecimalFormat("########.##"); // Agrega los valores del material a la variable auxiliar float precio = modelo.getPrecio(txtUnidad.getSelectionModel().getSelectedItem().getId()); product.setId_producto(txtUnidad.getSelectionModel().getSelectedItem().getId()); product.setMaterial(txtMaterial.getSelectionModel().getSelectedItem().getNombre()); product.setUnidad(txtUnidad.getSelectionModel().getSelectedItem().getNombre()); product.setPrecio(String.valueOf(precio)); product.setCantidad(txtCantidad.getText()); // Calcula el total: precio * cantidad product.setTotal(String.valueOf(decFor.format(precio * Integer.parseInt(txtCantidad.getText())))); // Ciclo for para revisar si ya se encuentra registrado el producto, si ya se encuentra, se suma la cantidad y se recalcula el total for(x = 0; x < productos.size(); x++) { if(productos.get(x).getId_producto().equals(txtUnidad.getSelectionModel().getSelectedItem().getId())) { product.setCantidad(String.valueOf(Integer.parseInt(txtCantidad.getText()) + Integer.parseInt(productos.get(x).getCantidad().get()))); product.setTotal(String.valueOf(decFor.format(precio * Integer.parseInt(product.getCantidad().get())))); existencia = true; break; } } // Si ya existìa el producto en la tabla de ventas, se modifica su ìndice if(existencia) { productos.set(x, product); } else { // Sino, se agrega el producto productos.add(product); } // Se vuelven a mostar los valores en la tabla createTableView(); // Se reinician los componentes para agregar setMateriales(); txtUnidad.getSelectionModel().clearSelection(); txtUnidad.setDisable(true); txtCantidad.setText(""); setTotal(); } else { dialogs.displayMessage((Stage) btnAgregar.getScene().getWindow(), "Advertencia", "Es necesario que los campos Material, Unidad y Cantidad se encuentren llenos", "Ok"); } } // Funciòn para hacer la venta @FXML private void btnVentaAction() { // Valida que se tenga agregado mìnimo 1 producto y 1 cliente if(productos.size() > 0 && !txtCliente.getSelectionModel().isEmpty()) { // Confirmaciòn de que se realize la venta if(dialogs.displayMessage((Stage) btnAgregar.getScene().getWindow(), "Registrar venta", "¿Estás seguro que quieres concluir esta venta?", "Si", "No")) { // Se registra la venta modelo.registrarVenta(productos, txtCliente.getSelectionModel().getSelectedItem().getId(), labelTotal.getText()); // Se limpia la vista productos.clear(); createTableView(); setClientes(); labelTotal.setText(""); } } else { dialogs.displayMessage((Stage) btnAgregar.getScene().getWindow(), "Advertencia", "Es necesario ingresar por lo menos un producto para realizar una venta y seleccionar un cliente", "Ok"); } } // Funciòn para cotizar @FXML private void btnCotizarAction() throws JRException, ClassNotFoundException, IOException { if(productos.size() > 0 && !txtCliente.getSelectionModel().isEmpty()) { if(dialogs.displayMessage((Stage) btnAgregar.getScene().getWindow(), "Cotización", "¿Estás seguro de que quieres generar una cotización?", "Si", "No")) { modelo.registrarCotizacion(productos, txtCliente.getSelectionModel().getSelectedItem().getId(), labelTotal.getText()); productos.clear(); createTableView(); setClientes(); labelTotal.setText(""); } } } // Funciòn para agregar cliente @FXML private void btnAgregarClienteAction(ActionEvent event) throws IOException { // Prepara el modal para agregar un cliente Stage stage = new Stage(); FXMLLoader modal = new FXMLLoader(getClass().getResource("/View/ClientesModal.fxml")); Parent root = modal.load(); root.getStylesheets().add("/Resources/main.css"); stage.setScene(new Scene(root)); stage.initStyle(StageStyle.TRANSPARENT); stage.getScene().setFill(Color.TRANSPARENT); stage.setTitle("Agregar Clientes"); stage.initModality(Modality.WINDOW_MODAL); stage.initOwner(((Node)event.getSource()).getScene().getWindow() ); stage.showAndWait(); setClientes(); } }
Zomzog/data-quality
dataquality-sampling/src/main/java/org/talend/dataquality/datamasking/generic/fields/FieldEnum.java
// ============================================================================ // // Copyright (C) 2006-2016 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataquality.datamasking.generic.fields; import java.math.BigInteger; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.talend.dataquality.sampling.exception.DQRuntimeException; /** * @author jteuladedenantes * * A FieldEnum is a list of specific values. We defined a FieldEnum by an exhaustive list of all possible values. */ public class FieldEnum extends AbstractField { private static final long serialVersionUID = 4434958606928963578L; private static final Logger LOGGER = LoggerFactory.getLogger(FieldEnum.class); /** * The exhaustive list of values */ private List<String> enumValues; public FieldEnum(List<String> enumValues) { int maxLen = 0; for (String value : enumValues) { int valueCPCount = value.codePointCount(0, value.length()); if (valueCPCount > maxLen) { maxLen = valueCPCount; } } initialize(enumValues, maxLen); } public FieldEnum(List<String> enumValues, int length) { initialize(enumValues, length); } private void initialize(List<String> enumValues, int length) { this.length = length; for (String value : enumValues) { int valueCPCount = value.codePointCount(0, value.length()); if (valueCPCount != this.length) { LOGGER.error("The field <" + value + "> with a length = " + valueCPCount + " should have a length = " + length); throw new DQRuntimeException( "The value <" + value + "> with a length = " + valueCPCount + " should have a length = " + length); } } this.enumValues = enumValues; } @Override public BigInteger getWidth() { return BigInteger.valueOf(enumValues.size()); } @Override public BigInteger encode(String str) { return BigInteger.valueOf(enumValues.indexOf(str)); } @Override public String decode(BigInteger number) { if (number.compareTo(getWidth()) >= 0) return ""; return enumValues.get(number.intValue()); } }
NB4444/BachelorProjectEnergyManager
Library/Source/EnergyManager/Testing/Tests/ActiveInactiveWorkloadTest.hpp
#pragma once #include "EnergyManager/Testing/Tests/WorkloadTest.hpp" #include <string> namespace EnergyManager { namespace Testing { namespace Tests { /** * Tests the ActiveInactiveWorkload. */ class ActiveInactiveWorkloadTest : public WorkloadTest { public: /** * Creates a new ActiveInactiveWorkloadTest from command line arguments. * @param arguments The command line arguments. */ ActiveInactiveWorkloadTest(const std::map<std::string, std::string>& arguments); }; } } }
haxpor/APIBook
12_Extensibility/visitor/scenegraph.cpp
/// -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- /// /// \file scenegraph.cpp /// \author <NAME> /// \brief Simple scenegraph API with different node types. /// /// Copyright (c) 2010, <NAME>. All rights reserved. /// Distributed under the X11/MIT License. See LICENSE.txt. /// See http://APIBook.com/ for the latest version. /// #include "scenegraph.h" #include "nodevisitor.h" #include <vector> BaseNode::BaseNode(const std::string &name) : mName(name) { } ShapeNode::ShapeNode(const std::string &name) : BaseNode(name) { } void ShapeNode::Accept(INodeVisitor &visitor) { visitor.Visit(*this); } TransformNode::TransformNode(const std::string &name) : BaseNode(name) { } void TransformNode::Accept(INodeVisitor &visitor) { visitor.Visit(*this); } LightNode::LightNode(const std::string &name) : BaseNode(name) { } void LightNode::Accept(INodeVisitor &visitor) { visitor.Visit(*this); } int ShapeNode::GetPolygonCount() const { // return a different polygon count each time static int called = 1; return 100 * ++called; } class SceneGraph::Impl { public: Impl() { mNodes.push_back(new LightNode("Light0")); mNodes.push_back(new TransformNode("Translate")); mNodes.push_back(new ShapeNode("Shape0")); mNodes.push_back(new TransformNode("Scale")); mNodes.push_back(new ShapeNode("Shape1")); } std::vector<BaseNode *> mNodes; }; SceneGraph::SceneGraph() { mImpl = new Impl; } SceneGraph::~SceneGraph() { delete mImpl; } void SceneGraph::Traverse(INodeVisitor &visitor) { std::vector<BaseNode *>::iterator it; for (it = mImpl->mNodes.begin(); it != mImpl->mNodes.end(); ++it) { BaseNode *node = *it; node->Accept(visitor); } }
juanca/backbone.marionette.native
specs/helpers.js
beforeEach(function(){ this.element = document.createElement('div'); this.element.classList.add('test-element'); document.body.appendChild(this.element); jasmine.addMatchers({ toHaveClass: function(util, customMatchers){ return { compare: function(actual, expected) { return { pass: actual.classList.contains(expected) }; } }; }, toHaveText: function(util, customMatchers){ return { compare: function(actual, expected) { return { pass: actual.textContent.trim() === expected }; } }; }, toBeInstanceOf: function(util, customMatchers){ return { compare: function(actual, expected) { return { pass: actual instanceof expected }; } }; } }); /** * Helper for triggering mouse events. */ this.createAndFireEvent = function(element, type){ var evt; if (type === 'popstate' || type === 'hashchange'){ evt = document.createEvent('HTMLEvents'); evt.initEvent( type, false, // bubbles false // cancelable ); } else { evt = document.createEvent('MouseEvent'); evt.initMouseEvent( type, true, // bubbles true, // cancelable window, 0, // detail 0, // screenX 0, // screenY 0, // pageX 0, // pageY false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 0, // button (type === 'mouseover' || type === 'mouseout') ? document : null ); } spyOn(evt, 'preventDefault').and.callThrough(); spyOn(evt, 'stopPropagation').and.callThrough(); element.dispatchEvent(evt); return evt; }; }); afterEach(function(){ document.body.removeChild(this.element); });
nickman/kafject
metric-hub/src/main/java/com/heliosapm/streams/metrichub/tsdbplugin/JSONMetricsAPIService.java
<gh_stars>0 /** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.heliosapm.streams.metrichub.tsdbplugin; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.heliosapm.streams.metrichub.MetricsMetaAPI; import com.heliosapm.streams.metrichub.QueryContext; import com.heliosapm.streams.metrichub.tsdbplugin.json.Netty3JSONRequest; import com.heliosapm.streams.metrichub.tsdbplugin.json.Netty3JSONResponse; import com.heliosapm.webrpc.annotations.JSONRequestHandler; import com.heliosapm.webrpc.annotations.JSONRequestService; import com.heliosapm.webrpc.jsonservice.ResponseType; import net.opentsdb.meta.TSMeta; import net.opentsdb.uid.UniqueId.UniqueIdType; import net.opentsdb.utils.JSON; import reactor.core.composable.Stream; import reactor.function.Consumer; /** * <p>Title: JSONMetricsAPIService</p> * <p>Description: JSON service to implement remoting for the Metric API over HTTP and WebSockets</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.streams.metrichub.tsdbplugin.JSONMetricsAPIService</code></p> */ @JSONRequestService(name="meta", description="JSON service to implement remoting for the Metric API over HTTP and WebSockets") public class JSONMetricsAPIService { /** The Metric Meta API impl used to serve this JSON service */ protected final MetricsMetaAPI metricApi; /** Instance logger */ protected final Logger log = LogManager.getLogger(getClass()); /** The ctx name for this class */ protected final String ctxName = getClass().getSimpleName(); /** The ctx name for the accept time */ protected final String ctxAcceptName = getClass().getSimpleName() + "Accepted"; /** * Creates a new JSONMetricsAPIService * @param metricApi The Metric Meta API impl used to serve this JSON service */ public JSONMetricsAPIService(final MetricsMetaAPI metricApi) { this.metricApi = metricApi; } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getMetricNames(net.opentsdb.meta.api.QueryContext, java.lang.String[])} * @param request The JSON request * @param q The query context * @param tags The TSMeta tags to match the metric names for * <p>Sample request:<pre> { "t": "req", "rid": 1, "svc": "meta", "op": "metricswtags", "q": { "pageSize": 10 }, "tags": { "host": "*", "type": "combined" } } * </pre></p> */ @JSONRequestHandler(name="metricswtags", description="Returns the MetricNames that match the passed tag pairs") public void getMetricNamesWithTagsJSON(final Netty3JSONRequest request, final QueryContext q, final Map<String, String> tags) { if(q==null) { getMetricNamesWithTagsJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), getMap(request, "tags") ); } else { log.info("Processing JSONMetricNames. q: [{}], tags: {}", q, tags); attachBatchHandlers(metricApi.getMetricNames(q, tags), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getMetricNames(net.opentsdb.meta.api.QueryContext, java.lang.String[])} * @param request The JSON request * @param q The query context * @param tagKeys an array of tag keys to exclude * <p>Sample request:<pre> * * </pre></p> * FIXME: merge metric name functions */ @JSONRequestHandler(name="metricnames", description="Returns the MetricNames that match the passed tag keys") public void getMetricNamesJSON(final Netty3JSONRequest request, final QueryContext q, final String...tagKeys) { if(q==null) { getMetricNamesJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), getStringArray(request, "keys") ); } else { log.info("Processing JSONMetricNames. q: [{}], keys: {}", q, Arrays.toString(tagKeys)); attachBatchHandlers(metricApi.getMetricNames(q.startExpiry(), tagKeys), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagKeys(QueryContext, String, String...)} * @param request The JSON request * @param q The query context * @param metricName The optional TSMeta metric name to match * @param tagKeys The tag keys to match * <p>Sample request:<pre> { "t": "req", "rid": 4, "svc": "meta", "op": "tagkeys", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "DEFAULT", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "keys": [ "dc", "host" ], "m": "sys*" } * </pre></p> */ @JSONRequestHandler(name="tagkeys", description="Returns the Tag Key UIDs that match the passed metric name and tag keys") public void getTagKeysJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final String...tagKeys) { if(q==null) { getTagKeysJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), request.getRequest().get("m").textValue(), getStringArray(request, "keys") ); } else { log.info("Processing JSONTagKeys. q: [{}], m: [{}], keys: {}", q, metricName, Arrays.toString(tagKeys)); attachBatchHandlers(metricApi.getTagKeys(q.startExpiry(), metricName, tagKeys), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)} * @param request The JSON request * @param q The query context * @param metricName The optional TSMeta metric name to match * @param tags The TSMeta tags to match * @param tagKey The value of the tag key to get values for * <p>Sample request:<pre> { "t": "req", "rid": 12, "svc": "meta", "op": "tagvalues", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "DEFAULT", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "tags": { "host": "*Server*", "cpu": "*" }, "m": "sys.cpu", "k": "type" } * </pre></p> */ @JSONRequestHandler(name="tagvalues", description="Returns the Tag Value UIDs that match the passed metric name and tag keys") public void getTagValuesJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final Map<String, String> tags, final String tagKey) { if(q==null) { getTagValuesJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), request.getRequest().get("m").textValue(), getMap(request, "tags"), request.getRequest().get("k").textValue() ); } else { log.info("Processing JSONTagValues. q: [{}], m: [{}], tags: {}", q, metricName, tags); attachBatchHandlers(metricApi.getTagValues(q.startExpiry(), metricName, tags, tagKey), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)} * @param request The JSON request * @param q The query context * @param expression The TSMeta fully qualified metric name pattern to match. An expression is basically an {@link javax.management.ObjectName} analog where * the {@link javax.management.ObjectName#getDomain()} value is the metric name and the {@link javax.management.ObjectName#getKeyPropertyList()} * map represents the tags. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys. * <p>Sample request:<pre> { "t": "req", "rid": 13, "svc": "meta", "op": "tsMetaEval", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "DEFAULT", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "x": "sys*:dc=dc*,host=WebServer1|WebServer5" } * </pre></p> */ @JSONRequestHandler(name="tsMetaEval", description="Returns the TSMetas that match the passed expression") public void evaluateJSON(final Netty3JSONRequest request, final QueryContext q, final String expression) { if(q==null) { evaluateJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), request.getRequest().get("x").textValue() ); } else { log.debug("Processing JSONTSMetaExpression. \n\tQueryContext: [{}], \n\tExpression: [{}]", q, expression); attachBatchHandlers(metricApi.evaluate(q, expression), q, request); } } @JSONRequestHandler(name="overlap", description="Determines how may items are common between the two passed expressions") public void overlap(final Netty3JSONRequest request, final QueryContext q, final String expressionOne, final String expressionTwo) { if(q==null) { overlap( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class), request.getRequest().get("x").textValue(), request.getRequest().get("y").textValue() ); } else { final long result = metricApi.overlap(expressionOne, expressionTwo); request.response(ResponseType.RESP).setContent(JSON.getMapper().createObjectNode().putPOJO("q", q).put("result", result)).send(); } } /** * Attaches the consume and error handlers to the passed stream * @param stream The stream to attach handlers to * @param q The query context * @param request The Netty3JSONRequest */ protected final <T> void attachBatchHandlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) { stream.consume(new Consumer<T>(){ @Override public void accept(T t) { try { final Netty3JSONResponse response; if(q.shouldContinue()) { response = request.response(ResponseType.MRESP); } else { response = request.response(ResponseType.XMRESP); } response.setOpCode("results"); JsonGenerator jgen = response.writeHeader(true); jgen.setCodec(q.getMapper()); jgen.writeObjectField("results", t); q.addCtx(ctxAcceptName, System.currentTimeMillis()); jgen.writeObjectField("q", q); response.closeGenerator(); } catch (Exception ex) { log.error("Failed to write result batch", ex); throw new RuntimeException("Failed to write result batch", ex); } } }) .when(Throwable.class, new Consumer<Throwable>(){ @Override public void accept(Throwable t) { q.setExhausted(true); final Netty3JSONResponse response = request.response(ResponseType.ERR); try { response.resetChannelOutputStream(); response.setOpCode("error"); final JsonGenerator jgen = response.writeHeader(true); String message = t.getMessage(); if(message==null || message.trim().isEmpty()) { message = t.getClass().getSimpleName(); } jgen.writeObjectField("error", message); jgen.writeObjectField("q", q); response.closeGenerator(); log.warn("Exception message dispatched"); } catch (Exception ex) { throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex); } } }); // .timeout(q.getTimeout()); } /** * Attaches the D3 serialization consumee and error handlers to the passed stream * @param stream The stream to attach handlers to * @param q The query context * @param request The Netty3JSONRequest */ protected final <T> void attachD3Handlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) { stream.consume(new Consumer<T>(){ final LinkedHashSet<TSMeta> set = new LinkedHashSet<TSMeta>(q.getNextMaxLimit()); @SuppressWarnings("unchecked") @Override public void accept(T t) { try { set.addAll((Collection<TSMeta>) t); final Netty3JSONResponse response; if(q.shouldContinue()) { response = request.response(ResponseType.MRESP); } else { response = request.response(ResponseType.XMRESP); } response.setOpCode("results"); JsonGenerator jgen = response.writeHeader(true); jgen.setCodec(q.getMapper()); jgen.writeObjectField("results", set); q.addCtx(ctxAcceptName, System.currentTimeMillis()); jgen.writeObjectField("q", q); response.closeGenerator(); } catch (Exception ex) { log.error("Failed to write result batch", ex); throw new RuntimeException("Failed to write result batch", ex); } } }) .when(Throwable.class, new Consumer<Throwable>(){ @Override public void accept(Throwable t) { q.setExhausted(true); final Netty3JSONResponse response = request.response(ResponseType.ERR); try { response.resetChannelOutputStream(); response.setOpCode("error"); final JsonGenerator jgen = response.writeHeader(true); String message = t.getMessage(); if(message==null || message.trim().isEmpty()) { message = t.getClass().getSimpleName(); } jgen.writeObjectField("error", message); jgen.writeObjectField("q", q); response.closeGenerator(); log.warn("Exception message dispatched"); } catch (Exception ex) { throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex); } } }); // .timeout(q.getTimeout()); } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)} * returning <a href="http://d3js.org"></a> friendly formatted JSON. * @param request The JSON request * @param q The query context * @param expression The TSMeta fully qualified metric name pattern to match. An expression is basically an {@link javax.management.ObjectName} analog where * the {@link javax.management.ObjectName#getDomain()} value is the metric name and the {@link javax.management.ObjectName#getKeyPropertyList()} * map represents the tags. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys. * <p>Sample request:<pre> { "t": "req", "rid": 14, "svc": "meta", "op": "tsMetaEval", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "D3", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "x": "sys*:dc=dc*,host=WebServer1|WebServer5" } * </pre></p> */ @JSONRequestHandler(name="d3tsmeta", description="Returns the d3 json graph for the TSMetas that match the passed expression") public void evaluateD3JSON(final Netty3JSONRequest request, final QueryContext q, final String expression) { if(q==null) { evaluateD3JSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class), request.getRequest().get("x").textValue() ); } else { attachD3Handlers(metricApi.evaluate(q, expression), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTSMetas(net.opentsdb.meta.api.QueryContext, java.lang.String, java.util.Map)} * @param request The JSON request * @param q The query context * @param metricName The TSMeta metric name * @param tags The TSMeta metric tags * <p>Sample request:<pre> { "t": "req", "rid": 1, "svc": "meta", "op": "tsmetas", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "DEFAULT", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "m" : "sys*", "tags": {"dc" : "dc*", "host" : "WebServer1|WebServer5"} } * </pre></p> */ @JSONRequestHandler(name="tsmetas", description="Returns the MetricNames that match the passed tag pairs") public void getTSMetasJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final Map<String, String> tags) { if(q==null) { getTSMetasJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), request.getRequest().get("m").textValue(), getMap(request, "tags") ); } else { // request.response().setOverrideObjectMapper(TSDBTypeSerializer.valueOf(q.getFormat()).getMapper()); // metricApi.getTSMetas(q, metricName, tags).consume(new ResultConsumer<List<TSMeta>>(request, q)); attachBatchHandlers(metricApi.getTSMetas(q, metricName, tags), q, request); } } /** * HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#find(QueryContext, UniqueIdType, String)} * @param request The JSON request * @param q The query context * @param type The UID type as enumerated in {@link UniqueIdType} * @param name The UID name pattern to match. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys. * <p>Sample request:<pre> { "t": "req", "rid": 5, "svc": "meta", "op": "finduid", "q": { "nextIndex": null, "pageSize": 100, "maxSize": 2000, "timeout": 500, "continuous": false, "format": "DEFAULT", "exhausted": false, "cummulative": 0, "elapsed": -1, "expired": false }, "name": "sys*", "type": "METRIC" } * </pre></p> */ @JSONRequestHandler(name="finduid", description="Returns all UIDMetas of the specified type that match the passed name") public void findJSON(final Netty3JSONRequest request, final QueryContext q, final UniqueIdType type, final String name) { if(q==null) { findJSON( request, JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), UniqueIdType.valueOf(request.getRequest().get("type").textValue().trim().toUpperCase()), request.getRequest().get("name").textValue() ); } else { attachBatchHandlers(metricApi.find(q.startExpiry(), type, name), q, request); } } // /** // * @param request // * @param q // * @param expression // * @param range // */ // @JSONRequestHandler(name="annotations", description="Returns all Annotations associated to TSMetas defined in the expression") // public void jsonGetAnnotations(final Netty3JSONRequest request, final QueryContext q, final String expression, final long... range) { // if(q==null) { // jsonGetAnnotations( // request, // JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()), // request.getRequest().has("x") ? request.getRequest().get("x").asText() : null, // getLongArray(request, "r") // ); // } else { // request.response().setOverrideObjectMapper(TSDBTypeSerializer.valueOf(q.getFormat()).getMapper()); // final Deferred<Set<Annotation>> def; // if(expression==null) { // def = metricApi.getGlobalAnnotations(q, range); // } else { // def = metricApi.getAnnotations(q, expression, range); // } //// def.addCallback(new ResultCompleteCallback<Set<Annotation>>(request, q)) //// .addCallback(new Callback<Void, QueryContext>() { //// @Override //// public Void call(QueryContext ctx) throws Exception { //// if(ctx.shouldContinue()) { //// jsonGetAnnotations(request, ctx, expression, range); //// } //// return null; //// } //// }); // } // } /** * Extracts the named string array from the Netty3JSONRequest * @param request the Netty3JSONRequest to get the array from * @param key the json name of the array * @return the read string array */ public static String[] getStringArray(final Netty3JSONRequest request, final String key) { final ArrayNode arrayNode = (ArrayNode)request.getRequest().get(key); final String[] arr = new String[arrayNode.size()]; for(int i = 0; i < arrayNode.size(); i++) { arr[i] = arrayNode.get(i).asText(); } return arr; } /** * Extracts the named long array from the Netty3JSONRequest * @param request the Netty3JSONRequest to get the array from * @param key the json name of the array * @return the read long array */ public static long[] getLongArray(final Netty3JSONRequest request, final String key) { final ArrayNode arrayNode = (ArrayNode)request.getRequest().get(key); final long[] arr = new long[arrayNode.size()]; for(int i = 0; i < arrayNode.size(); i++) { arr[i] = arrayNode.get(i).asLong(); } return arr; } /** * Extracts the named map from the Netty3JSONRequest * @param request the Netty3JSONRequest to get the map from * @param key the json name of the map * @return the read map */ public static Map<String, String> getMap(final Netty3JSONRequest request, final String key) { ObjectNode tagNode = (ObjectNode)request.getRequest().get(key); final Map<String, String> map = new LinkedHashMap<String, String>(); Iterator<String> titer = tagNode.fieldNames(); while(titer.hasNext()) { String k = titer.next(); map.put(k, tagNode.get(k).asText()); } return map; } } /* protected final <T> void attachHandlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) { stream.consume(new Consumer<T>(){ boolean firstRow = true; Netty3JSONResponse response = request.response(); JsonGenerator jgen = null; final AtomicLong msgId = new AtomicLong(); @Override public synchronized void accept(T t) { try { if(t==null) { if(firstRow) { // empty results jgen.writeObjectField("results", Collections.emptyList()); } else { jgen.writeEndArray(); } jgen.writeObjectField("q", q); jgen.writeNumberField("msgid", msgId.incrementAndGet()); response = response.closeGenerator(); firstRow = true; return; } if(firstRow) { jgen = response.writeHeader(true); response.setOpCode("results"); jgen.setCodec(q.getMapper()); jgen.writeFieldName("results"); jgen.writeStartArray(); firstRow = false; } jgen.writeObject(t); } catch (Exception ex) { log.error("Failed to write result instance. FR: {}, t: {}, jg: {}", firstRow, t, jgen, ex); throw new RuntimeException("Failed to write result instance", ex); } } }) .when(Throwable.class, new Consumer<Throwable>(){ @Override public void accept(Throwable t) { q.setExhausted(true); final Netty3JSONResponse response = request.response(); try { response.resetChannelOutputStream(); response.setOpCode("error"); @SuppressWarnings("resource") final JsonGenerator jgen = response.writeHeader(true); String message = t.getMessage(); if(message==null || message.trim().isEmpty()) { message = t.getClass().getSimpleName(); } jgen.writeObjectField("error", message); jgen.writeObjectField("q", q); response.closeGenerator(); log.warn("Exception message dispatched"); } catch (Exception ex) { throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex); } } }); // .timeout(q.getTimeout()); } */
eltociear/material-ui
packages/material-ui-icons/lib/InvertColorsOffRounded.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20.49 20.49 3.51 3.51a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l3.5 3.5c-1 1.31-1.6 2.94-1.6 4.7C4 17.48 7.58 21 12 21c1.75 0 3.36-.56 4.67-1.5l2.4 2.4c.39.39 1.02.39 1.41 0 .4-.39.4-1.02.01-1.41zM12 19c-3.31 0-6-2.63-6-5.87 0-1.19.36-2.32 1.02-3.28L12 14.83V19zM8.38 5.56l2.91-2.87c.39-.38 1.01-.38 1.4 0l4.95 4.87C19.1 8.99 20 10.96 20 13.13c0 1.18-.27 2.29-.74 3.3L12 9.17V4.81L9.8 6.97 8.38 5.56z" }), 'InvertColorsOffRounded'); exports.default = _default;
NCIEVS/nci-meme5
model/src/main/java/com/wci/umls/server/model/content/ConceptSubsetMember.java
/** * Copyright 2016 West Coast Informatics, LLC */ /************************************************************* * SubsetMember: SubsetMember.java * Last Updated: Feb 27, 2009 *************************************************************/ package com.wci.umls.server.model.content; /** * Represents membership of an {@link Concept} in a {@link Subset}. */ public interface ConceptSubsetMember extends SubsetMember<Concept, ConceptSubset> { // n/a }
BReduardokramer/gaia
apps/system/test/unit/homescreen_window_test.js
'use strict'; mocha.globals(['SettingsListener', 'removeEventListener', 'addEventListener', 'dispatchEvent', 'WindowManager', 'Applications', 'ManifestHelper', 'HomescreenWindow', 'KeyboardManager', 'StatusBar', 'SoftwareButtonManager', 'AttentionScreen']); requireApp('system/js/browser_config_helper.js'); requireApp('system/js/browser_frame.js'); requireApp('system/js/window.js'); requireApp('system/test/unit/mock_statusbar.js'); requireApp('system/test/unit/mock_software_button_manager.js'); requireApp('system/test/unit/mock_keyboard_manager.js'); requireApp('system/test/unit/mock_manifest_helper.js'); requireApp('system/test/unit/mock_window_manager.js'); requireApp('system/test/unit/mock_applications.js'); requireApp('system/test/unit/mock_attention_screen.js'); function switchProperty(originObject, prop, stub, reals, useDefineProperty) { if (!useDefineProperty) { reals[prop] = originObject[prop]; originObject[prop] = stub; } else { Object.defineProperty(originObject, prop, { configurable: true, get: function() { return stub; } }); } } function restoreProperty(originObject, prop, reals, useDefineProperty) { if (!useDefineProperty) { originObject[prop] = reals[prop]; } else { Object.defineProperty(originObject, prop, { configurable: true, get: function() { return reals[prop]; } }); } } suite('system/HomescreenWindow', function() { var reals = {}; var homescreenWindow; var clock, stubById; setup(function(done) { switchProperty(window, 'WindowManager', MockWindowManager, reals); switchProperty(window, 'Applications', MockApplications, reals); switchProperty(window, 'ManifestHelper', MockManifestHelper, reals); switchProperty(window, 'KeyboardManager', MockKeyboardManager, reals); switchProperty(window, 'StatusBar', MockStatusBar, reals); switchProperty(window, 'SoftwareButtonManager', MockSoftwareButtonManager, reals); switchProperty(window, 'AttentionScreen', MockAttentionScreen, reals); clock = sinon.useFakeTimers(); stubById = this.sinon.stub(document, 'getElementById'); stubById.returns(document.createElement('div')); requireApp('system/js/homescreen_window.js', done); }); teardown(function() { MockWindowManager.mTeardown(); MockApplications.mTeardown(); MockKeyboardManager.mTeardown(); MockStatusBar.mTeardown(); MockSoftwareButtonManager.mTeardown(); MockAttentionScreen.mTeardown(); clock.restore(); stubById.restore(); restoreProperty(window, 'AttentionScreen', reals); restoreProperty(window, 'SoftwareButtonManager', reals); restoreProperty(window, 'StatusBar', reals); restoreProperty(window, 'KeyboardManager', reals); restoreProperty(window, 'WindowManager', reals); restoreProperty(window, 'Applications', reals); restoreProperty(window, 'ManifestHelper', reals); }); suite('homescreen window instance.', function() { setup(function() { MockApplications.mRegisterMockApp({ manifestURL: 'fakeManifestURL', origin: 'fakeOrigin', manifest: { } }); homescreenWindow = new HomescreenWindow('fakeManifestURL'); if (!'setVisible' in homescreenWindow.browser.element) { homescreenWindow.browser.element.setVisible = function() {}; } }); teardown(function() { }); test('Homescreen browser frame', function() { assert.equal(homescreenWindow.browser.element.name, 'main'); assert.equal( homescreenWindow.browser.element.getAttribute('mozapptype'), 'homescreen'); }); test('homescree is created', function() { assert.isTrue(homescreenWindow.isHomescreen); }); suite('transition test', function() { setup(function() {}); teardown(function() {}); test('close', function() { homescreenWindow._transitionState = 'opened'; homescreenWindow.close(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isFalse( homescreenWindow.element.classList.contains('active')); }); test('open', function() { homescreenWindow._transitionState = 'closed'; homescreenWindow.open(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isTrue( homescreenWindow.element.classList.contains('active')); }); test('open twice', function() { homescreenWindow._transitionState = 'closed'; homescreenWindow.open(); homescreenWindow.open(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isTrue( homescreenWindow.element.classList.contains('active')); }); test('close twice', function() { homescreenWindow._transitionState = 'opened'; homescreenWindow.close(); homescreenWindow.close(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isFalse( homescreenWindow.element.classList.contains('active')); }); test('open than close', function() { homescreenWindow._transitionState = 'closed'; homescreenWindow.open(); homescreenWindow.close(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isTrue( homescreenWindow.element.classList.contains('active')); }); test('close than open', function() { homescreenWindow._transitionState = 'opened'; homescreenWindow.close(); homescreenWindow.open(); clock.tick(homescreenWindow._transitionTimeout * 1.3); assert.isTrue( homescreenWindow.element.classList.contains('active')); }); }); suite('homescreen is crashed', function() { var stubRender; var stubKill; setup(function() { stubRender = this.sinon.stub(homescreenWindow, 'render'); stubKill = this.sinon.stub(homescreenWindow, 'kill'); }); teardown(function() { stubRender.restore(); stubKill.restore(); }); test('Homescreen is crashed at foreground:' + 'rerender right away.', function() { homescreenWindow._visibilityState = 'foreground'; homescreenWindow.restart(); assert.isTrue(stubKill.called); clock.tick(1); assert.isTrue(stubRender.called); }); test('Homescreen is crashed at background: killed', function() { homescreenWindow._visibilityState = 'background'; homescreenWindow.restart(); assert.isTrue(stubKill.called); }); }); }); });
jeremy-frank/advent-of-code
2020/day13/day13ab.py
<reponame>jeremy-frank/advent-of-code<filename>2020/day13/day13ab.py """ day13ab - https://adventofcode.com/2020/day/13 --- Day 13: Shuttle Search --- * Part 1 The first line is your estimate of the earliest timestamp you could depart on a bus. The second line lists the bus IDs that are in service according to the shuttle company; Entries that show x must be out of service, so you decide to ignore them. To save time once you arrive, your goal is to figure out the earliest bus you can take to the airport. What is the ID of the earliest bus you can take to the airport multiplied by the number of minutes you'll need to wait for that bus? 222 * Part 2 The first line in your input is no longer relevant. 7,13,x,x,59,x,31,19 An x in the schedule means there are no constraints on what bus IDs must depart at that time. This means you are looking for the earliest timestamp (called t) such that: - Bus ID 7 departs at timestamp t. - Bus ID 13 departs one minute after timestamp t. - There are no requirements or restrictions on departures at two or three minutes after timestamp t. - Bus ID 59 departs four minutes after timestamp t. - There are no requirements or restrictions on departures at five minutes after timestamp t. - Bus ID 31 departs six minutes after timestamp t. - Bus ID 19 departs seven minutes after timestamp t. The only bus departures that matter are the listed bus IDs at their specific offsets from t. Those bus IDs can depart at other times, and other bus IDs can depart at those times. Example: 1068781 Here are some other examples: The earliest timestamp that matches the list 17,x,13,19 is 3417. 67,7,59,61 first occurs at timestamp 754018. 67,x,7,59,61 first occurs at timestamp 779210. 67,7,x,59,61 first occurs at timestamp 1261476. 1789,37,47,1889 first occurs at timestamp 1202161486. What is the earliest timestamp such that all of the listed bus IDs depart at offsets matching their positions in the list? 408270049879073 """ def load_data(): data = [] datafile = 'input-day13' with open(datafile, 'r') as input: for line in input: data.append(line.strip()) timestamp = int(data[0]) buses = [] for bus in data[1].split(","): if bus == "x": buses.append(1) else: buses.append(int(bus)) return timestamp, buses def part1(timestamp, buses): # arbitrary large number time_diff = 1000000 for bus in buses: if bus != 1: previous_bus = timestamp % bus new_time_diff = bus - previous_bus if new_time_diff < time_diff: time_diff = new_time_diff best_bus = bus print(f"best_bus is {best_bus} and the time_diff is {time_diff}") return best_bus * time_diff def part2(buses): """ See https://en.wikipedia.org/wiki/Chinese_remainder_theorem Think about it like prime numbers: - The first number that is divisible by both 5 and 7 is 35 (5*7) - The first number that is divisible by 5, 7, and 13 is 455 (5*7*13) Note that 455 is also divisible by 5*7, 5*13, and 7*13 - Therefore, as soon as we find a timestamp that is evenly divisible by the current bus, we can multiply timejump by the bus and keep moving forward in bigger increments. """ timestamp = 0 timejump = 1 for i, bus in enumerate(buses): # keep increasing timestamp until modulus is zero while (timestamp+i) % bus: timestamp += timejump timejump *= bus print(f"timejump is {timejump}") return timestamp if __name__ == '__main__': timestamp, buses = load_data() print(f"Timestamp: {timestamp}") print(f"Buses: {buses}\n") results1 = part1(timestamp, buses) results2 = part2(buses) print(f"Part 1 - {results1}") print(f"Part 2 - {results2}")