repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
rgolangh/cloud-credential-operator
vendor/github.com/Azure/azure-sdk-for-go/services/preview/iothub/mgmt/2019-03-22-preview/devices/resourceprovidercommon.go
package devices // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // ResourceProviderCommonClient is the use this API to manage the IoT hubs in your Azure subscription. type ResourceProviderCommonClient struct { BaseClient } // NewResourceProviderCommonClient creates an instance of the ResourceProviderCommonClient client. func NewResourceProviderCommonClient(subscriptionID string) ResourceProviderCommonClient { return NewResourceProviderCommonClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewResourceProviderCommonClientWithBaseURI creates an instance of the ResourceProviderCommonClient client. func NewResourceProviderCommonClientWithBaseURI(baseURI string, subscriptionID string) ResourceProviderCommonClient { return ResourceProviderCommonClient{NewWithBaseURI(baseURI, subscriptionID)} } // GetSubscriptionQuota get the number of free and paid iot hubs in the subscription func (client ResourceProviderCommonClient) GetSubscriptionQuota(ctx context.Context) (result UserSubscriptionQuotaListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ResourceProviderCommonClient.GetSubscriptionQuota") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetSubscriptionQuotaPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", nil, "Failure preparing request") return } resp, err := client.GetSubscriptionQuotaSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", resp, "Failure sending request") return } result, err = client.GetSubscriptionQuotaResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "devices.ResourceProviderCommonClient", "GetSubscriptionQuota", resp, "Failure responding to request") } return } // GetSubscriptionQuotaPreparer prepares the GetSubscriptionQuota request. func (client ResourceProviderCommonClient) GetSubscriptionQuotaPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-03-22-preview" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Devices/usages", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSubscriptionQuotaSender sends the GetSubscriptionQuota request. The method will close the // http.Response Body if it receives an error. func (client ResourceProviderCommonClient) GetSubscriptionQuotaSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetSubscriptionQuotaResponder handles the response to the GetSubscriptionQuota request. The method always // closes the http.Response Body. func (client ResourceProviderCommonClient) GetSubscriptionQuotaResponder(resp *http.Response) (result UserSubscriptionQuotaListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
jansupol/helidon
microprofile/grpc/core/src/main/java/io/helidon/microprofile/grpc/core/GrpcInterceptors.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. * * 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 io.helidon.microprofile.grpc.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Declares an ordered list of gRPC interceptors for a target gRPC * service class or a gRPC service method of a target class. * <p> * The classes specified must be implementations of either * {@link io.grpc.ClientInterceptor} or {@link io.grpc.ServerInterceptor}. * * <pre> * &#064;GrpcService * &#064;GrpcInterceptors(ValidationInterceptor.class) * public class OrderService { ... } * </pre> * * <pre> * &#064;Unary * &#064;Interceptors({ValidationInterceptor.class, SecurityInterceptor.class}) * public void updateOrder(Order order) { ... } * </pre> */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface GrpcInterceptors { /** * An ordered list of interceptors. * * @return the ordered list of interceptors */ Class[] value(); }
marcomarasca/SynapseWebClient
src/main/java/org/sagebionetworks/web/client/presenter/SearchUtil.java
<reponame>marcomarasca/SynapseWebClient package org.sagebionetworks.web.client.presenter; import org.sagebionetworks.web.client.ClientProperties; import org.sagebionetworks.web.client.GlobalApplicationState; import org.sagebionetworks.web.client.place.PeopleSearch; import org.sagebionetworks.web.client.place.Search; import org.sagebionetworks.web.client.place.Synapse; import com.google.gwt.place.shared.Place; /** * This logic was removed from the search presenter so we could make a clean SearchPresenterProxy. * * @author John * */ public class SearchUtil { /** * If this returns a Synapse place then we should redirect to an entity page * * @param place * @return */ public static Place willRedirect(Search place) { String queryTerm = place.getSearchTerm(); if (queryTerm == null) queryTerm = ""; return willRedirect(queryTerm); } /** * If this returns a Synapse place then we should redirect to an entity page * * @param queryTerm * @return */ public static Place willRedirect(String queryTerm) { if (queryTerm.startsWith(ClientProperties.SYNAPSE_ID_PREFIX)) { String remainder = queryTerm.replaceFirst(ClientProperties.SYNAPSE_ID_PREFIX, ""); if (remainder.matches("^[0-9]+$")) { return new Synapse(queryTerm); } } else if (queryTerm.charAt(0) == '@') { return new PeopleSearch(queryTerm.substring(1)); } return null; } public static void searchForTerm(String queryTerm, final GlobalApplicationState globalApplicationState) { final Place place = willRedirect(queryTerm); final Search searchPlace = new Search(queryTerm); if (place == null) { // no potential redirect, go directly to search! globalApplicationState.getPlaceChanger().goTo(searchPlace); } else { globalApplicationState.getPlaceChanger().goTo(place); } } }
rvedotrc/node-aws-query
collectors/rds-collector.js
/* Copyright 2016 <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. */ var AWS = require('aws-sdk'); var Q = require('q'); var merge = require('merge'); var AtomicFile = require('../util/atomic-file'); var AwsDataUtils = require('../util/aws-data-utils'); var regions = require('../regions').regionsForService('RDS'); var promiseClient = function (clientConfig, region) { var config = merge(clientConfig, { region: region }); return Q(new AWS.RDS(config)); }; var describeDBInstances = function (client) { var paginationHelper = AwsDataUtils.paginationHelper("Marker", "Marker", "DBInstances"); return AwsDataUtils.collectFromAws(client, "describeDBInstances", {}, paginationHelper) .then(AwsDataUtils.tidyResponseMetadata) .then(function (r) { r.DBInstances.sort(function (a, b) { if (a.DBInstanceIdentifier < b.DBInstanceIdentifier) return -1; else if (a.DBInstanceIdentifier > b.DBInstanceIdentifier) return +1; else return 0; }); // TODO, more sorting? // DBParameterGroups.DBParameterGroupName // DBSecurityGroups.DBSecurityGroupName // DBSubnetGroup.Subnets.SubnetIdentifier // OptionGroupMemberships.OptionGroupName // ... return r; }); }; var collectAllForRegion = function (clientConfig, region) { var client = promiseClient(clientConfig, region); var ddi = client.then(describeDBInstances).then(AtomicFile.saveJsonTo("service/rds/region/"+region+"/describe-db-instances.json")); return Q.all([ ddi, Q(true) ]); }; var collectAll = function (clientConfig) { return Q.all(regions.map(function (r) { return collectAllForRegion(clientConfig, r); })); }; module.exports = { collectAll: collectAll };
JimmyBeldone/reapt
src/views/components/default/Dropdown/index.js
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import cn from "classnames"; import "./Dropdown.styl"; class Dropdown extends PureComponent { static propTypes = { dropdownTrigger: PropTypes.node.isRequired, dropdownContent: PropTypes.node.isRequired, buttonHeight: PropTypes.number, elemHeight: PropTypes.number, dropdownContentClassName: PropTypes.string, elemClassName: PropTypes.string }; static defaultProps = { buttonHeight: 40, elemHeight: 40, dropdownContentClassName: "", elemClassName: "" }; constructor(props) { super(props); this.state = { isActiveMenu: false }; this.showMenu = this.showMenu.bind(this); this.hideMenu = this.hideMenu.bind(this); } showMenu(e) { e.preventDefault(); this.setState({ isActiveMenu: true }, () => { document.addEventListener("click", this.hideMenu); }); } hideMenu() { this.setState({ isActiveMenu: false }, () => { document.removeEventListener("click", this.hideMenu); }); } renderContent() { const { elemClassName, dropdownContent, elemHeight } = this.props; return dropdownContent.map((elem, i) => ( <div key={`dropdown-content-elem-${i}`} className={cn("dropdown-content-elem", elemClassName)} style={{ height: elemHeight }} > {elem} </div> )); } render() { const { dropdownTrigger, buttonHeight, dropdownContentClassName } = this.props; const { isActiveMenu } = this.state; return ( <div className="dropdown-menu"> <button type="button" className="dropdown-trigger" onClick={this.showMenu.bind(this)} style={{ height: buttonHeight }} > {dropdownTrigger} </button> <div className={cn( "dropdown-content", dropdownContentClassName, { hidden: !isActiveMenu } )} // ref="dropdownContent" > {this.renderContent()} </div> </div> ); } } export default Dropdown;
xcjmine/Coding-Android
common-coding/src/main/java/net/coding/program/common/model/GitUploadPrepareObject.java
<reponame>xcjmine/Coding-Android package net.coding.program.common.model; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; /** * Created by zjh on 2017/2/16. * 文件上传前需要拿到lastCommit */ public class GitUploadPrepareObject implements Serializable { public String lastCommit; public GitUploadPrepareObject(JSONObject json) throws JSONException { lastCommit = json.optString("lastCommit"); } }
ImmanuelChavoya/launcher
pkg/pb/launcher/launcher.go
package launcher //go:generate protoc --go_out=plugins=grpc:. launcher.proto
andriyzagoruyko/landing-core
resources/js/pages/entity/Products/List/Card/index.js
import React from 'react'; import PropTypes from 'prop-types'; import { Grid, Card, CardActions, CardContent, Typography, Checkbox, FormControlLabel, } from '@material-ui/core/'; import Availability from '../Availability'; import useStyles from './styles'; import ProgresiveImage from '~c/common/ProgresiveImage'; const ProductCard = ({ id, checked, title, article, available, description, price, images, onSelect, renderActionButtons, }) => { const classes = useStyles(); return ( <Grid item xs={12} sm={6} md={4} lg={3}> <Card className={classes.card} variant="outlined"> <CardContent> <div> <FormControlLabel label={title} className={classes.cardTitle} control={ <Checkbox checked={checked} onChange={onSelect} color="secondary" /> } /> </div> <Typography variant="body2" color="textSecondary" component="p" > <b>${price}</b> Article: {article} </Typography> </CardContent> {images != null && ( <ProgresiveImage alt={title} title={title} {...images[0]} /> )} <CardContent className={classes.cardContent}> <Availability size="small" variant="default" available={available} /> <Typography variant="body2" color="textSecondary" component="p" className={classes.cardDescription} > {description} </Typography> </CardContent> <CardActions className={classes.cardActions}> {renderActionButtons(id)} </CardActions> </Card> </Grid> ); }; ProductCard.propTypes = { checked: PropTypes.bool, title: PropTypes.string.isRequired, article: PropTypes.string, available: PropTypes.number, price: PropTypes.number, description: PropTypes.string, thumbnail: PropTypes.object, onSelect: PropTypes.func, }; ProductCard.defaultProps = { onSelect: () => {}, }; export default ProductCard;
kevinsuh/labrador
app/assets/javascripts/application.js
<reponame>kevinsuh/labrador<gh_stars>1-10 //= require jquery //= require jquery_ujs //= require jquery-ui //= require jquery.Jcrop //= require jquery.payment.js //= require angular //= require angular-messages //= require angular-ui-router //= require angular-rails-templates //= require bootstrap //= require ui-bootstrap-tpls-0.13.4.min.js //= require spin.js/spin.min.js //= require angular-spinner/angular-spinner.min.js //= require angularjs-file-upload //= require angular-animate //= require ngImgCrop-master/compile/unminified/ng-img-crop.js //= require Case.js //= require CaseFilter.js //= require angular-stripe/angular-credit-cards.js //= require angular-stripe/angular-stripe.js //= require_tree . //= require_tree ./templates
noisychannel/joshua
test/joshua/zmert/BLEUTest.java
/* This file is part of the Joshua Machine Translation System. * * Joshua is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package joshua.zmert; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import joshua.zmert.BLEU; import joshua.zmert.EvaluationMetric; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * Unit tests for BLEU class. * * @author <NAME> * @version $LastChangedDate$ */ public class BLEUTest { @Test public void metricName() { // Setup the EvaluationMetric class EvaluationMetric.set_numSentences(0); EvaluationMetric.set_refsPerSen(1); EvaluationMetric.set_refSentences(null); BLEU bleu = new BLEU(); Assert.assertEquals(bleu.get_metricName(), "BLEU"); } @Test public void defaultConstructor() { // Setup the EvaluationMetric class EvaluationMetric.set_numSentences(0); EvaluationMetric.set_refsPerSen(1); EvaluationMetric.set_refSentences(null); BLEU bleu = new BLEU(); // Default constructor should use a maximum n-gram length of 4 Assert.assertEquals(bleu.maxGramLength, 4); // Default constructor should use the closest reference Assert.assertEquals(bleu.effLengthMethod, BLEU.EffectiveLengthMethod.CLOSEST); } @Test public void simpleTest() { String ref = "this is the fourth chromosome whose sequence has been completed to date . it comprises more than 87 million pairs of dna ."; String test = "this is the fourth chromosome to be fully sequenced up till now and it comprises of over 87 million pairs of deoxyribonucleic acid ( dna ) ."; // refSentences[i][r] stores the r'th reference of the i'th sentence String[][] refSentences = new String[1][1]; refSentences[0][0] = ref; EvaluationMetric.set_numSentences(1); EvaluationMetric.set_refsPerSen(1); EvaluationMetric.set_refSentences(refSentences); BLEU bleu = new BLEU(); // testSentences[i] stores the candidate translation for the i'th sentence String[] testSentences = new String[1]; testSentences[0] = test; try { // Check BLEU score matches double actualScore = bleu.score(testSentences); double expectedScore = 0.2513; double acceptableScoreDelta = 0.00001f; Assert.assertEquals(actualScore, expectedScore, acceptableScoreDelta); // Check sufficient statistics match int[] actualSS = bleu.suffStats(testSentences); int[] expectedSS = {14,27,8,26,5,25,3,24,27,23}; Assert.assertEquals(actualSS[0], expectedSS[0], 0); // 1-gram matches Assert.assertEquals(actualSS[1], expectedSS[1], 0); // 1-gram total Assert.assertEquals(actualSS[2], expectedSS[2], 0); // 2-gram matches Assert.assertEquals(actualSS[3], expectedSS[3], 0); // 2-gram total Assert.assertEquals(actualSS[4], expectedSS[4], 0); // 3-gram matches Assert.assertEquals(actualSS[5], expectedSS[5], 0); // 3-gram total Assert.assertEquals(actualSS[6], expectedSS[6], 0); // 4-gram matches Assert.assertEquals(actualSS[7], expectedSS[7], 0); // 4-gram total Assert.assertEquals(actualSS[8], expectedSS[8], 0); // candidate length Assert.assertEquals(actualSS[9], expectedSS[9], 0); // reference length } catch (Exception e) { Assert.fail(); } } @Parameters({"referenceFile","testFile"}) @Test public void fileTest(String referenceFile, String testFile) throws FileNotFoundException { //TODO You can now read in the files, and do something useful with them. Scanner refScanner = new Scanner(new File(referenceFile)); while (refScanner.hasNextLine()) { String refLine = refScanner.nextLine(); } } }
fatahamirha/delTelegramAccount
app/src/main/java/org/telegram/android/ui/pick/PickIntentClickListener.java
<filename>app/src/main/java/org/telegram/android/ui/pick/PickIntentClickListener.java<gh_stars>100-1000 package org.telegram.android.ui.pick; /** * Created by ex3ndr on 19.12.13. */ public interface PickIntentClickListener { public void onItemClicked(int index, PickIntentItem item, boolean isUseAlways); }
Manonjkfgh/stayaware
app/models/watchlist.rb
class Watchlist < ApplicationRecord end
onnoA/sample-collection
myselef-mybatis-test/src/main/java/cn/quellanan/pojo/Client.java
<gh_stars>1-10 package cn.quellanan.pojo; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import static java.util.stream.Collectors.toList; /** * @className: Client * @description: * @author: onnoA * @date: 2021/11/1 **/ public class Client { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { Mapper mapper = new Mapper(); MybatisXmlConfig xmlConfig = new MybatisXmlConfig(); xmlConfig.setNamespace("test"); xmlConfig.setMapperiname("TestDao"); mapper.setParmType(MybatisXmlConfig.class); Class<?> parmType = mapper.getParmType(); Field declaredField = parmType.getDeclaredField("namespace"); System.out.println(declaredField); declaredField.setAccessible(true); Object o = declaredField.get(xmlConfig); System.out.println(o.toString()); // Object o = parameter[0]; // value = declaredField.get(o); } /*public static void main(String[] args) { List<String> list1 = new ArrayList<String>(); list1.add("1"); list1.add("2"); list1.add("3"); list1.add("5"); list1.add("6"); List<String> list2 = new ArrayList<String>(); list2.add("2"); list2.add("3"); list2.add("7"); list2.add("8"); // 差集 (list2 - list1) List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList()); System.out.println("---差集 reduce2 (list2 - list1)---"); reduce2.parallelStream().forEach(System.out :: println); }*/ }
Fidor-FZCO/fidor_api
lib/fidor_api/transfer/swift.rb
<reponame>Fidor-FZCO/fidor_api module FidorApi module Transfer class Swift < Base include Generic validates :contact_name, presence: true, unless: :beneficiary_reference_passed? attribute :account_number, :string attribute :swift_code, :string attribute :account_currency, :string validates :account_number, presence: true, unless: :beneficiary_reference_passed? validates :swift_code, presence: true, unless: :beneficiary_reference_passed? validates :account_currency, presence: true, unless: :beneficiary_reference_passed? def set_attributes(attrs = {}) set_beneficiary_attributes(attrs) self.account_number = attrs.fetch("beneficiary", {}).fetch("routing_info", {})["account_number"] self.swift_code = attrs.fetch("beneficiary", {}).fetch("routing_info", {})["swift_code"] self.account_currency = attrs.fetch("beneficiary", {}).fetch("routing_info", {})["account_currency"] super(attrs.except("beneficiary")) end def as_json_routing_type "SWIFT" end def as_json_routing_info { account_number: account_number, swift_code: swift_code, account_currency: account_currency } end end end end
AugustinLF/academie
src/pages/helene-dufour.en.js
<reponame>AugustinLF/academie<filename>src/pages/helene-dufour.en.js import React from "react"; import InnerPage from "../components/innerPage"; import helene from "../helene.jpg"; import Layout from "../layouts/en"; const Helene = (props) => ( <Layout location={props.location}> <InnerPage name="<NAME>" title="Harpischord and lyric coach" imgUrl={helene} content={ <div> <p> <NAME> started studying harpsichord at the Paris Superior National Music Conservatory, then at the Royal Flemish Conservatory in Antwerp with <NAME>, and studied organ with <NAME>. </p> <p> She took part in tours of the European Union Baroque Orchestra, where she was to meet <NAME>, <NAME> and <NAME>. She then played for the most important concert institutions (Paris Sacred Art Festival, Lisbon Gulbekian Foundation, Utrecht Festival, Moscow Conservatory…) </p> <p> She now plays chamber music (duet with <NAME>, trio with La Tempesta…), basso continuo for orchestras (Le Capriccio Français, La Réjouissance…), and solos (Bach concertos, Manuel de Falla…). </p> <p> She has recorded French baroque motets (Diapason d’Or award), concerti grossi with ECBO. Her recording of 18th century sonatas with <NAME> received the Venice Fondazione Cini award, and her recording of Biber’s Rosenkranzsonaten received a “Choc” award from “Le Monde de la Musique”. </p> <p> She is a Lyric coach at the Versailles Baroque Music Center, a harpsichord Professor at the Reims Regional Conservatory, and a basso continuo Professor at the Orsay Regional Conservatory. </p> </div> } /> </Layout> ); export default Helene;
Anshul1507/Leetcode
src/main/java/com/fishercoder/solutions/_1386.java
package com.fishercoder.solutions; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * 1386. Cinema Seat Allocation * * A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. * Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i]=[3,8] means the seat located in row 3 and labelled with 8 is already reserved. * Return the maximum number of four-person families you can allocate on the cinema seats. A four-person family occupies fours seats in one row, that are next to each other. * Seats across an aisle (such as [3,3] and [3,4]) are not considered to be next to each other, however, It is permissible for the four-person family to be separated by an aisle, but in that case, exactly two people have to sit on each side of the aisle. * * Example 1: * Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]] * Output: 4 * Explanation: The figure above shows the optimal allocation for four families, where seats mark with blue are already reserved and contiguous seats mark with orange are for one family. * * Example 2: * Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]] * Output: 2 * * Example 3: * Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]] * Output: 4 * * Constraints: * 1 <= n <= 10^9 * 1 <= reservedSeats.length <= min(10*n, 10^4) * reservedSeats[i].length == 2 * 1 <= reservedSeats[i][0] <= n * 1 <= reservedSeats[i][1] <= 10 * All reservedSeats[i] are distinct. * */ public class _1386 { public static class Solution1 { public int maxNumberOfFamilies(int n, int[][] reservedSeats) { Map<Integer, Set<Integer>> map = new HashMap<>(); for (int[] seat : reservedSeats) { if (!map.containsKey(seat[0])) { map.put(seat[0], new HashSet<>()); } map.get(seat[0]).add(seat[1]); } int count = (n - map.size()) * 2; for (int key : map.keySet()) { Set<Integer> reservedOnes = map.get(key); if (reservedOnes.size() > 6) { continue; } if (!reservedOnes.contains(2) && !reservedOnes.contains(3) && !reservedOnes.contains(4) && !reservedOnes.contains(5) && !reservedOnes.contains(6) && !reservedOnes.contains(7) && !reservedOnes.contains(8) && !reservedOnes.contains(9)) { count += 2; } else if (!reservedOnes.contains(4) && !reservedOnes.contains(5) && !reservedOnes.contains(6) && !reservedOnes.contains(7)) { count++; } else if (!reservedOnes.contains(2) && !reservedOnes.contains(3) && !reservedOnes.contains(4) && !reservedOnes.contains(5)) { count++; } else if (!reservedOnes.contains(6) && !reservedOnes.contains(7) && !reservedOnes.contains(8) && !reservedOnes.contains(9)) { count++; } } return count; } } }
herlesupreeth/5G-Controller
empower/apps/thor/thor.py
<filename>empower/apps/thor/thor.py<gh_stars>0 #!/usr/bin/env python3 # # Copyright (c) 2015, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY CREATE-NET ''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 CREATE-NET 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. """Energy consumption balacing app.""" from empower.core.app import EmpowerApp from empower.core.app import EmpowerAppHandler from empower.core.app import EmpowerAppHomeHandler from empower.core.app import DEFAULT_PERIOD import empower.logger LOG = empower.logger.get_logger() class ThorHandler(EmpowerAppHandler): pass class ThorHomeHandler(EmpowerAppHomeHandler): pass class Thor(EmpowerApp): """Energy consumption balacing app. Command Line Parameters: period: loop period in ms (optional, default 5000ms) max_lvap_per_wtp: max number of LVAPs per WTP (optional, default 2) Example: ID="52313ecb-9d00-4b7d-b873-b55d3d9ada26" ./empower-runtime.py apps.thor.thor:$ID --max_lvaps_per_wtp=2 """ MODULE_NAME = "thor" MODULE_HANDLER = ThorHandler MODULE_HOME_HANDLER = ThorHomeHandler def __init__(self, tenant, **kwargs): self.__max_lvaps_per_wtp = 2 self.idle_cycles = {} EmpowerApp.__init__(self, tenant, **kwargs) @property def max_lvaps_per_wtp(self): """Return max_lvaps_per_wtp.""" return self.__max_lvaps_per_wtp @max_lvaps_per_wtp.setter def max_lvaps_per_wtp(self, value): """Set max_lvaps_per_wtp.""" max_lvaps_per_wtp = int(value) if max_lvaps_per_wtp < 1: raise ValueError("Invalid value for max_lvaps_per_wtp") LOG.info("Setting max_lvaps_per_wtp to %u" % value) self.__max_lvaps_per_wtp = max_lvaps_per_wtp def loop(self): """ Periodic job. """ count = 0 mappings = {v: [] for v in self.wtps() if v.feed} tank = [v for v in self.wtps() for _ in range(self.max_lvaps_per_wtp) if v.feed and v.connection] always_on = None if not tank: return for lvap in self.lvaps(): if not lvap.wtp.feed: LOG.info("LVAP %s on WTP w/o feed, ignoring.", lvap.addr) continue if not tank: tank = [v for v in self.wtps() if v.feed and v.connection] wtp = tank.pop() lvap.wtp = wtp mappings[lvap.wtp].append(lvap) LOG.info("LVAP %s -> %s", lvap.addr, lvap.wtp) if not always_on: always_on = lvap.wtp for wtp in mappings: if len(mappings[wtp]) > self.max_lvaps_per_wtp: count = count + (len(mappings[wtp]) - self.max_lvaps_per_wtp) if not always_on: always_on = [x for x in self.wtps() if x.feed][0] LOG.info("WTP %s always on", always_on.addr) LOG.info("Number of APs to be powered on %u", count) for wtp in mappings: if wtp == always_on or len(mappings[wtp]) > 0: if wtp in self.idle_cycles: del self.idle_cycles[wtp] wtp.powerup() elif count > 0: if wtp in self.idle_cycles: del self.idle_cycles[wtp] wtp.powerup() count = count - 1 elif wtp.feed.is_on: if wtp not in self.idle_cycles: self.idle_cycles[wtp] = 0 LOG.info("WTP %s idle for %u cycles", wtp.addr, self.idle_cycles[wtp]) if self.idle_cycles[wtp] >= 5: del self.idle_cycles[wtp] wtp.powerdown() else: self.idle_cycles[wtp] = self.idle_cycles[wtp] + 1 def launch(tenant, max_lvaps_per_wtp=2, period=DEFAULT_PERIOD): """ Initialize the module. """ return Thor(tenant, max_lvaps_per_wtp=max_lvaps_per_wtp, every=period)
mengzhisuoliu/librime
src/rime/gear/echo_translator.h
<reponame>mengzhisuoliu/librime // // Copyright RIME Developers // Distributed under the BSD License // // 2011-06-20 <NAME> <<EMAIL>> // #ifndef RIME_ECHO_TRANSLATOR_H_ #define RIME_ECHO_TRANSLATOR_H_ #include <rime/translator.h> namespace rime { class EchoTranslator : public Translator { public: EchoTranslator(const Ticket& ticket); virtual an<Translation> Query(const string& input, const Segment& segment); }; } // namespace rime #endif // RIME_ECHO_TRANSLATOR_H_
CIS-SoftwareDesign-S21/TeraNUI
nui-input/src/main/java/org/terasology/input/device/RawKeyboardAction.java
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.input.device; import org.terasology.input.ButtonState; import org.terasology.input.Input; public final class RawKeyboardAction { private final Input input; private final ButtonState state; public RawKeyboardAction(Input input, ButtonState state) { this.input = input; this.state = state; } /** * @return The type of input involved in this action (mouse button/mouse wheel) */ public Input getInput() { return input; } /** * @return The state of that input button */ public ButtonState getState() { return state; } @Override public String toString() { return "RawKeyboardAction [" + this.input + " (" + state + ")]"; } }
qdiankun/firstcode
firstcode/chapter8_media/src/main/java/com/me/diankun/chapter8_media/TakePhotoActivity.java
<reponame>qdiankun/firstcode package com.me.diankun.chapter8_media; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.me.diankun.chapter8_media.utils.CameraUtils; import com.me.diankun.chapter8_media.utils.FileUtils; import java.io.File; import java.io.FileNotFoundException; import java.text.SimpleDateFormat; import java.util.Date; /** * 拍摄照片 * Created by diankun on 2016/3/8. */ public class TakePhotoActivity extends AppCompatActivity { private Button btn_take_photo; private Button btn_choose_photo; private ImageView imageview; //这个Uri对象标识着output_image.jpg这张图片的唯一地址 private Uri imageUri; private String imagePath; private SimpleDateFormat simpleDateFormat; public static final int TAKE_PHOTO = 1; public static final int CROP_PHOTO = 2; public static final int CHOOSE_PHOTO = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_take_photo); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); btn_take_photo = (Button) findViewById(R.id.btn_take_photo); btn_choose_photo = (Button) findViewById(R.id.btn_choose_photo); imageview = (ImageView) findViewById(R.id.imageview); btn_take_photo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { takePhoto(); } }); btn_choose_photo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { choosePhoto(); } }); } private void choosePhoto() { //选择照片 //Intent intent = new Intent("android.intent.action.GET_CONTENT"); Intent intent = new Intent( // 相册 Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, CHOOSE_PHOTO); } private void takePhoto() { imageUri = Uri.fromFile(generateFile()); Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(i, TAKE_PHOTO); // 启动相机程序 } private File generateFile() { String path = Environment.getExternalStorageDirectory() + File.separator + "firstcode"; File file = new File(path); //判断文件夹是否存在,不存在创建 if (!file.exists()) { file.mkdirs(); } //拍摄照片的路径 imagePath = path + File.separator + simpleDateFormat.format(new Date()) + ".jpg"; File imageFile = new File(imagePath); return imageFile; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case TAKE_PHOTO: //Bitmap bitmap = BitmapFactory.decodeFile(imagePath); //imageview.setImageBitmap(bitmap); // 裁剪图片 cropImage(); break; case CHOOSE_PHOTO: if (data == null) return; //获取图片所在的真实路径 String picturePath = CameraUtils.getPath(TakePhotoActivity.this, data.getData()); //将图片复制到我们firstcode的文件夹下 File targetLocation = generateFile(); FileUtils.copyFile(new File(picturePath), targetLocation); //指定我们拷贝的文件为待裁剪的图片 imageUri = Uri.fromFile(targetLocation); cropImage(); break; case CROP_PHOTO: try { //使用decodeStream 获取Bitmap Bitmap map = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); imageview.setImageBitmap(map); //使用decodeFile来,获取Bitmap //Bitmap bitmap = BitmapFactory.decodeFile(imagePath); //imageview.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } break; } } } /** * 启动裁剪程序 */ public void cropImage() { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(imageUri, "image/*"); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, CROP_PHOTO); } }
NeonOcean/Environment
S4/S4 Decompiler/Old Libraries/xdis/opcodes/opcode_21.py
<reponame>NeonOcean/Environment # (C) Copyright 2017, 2019 by <NAME> # # This program 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 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ CPython 2.1 bytecode opcodes This is similar to the opcode portion in Python 2.1's dis.py library. """ import xdis.opcodes.opcode_22 as opcode_22 from xdis.opcodes.base import ( init_opdata, finalize_opcodes, format_extended_arg, rm_op, update_pj2, ) version = 2.1 l = locals() init_opdata(l, opcode_22, version) # 2.1 bytecodes changes from 2.2 rm_op(l, "BINARY_FLOOR_DIVIDE", 26) rm_op(l, "BINARY_TRUE_DIVIDE", 27) rm_op(l, "INPLACE_FLOOR_DIVIDE", 28) rm_op(l, "INPLACE_TRUE_DIVIDE", 29) rm_op(l, "GET_ITER", 68) rm_op(l, "YIELD_VALUE", 86) rm_op(l, "FOR_ITER", 93) update_pj2(globals(), l) opcode_arg_fmt = {"EXTENDED_ARG": format_extended_arg} finalize_opcodes(l)
npocmaka/Windows-Server-2003
net/sfm/afp/server/afp.h
<reponame>npocmaka/Windows-Server-2003<filename>net/sfm/afp/server/afp.h /* Copyright (c) 1992 Microsoft Corporation Module Name: afp.h Abstract: This file defines some server globals as well as include all relevant header files. Author: <NAME> (microsoft!jameelh) Revision History: 25 Apr 1992 Initial Version Notes: Tab stop: 4 --*/ #ifndef _AFP_ #define _AFP_ #include <ntosp.h> #include <zwapi.h> #include <security.h> #include <ntlmsp.h> #include <string.h> #include <wcstr.h> #include <ntiologc.h> #include <tdi.h> #include <tdikrnl.h> #if DBG /* Disable FASTCALLs for checked builds */ #undef FASTCALL #define FASTCALL #define LOCAL #else #define LOCAL #endif #ifdef _GLOBALS_ #define GLOBAL #define EQU = #else #define GLOBAL extern #define EQU ; / ## / #endif #include <atalktdi.h> #include <afpconst.h> #include <fwddecl.h> #include <intrlckd.h> #include <macansi.h> #include <macfile.h> #include <admin.h> #include <swmr.h> #include <fileio.h> #include <server.h> #include <forks.h> #include <sda.h> #include <afpinfo.h> #include <idindex.h> #include <desktop.h> #include <atalkio.h> #include <volume.h> #include <afpmem.h> #include <errorlog.h> #include <srvmsg.h> #include <time.h> #include <lists.h> #include <filenums.h> #include <rasfmsub.h> #include <tcp.h> #endif // _AFP_
treblereel/gwtbootstrap3
gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/InlineCheckBox.java
package org.gwtbootstrap3.client.ui; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 - 2014 GwtBootstrap3 * %% * 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% */ import org.gwtbootstrap3.client.ui.constants.Styles; import org.gwtproject.dom.client.Document; import org.gwtproject.i18n.client.HasDirection; import org.gwtproject.i18n.shared.DirectionEstimator; import org.gwtproject.safehtml.shared.SafeHtml; import org.gwtproject.user.client.DOM; /** * An inline check box widget. * * @author <NAME> * @see org.gwtbootstrap3.client.ui.CheckBox */ public class InlineCheckBox extends CheckBox { /** * Creates a check box with the specified text label. * * @param label * the check box's label */ public InlineCheckBox(SafeHtml label) { this(label.asString(), true); } /** * Creates a check box with the specified text label. * * @param label * the check box's label * @param dir * the text's direction. Note that {@code DEFAULT} means * direction should be inherited from the widget's parent * element. */ public InlineCheckBox(SafeHtml label, HasDirection.Direction dir) { this(); setHTML(label, dir); } /** * Creates a check box with the specified text label. * * @param label * the check box's label * @param directionEstimator * A DirectionEstimator object used for automatic direction * adjustment. For convenience, * {@link #DEFAULT_DIRECTION_ESTIMATOR} can be used. */ public InlineCheckBox(SafeHtml label, DirectionEstimator directionEstimator) { this(); setDirectionEstimator(directionEstimator); setHTML(label.asString()); } /** * Creates a check box with the specified text label. * * @param label * the check box's label */ public InlineCheckBox(String label) { this(); setText(label); } /** * Creates a check box with the specified text label. * * @param label * the check box's label * @param dir * the text's direction. Note that {@code DEFAULT} means * direction should be inherited from the widget's parent * element. */ public InlineCheckBox(String label, HasDirection.Direction dir) { this(); setText(label, dir); } /** * Creates a label with the specified text and a default direction * estimator. * * @param label * the check box's label * @param directionEstimator * A DirectionEstimator object used for automatic direction * adjustment. For convenience, * {@link #DEFAULT_DIRECTION_ESTIMATOR} can be used. */ public InlineCheckBox(String label, DirectionEstimator directionEstimator) { this(); setDirectionEstimator(directionEstimator); setText(label); } /** * Creates a check box with the specified text label. * * @param label * the check box's label * @param asHTML * <code>true</code> to treat the specified label as html */ public InlineCheckBox(String label, boolean asHTML) { this(); if (asHTML) { setHTML(label); } else { setText(label); } } public InlineCheckBox() { super(DOM.createLabel(), Document.get().createCheckInputElement()); setStyleName(Styles.CHECKBOX_INLINE); getElement().appendChild(inputElem); getElement().appendChild(labelElem); } }
byxorna/collins
app/collins/models/logs/LogMessageType.scala
package collins.models.logs object LogMessageType extends Enumeration { type LogMessageType = Value val Emergency = Value(0, "EMERGENCY") val Alert = Value(1, "ALERT") val Critical = Value(2, "CRITICAL") val Error = Value(3, "ERROR") val Warning = Value(4, "WARNING") val Notice = Value(5, "NOTICE") val Informational = Value(6, "INFORMATIONAL") val Debug = Value(7, "DEBUG") val Note = Value(8, "NOTE") }
versionwen/faststart
start/src/main/java/com/wenxin/learn/faststart/web/service/impl/AdminServiceImpl.java
<reponame>versionwen/faststart package com.wenxin.learn.faststart.web.service.impl; import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.ShearCaptcha; import cn.hutool.captcha.generator.MathGenerator; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.wenxin.learn.faststart.web.domain.AdminUserDetails; import com.wenxin.learn.faststart.web.dto.UpdateAdminPasswordParam; import com.wenxin.learn.faststart.web.entity.*; import com.wenxin.learn.faststart.web.mapper.AdminMapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.wenxin.learn.faststart.web.mapper.LoginLogMapper; import com.wenxin.learn.faststart.web.mapper.RoleMapper; import com.wenxin.learn.faststart.web.mapper.UmsResourceMapper; import com.wenxin.learn.faststart.web.service.AdminRoleRelationService; import com.wenxin.learn.faststart.web.service.AdminService; import com.wenxin.learn.faststart.web.utils.IpUtil; import com.wenxin.learn.faststart.web.utils.JwtTokenUtil; import com.wenxin.learn.faststart.web.utils.RedisUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.xml.crypto.Data; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; /** * <p> * 后台用户表 服务实现类 * </p> * * @author version * @since 2020-09-26 */ @Service @Slf4j public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService,UserDetails { @Autowired AdminMapper adminMapper; @Autowired private PasswordEncoder passwordEncoder; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UmsResourceMapper resourceMapper; @Autowired private RedisUtils redisUtils; @Autowired private LoginLogMapper loginLogMapper; @Autowired private RoleMapper roleMapper; @Autowired private AdminRoleRelationService adminRoleRelationService; @Override public UserDetails loadUserByUsername(String username){ QueryWrapper<Admin> wrapper = new QueryWrapper<>(); QueryWrapper<Admin> result = wrapper.eq("username", username); //获取用户信息 Admin admin = adminMapper.selectOne(result); if (admin != null) { List<UmsResource> resourceList = resourceMapper.getResourceList(admin.getId()); return new AdminUserDetails(admin,resourceList); } return null; } @Override public boolean Register(String username, String password, String Email) { Admin admin = new Admin(); admin.setUsername(username); String passwordEncode = passwordEncoder.encode(password); admin.setPassword(passwordEncode); admin.setEmail(Email); admin.setStatus(1); admin.setCreateTime(new Date()); //查询是否有重名用户 QueryWrapper<Admin>wrapper = new QueryWrapper<>(); wrapper.lambda().eq(Admin::getUsername,admin.getUsername()); List<Admin>adminList = list(wrapper); if(adminList.size() > 0){ return false ; } try { adminMapper.insert(admin); } catch (Exception e){ log.error("插入数据库出现错误,错误提示:{}",e); return false; } return true; } @Override public String getCaptcha(String request) { String uuid = request; ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4); log.info("获取到的UUID为:{}",uuid); // captcha.setGenerator(new MathGenerator()); String result = "data:image/png;base64," + captcha.getImageBase64(); log.info("captcha={}", captcha.getCode().toUpperCase()); redisUtils.set(uuid, captcha.getCode().toUpperCase(), 60L); return result; } @Override public boolean verifyCaptcha(String captcha,String uuid) { String rightCaptcha =(String)redisUtils.get(uuid); log.info("rightCaptcha={}",rightCaptcha); if(rightCaptcha == null||captcha == null){ return false; } if(captcha.toUpperCase().equals(rightCaptcha)){ return true ; } else { return false; } } @Override public String refreshToken(String oldToken) { return jwtTokenUtil.refreshHeadToken(oldToken); } @Override public void insertLoginLog(String username) { QueryWrapper<Admin>wrapper = new QueryWrapper<>(); QueryWrapper<Admin> user = wrapper.eq("username", username); Admin userLog = adminMapper.selectOne(user); if(user == null){ return; } LoginLog loginLog = new LoginLog(); loginLog.setAdminId(userLog.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String ua = request.getHeader("User-Agent"); loginLog.setUserAgent(ua); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); } @Override public boolean update(Long id, Admin admin) { admin.setId(id); Admin rawAdmin = getById(id); if(rawAdmin.getPassword().equals(admin.getPassword())){ //密码相同,不用修改 admin.setPassword(null); } else { if(StrUtil.isEmpty(admin.getPassword())){ admin.setPassword(null); } else { admin.setPassword(passwordEncoder.encode(admin.getPassword())); } } boolean success = updateById(admin); return success; } @Override public Page<Admin> list(String keyword, Integer pageSize, Integer pageNum) { return null; } @Override public boolean delete(Long id) { return false; } @Override public int updateRole(Long adminId, List<Long> roleIds) { int count = roleIds == null ? 0 : roleIds.size(); //先删除原来的关系 QueryWrapper<AdminRoleRelation> wrapper = new QueryWrapper<>(); wrapper.lambda().eq(AdminRoleRelation::getAdminId,adminId); adminRoleRelationService.remove(wrapper); //建立新关系 if (!CollectionUtils.isEmpty(roleIds)) { List<AdminRoleRelation> list = new ArrayList<>(); for (Long roleId : roleIds) { AdminRoleRelation roleRelation = new AdminRoleRelation(); roleRelation.setAdminId(adminId); roleRelation.setRoleId(roleId); list.add(roleRelation); } adminRoleRelationService.saveBatch(list); } return count; } @Override public List<Role> getRoleList(Long adminId) { return roleMapper.getRoleList(adminId); } @Override public List<UmsResource> getResourceList(Long adminId) { List<UmsResource> resourceList; resourceList = resourceMapper.getResourceList(adminId); return resourceList; } @Override public int updatePassword(UpdateAdminPasswordParam param) { if(StrUtil.isEmpty(param.getUsername()) ||StrUtil.isEmpty(param.getOldPassword()) ||StrUtil.isEmpty(param.getNewPassword())){ return -1; } QueryWrapper<Admin> wrapper = new QueryWrapper<>(); wrapper.lambda().eq(Admin::getUsername,param.getUsername()); List<Admin> adminList = list(wrapper); if(CollUtil.isEmpty(adminList)){ return -2; } Admin umsAdmin = adminList.get(0); if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){ return -3; } umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword())); updateById(umsAdmin); return 1; } @Override public Admin getAdminByUsername(String username) { QueryWrapper<Admin>wrapper =new QueryWrapper<>(); wrapper.lambda().eq(Admin::getUsername,username); Admin admin; List<Admin> adminList = list(wrapper); if (adminList != null && adminList.size() > 0) { admin = adminList.get(0); return admin; } return null; } @Override public String login(String username, String userpassword) { String token = null; try{ UserDetails userDetails =loadUserByUsername(username); if(!passwordEncoder.matches(userpassword,userDetails.getPassword())){ log.error("用户密码错误"); } token = jwtTokenUtil.generateToken(userDetails); }catch (Exception e){ log.error("出现错误{}",e); } return token; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return null; } @Override public String getUsername() { return null; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; } }
jklingen92/Roll20-Snippets
kscaffold-js/javascript/constants.js
const constants = { attributes: [ "strength", "dexterity", "constitution", "intelligence", "wisdom", "charisma" ] } export { constants }
dalvikfrank/development
apps/Development/src/com/android/development/InstrumentationList.java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.development; import android.app.ActivityManagerNative; import android.app.IInstrumentationWatcher; import android.app.ListActivity; import android.content.ComponentName; import android.content.Context; import android.content.pm.InstrumentationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.RemoteException; import android.os.UserHandle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Collections; import java.util.List; class InstrumentationAdapter extends BaseAdapter { private PackageManager mPM; public InstrumentationAdapter(Context context, String targetPackage) { mContext = context; mTargetPackage = targetPackage; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPM = context.getPackageManager(); mList = context.getPackageManager().queryInstrumentation(mTargetPackage, 0); if (mList != null) { Collections.sort(mList, new InstrumentationInfo.DisplayNameComparator(mPM)); } } public ComponentName instrumentationForPosition(int position) { if (mList == null) { return null; } InstrumentationInfo ii = mList.get(position); return new ComponentName(ii.packageName, ii.name); } public int getCount() { return mList != null ? mList.size() : 0; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate( android.R.layout.simple_list_item_1, parent, false); } else { view = convertView; } bindView(view, mList.get(position)); return view; } private final void bindView(View view, InstrumentationInfo info) { TextView text = (TextView)view.findViewById(android.R.id.text1); CharSequence label = info.loadLabel(mPM); text.setText(label != null ? label : info.name); } protected final Context mContext; protected final String mTargetPackage; protected final LayoutInflater mInflater; protected List<InstrumentationInfo> mList; } public class InstrumentationList extends ListActivity { @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mProfilingMode = icicle != null && icicle.containsKey("profiling"); setListAdapter(new InstrumentationAdapter(this, null)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mProfilingItem = menu.add(0, 0, 0, "Profiling Mode") .setOnMenuItemClickListener(mProfilingCallback); mProfilingItem.setCheckable(true); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); mProfilingItem.setChecked(mProfilingMode); return true; } @Override protected void onSaveInstanceState(Bundle outState) { if (mProfilingMode) { outState.putBoolean("profiling", true); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { ComponentName className = ((InstrumentationAdapter)getListAdapter()). instrumentationForPosition(position); if (className != null) { String profilingFile = null; if (mProfilingMode) { profilingFile = "/tmp/trace/" + className + ".dmtrace"; } try { ActivityManagerNative.getDefault(). startInstrumentation(className, profilingFile, 0, null, mWatcher, null, UserHandle.myUserId(), null); } catch (RemoteException ex) { } } } private MenuItem.OnMenuItemClickListener mProfilingCallback = new MenuItem.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { mProfilingMode = !mProfilingMode; return true; } }; private IInstrumentationWatcher mWatcher = new IInstrumentationWatcher.Stub() { public void instrumentationStatus(ComponentName name, int resultCode, Bundle results) { if (results != null) { for (String key : results.keySet()) { Log.i("instrumentation", "INSTRUMENTATION_STATUS_RESULT: " + key + "=" + results.get(key)); } } Log.i("instrumentation", "INSTRUMENTATION_STATUS_CODE: " + resultCode); } public void instrumentationFinished(ComponentName name, int resultCode, Bundle results) { if (results != null) { for (String key : results.keySet()) { Log.i("instrumentation", "INSTRUMENTATION_RESULT: " + key + "=" + results.get(key)); } } Log.i("instrumentation", "INSTRUMENTATION_CODE: " + resultCode); } }; private MenuItem mProfilingItem; private boolean mProfilingMode; }
bubby932/RecNetBotV2
cogs/other.py
import functions import discord from discord.ext import commands class Other(commands.Cog): def __init__(self, client): self.client = client # CMD-DOC @commands.command() @commands.check(functions.beta_tester) async def doc(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) embed=discord.Embed( colour=discord.Colour.orange(), title = "Unofficial documentation of RecNet API, made by ColinXYZ", description = "[Documentation Link](https://documenter.getpostman.com/view/13848200/TVt184DN)" ) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) # CMD-INVITE @commands.command() @commands.check(functions.beta_tester) async def invite(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) embed=discord.Embed( colour=discord.Colour.orange(), title = "🔗 Invitation links!", description = "<:discord:803539862435135510> [Test server](https://discord.gg/GPVdhMa2zK)\n<:BotGraffiti:803539486930763786> [Bot invite link](https://discord.com/api/oauth2/authorize?client_id=788632031835324456&permissions=322624&scope=bot)" ) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) #CMD-CRINGEBIOS @commands.command() async def cringebios(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) with open("cringe_bios.json", "rb") as bios: await ctx.send(file=discord.File(bios, "Cringe bio list.json")) def setup(client): client.add_cog(Other(client))
Selous05/beeetv_1.6
app/src/main/java/com/beeecorptv/ui/downloadmanager/core/sorting/DownloadSortingComparator.java
/* * EasyPlex - Movies - Live Streaming - TV Series, Anime * * @author @Y0bEX * @package EasyPlex - Movies - Live Streaming - TV Series, Anime * @copyright Copyright (c) 2021 Y0bEX, * @license http://codecanyon.net/wiki/support/legal-terms/licensing-terms/ * @profile https://codecanyon.net/user/yobex * @link <EMAIL> * @skype <EMAIL> **/ package com.beeecorptv.ui.downloadmanager.core.sorting; import androidx.annotation.NonNull; import com.beeecorptv.ui.downloadmanager.ui.main.DownloadItem; import java.util.Comparator; public class DownloadSortingComparator implements Comparator<DownloadItem> { private DownloadSorting sorting; public DownloadSortingComparator(@NonNull DownloadSorting sorting) { this.sorting = sorting; } public DownloadSorting getSorting() { return sorting; } @Override public int compare(DownloadItem o1, DownloadItem o2) { return DownloadSorting.SortingColumns.fromValue(sorting.getColumnName()) .compare(o1, o2, sorting.getDirection()); } }
halotroop2288/consulo
modules/base/lang-impl/src/main/java/com/intellij/ide/projectView/impl/nodes/PsiDirectoryNode.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.projectView.impl.nodes; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.projectView.impl.ProjectRootsUtil; import com.intellij.ide.projectView.impl.ProjectViewImpl; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.fileTypes.FileTypeRegistry; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.libraries.LibraryUtil; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.NavigatableWithText; import com.intellij.psi.PsiDirectory; import com.intellij.psi.impl.file.PsiPackageHelper; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.PathUtil; import consulo.ui.annotation.RequiredUIAccess; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; public class PsiDirectoryNode extends BasePsiNode<PsiDirectory> implements NavigatableWithText { private final PsiFileSystemItemFilter myFilter; public PsiDirectoryNode(Project project, @Nonnull PsiDirectory value, ViewSettings viewSettings) { this(project, value, viewSettings, null); } public PsiDirectoryNode(Project project, @Nonnull PsiDirectory value, ViewSettings viewSettings, @Nullable PsiFileSystemItemFilter filter) { super(project, value, viewSettings); myFilter = filter; } @Nullable public PsiFileSystemItemFilter getFilter() { return myFilter; } @Override protected void updateImpl(PresentationData data) { final Project project = getProject(); final PsiDirectory psiDirectory = getValue(); final VirtualFile directoryFile = psiDirectory.getVirtualFile(); final Object parentValue = getParentValue(); if (ProjectRootsUtil.isModuleContentRoot(directoryFile, project)) { ProjectFileIndex fi = ProjectRootManager.getInstance(project).getFileIndex(); Module module = fi.getModuleForFile(directoryFile); data.setPresentableText(directoryFile.getName()); if (module != null) { if (!(parentValue instanceof Module)) { if (Comparing.equal(module.getName(), directoryFile.getName())) { data.addText(directoryFile.getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); } else { data.addText(directoryFile.getName() + " ", SimpleTextAttributes.REGULAR_ATTRIBUTES); data.addText("[" + module.getName() + "]", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); } } else { data.addText(directoryFile.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } if (parentValue instanceof Module || parentValue instanceof Project) { final String location = FileUtil.getLocationRelativeToUserHome(directoryFile.getPresentableUrl()); data.addText(" (" + location + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES); } else if (ProjectRootsUtil.isSourceOrTestRoot(directoryFile, project)) { if (ProjectRootsUtil.isInTestSource(directoryFile, project)) { data.addText(" (test source root)", SimpleTextAttributes.GRAY_ATTRIBUTES); } else { data.addText(" (source root)", SimpleTextAttributes.GRAY_ATTRIBUTES); } } return; } } final String name = parentValue instanceof Project ? psiDirectory.getVirtualFile().getPresentableUrl() : BaseProjectViewDirectoryHelper.getNodeName(getSettings(), parentValue, psiDirectory); if (name == null) { setValue(null); return; } data.setPresentableText(name); if (ProjectRootsUtil.isLibraryRoot(directoryFile, project)) { data.setLocationString("library home"); } else { data.setLocationString(BaseProjectViewDirectoryHelper.getLocationString(psiDirectory)); } } @Override public Collection<AbstractTreeNode> getChildrenImpl() { return BaseProjectViewDirectoryHelper.getDirectoryChildren(getValue(), getSettings(), true); } @Override @SuppressWarnings("deprecation") public String getTestPresentation() { return "PsiDirectory: " + getValue().getName(); } public boolean isFQNameShown() { return BaseProjectViewDirectoryHelper.isShowFQName(getProject(), getSettings(), getParentValue(), getValue()); } @Override public boolean contains(@Nonnull VirtualFile file) { final PsiDirectory value = getValue(); if (value == null) { return false; } VirtualFile directory = value.getVirtualFile(); if (directory.getFileSystem() instanceof LocalFileSystem) { file = PathUtil.getLocalFile(file); } if (!VfsUtilCore.isAncestor(directory, file, false)) { return false; } return !FileTypeRegistry.getInstance().isFileIgnored(file); } @Override public boolean canRepresent(final Object element) { if (super.canRepresent(element)) return true; PsiDirectory directory = getValue(); if (directory == null) return false; return BaseProjectViewDirectoryHelper.canRepresent(element, directory); } @Override public boolean canNavigate() { VirtualFile file = getVirtualFile(); Project project = getProject(); ProjectSettingsService service = ProjectSettingsService.getInstance(myProject); return file != null && ((ProjectRootsUtil.isModuleContentRoot(file, project) && service.canOpenModuleSettings()) || (ProjectRootsUtil.isModuleSourceRoot(file, project) && service.canOpenContentEntriesSettings()) || (ProjectRootsUtil.isLibraryRoot(file, project) && service.canOpenModuleLibrarySettings())); } @Override public boolean canNavigateToSource() { return false; } @Override @RequiredUIAccess public void navigate(final boolean requestFocus) { Module module = ModuleUtil.findModuleForPsiElement(getValue()); if (module != null) { final VirtualFile file = getVirtualFile(); final Project project = getProject(); ProjectSettingsService service = ProjectSettingsService.getInstance(myProject); if (ProjectRootsUtil.isModuleContentRoot(file, project)) { service.openModuleSettings(module); } else if (ProjectRootsUtil.isLibraryRoot(file, project)) { final OrderEntry orderEntry = LibraryUtil.findLibraryEntry(file, module.getProject()); if (orderEntry != null) { service.openLibraryOrSdkSettings(orderEntry); } } else { service.openContentEntriesSettings(module); } } } @Override public String getNavigateActionText(boolean focusEditor) { VirtualFile file = getVirtualFile(); Project project = getProject(); if (file != null) { if (ProjectRootsUtil.isModuleContentRoot(file, project) || ProjectRootsUtil.isSourceOrTestRoot(file, project)) { return "Open Module Settings"; } if (ProjectRootsUtil.isLibraryRoot(file, project)) { return "Open Library Settings"; } } return null; } @Override public int getWeight() { final ProjectView projectView = ProjectView.getInstance(myProject); if (projectView instanceof ProjectViewImpl && !((ProjectViewImpl)projectView).isFoldersAlwaysOnTop()) { return 20; } return isFQNameShown() ? 70 : 0; } @Override public String getTitle() { final PsiDirectory directory = getValue(); if (directory != null) { return PsiPackageHelper.getInstance(getProject()).getQualifiedName(directory, true); } return super.getTitle(); } @Override public String getQualifiedNameSortKey() { final PsiPackageHelper factory = PsiPackageHelper.getInstance(getProject()); return factory.getQualifiedName(getValue(), true); } @Override public int getTypeSortWeight(final boolean sortByType) { return 3; } @Override public boolean shouldDrillDownOnEmptyElement() { return true; } @Override public boolean isAlwaysShowPlus() { final VirtualFile file = getVirtualFile(); return file == null || file.getChildren().length > 0; } }
nkruzan/bluepad32
src/components/bluepad32/include/uni_gamepad.h
<filename>src/components/bluepad32/include/uni_gamepad.h /**************************************************************************** http://retro.moe/unijoysticle2 Copyright 2019 <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. ****************************************************************************/ #ifndef UNI_GAMEPAD_H #define UNI_GAMEPAD_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include "uni_common.h" extern const int AXIS_NORMALIZE_RANGE; extern const int AXIS_THRESHOLD; typedef enum { UNI_GAMEPAD_MAPPINGS_DPAD_UP, UNI_GAMEPAD_MAPPINGS_DPAD_DOWN, UNI_GAMEPAD_MAPPINGS_DPAD_RIGHT, UNI_GAMEPAD_MAPPINGS_DPAD_LEFT, } uni_gamepad_mappings_dpad_t; typedef enum { UNI_GAMEPAD_MAPPINGS_BUTTON_A, UNI_GAMEPAD_MAPPINGS_BUTTON_B, UNI_GAMEPAD_MAPPINGS_BUTTON_X, UNI_GAMEPAD_MAPPINGS_BUTTON_Y, UNI_GAMEPAD_MAPPINGS_BUTTON_SHOULDER_L, UNI_GAMEPAD_MAPPINGS_BUTTON_SHOULDER_R, UNI_GAMEPAD_MAPPINGS_BUTTON_TRIGGER_L, UNI_GAMEPAD_MAPPINGS_BUTTON_TRIGGER_R, UNI_GAMEPAD_MAPPINGS_BUTTON_THUMB_L, UNI_GAMEPAD_MAPPINGS_BUTTON_THUMB_R, } uni_gamepad_mappings_button_t; typedef enum { UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_SYSTEM, UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_BACK, UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_HOME, } uni_gamepad_mappings_misc_button_t; typedef enum { UNI_GAMEPAD_MAPPINGS_AXIS_X, UNI_GAMEPAD_MAPPINGS_AXIS_Y, UNI_GAMEPAD_MAPPINGS_AXIS_RX, UNI_GAMEPAD_MAPPINGS_AXIS_RY, } uni_gamepad_mappings_axis_t; typedef enum { UNI_GAMEPAD_MAPPINGS_PEDAL_BRAKE, UNI_GAMEPAD_MAPPINGS_PEDAL_THROTTLE, } uni_gamepad_mappings_pedal_t; // DPAD constants. enum { DPAD_UP = BIT(UNI_GAMEPAD_MAPPINGS_DPAD_UP), DPAD_DOWN = BIT(UNI_GAMEPAD_MAPPINGS_DPAD_DOWN), DPAD_RIGHT = BIT(UNI_GAMEPAD_MAPPINGS_DPAD_RIGHT), DPAD_LEFT = BIT(UNI_GAMEPAD_MAPPINGS_DPAD_LEFT), }; // BUTTON_ are the main gamepad buttons, like X, Y, A, B, etc. enum { BUTTON_A = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_A), BUTTON_B = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_B), BUTTON_X = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_X), BUTTON_Y = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_Y), BUTTON_SHOULDER_L = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_SHOULDER_L), BUTTON_SHOULDER_R = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_SHOULDER_R), BUTTON_TRIGGER_L = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_TRIGGER_L), BUTTON_TRIGGER_R = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_TRIGGER_R), BUTTON_THUMB_L = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_THUMB_L), BUTTON_THUMB_R = BIT(UNI_GAMEPAD_MAPPINGS_BUTTON_THUMB_R), }; // MISC_BUTTONS_ are buttons that are usually not used in the game, but are // helpers like "back", "home", etc. enum { MISC_BUTTON_SYSTEM = BIT(UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_SYSTEM), // AKA: PS, Xbox, etc. MISC_BUTTON_BACK = BIT(UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_BACK), // AKA: Select, Share, - MISC_BUTTON_HOME = BIT(UNI_GAMEPAD_MAPPINGS_MISC_BUTTON_HOME), // AKA: Start, Options, + }; // GAMEPAD_STATE_ are used internally to determine which button event // were registered in the last HID report. // Most gamepad (if not all) report all their buttons in just one report. // TODO: Investigate if this is legacy code, or it is actually needed for iCade. enum { GAMEPAD_STATE_DPAD = BIT(0), GAMEPAD_STATE_AXIS_X = BIT(1), GAMEPAD_STATE_AXIS_Y = BIT(2), GAMEPAD_STATE_AXIS_RX = BIT(3), GAMEPAD_STATE_AXIS_RY = BIT(4), GAMEPAD_STATE_BRAKE = BIT(5), // AKA L2 GAMEPAD_STATE_THROTTLE = BIT(6), // AKA R2 GAMEPAD_STATE_BUTTON_A = BIT(10), GAMEPAD_STATE_BUTTON_B = BIT(11), GAMEPAD_STATE_BUTTON_X = BIT(12), GAMEPAD_STATE_BUTTON_Y = BIT(13), GAMEPAD_STATE_BUTTON_SHOULDER_L = BIT(14), // AKA L1 GAMEPAD_STATE_BUTTON_SHOULDER_R = BIT(15), // AKA R1 GAMEPAD_STATE_BUTTON_TRIGGER_L = BIT(16), GAMEPAD_STATE_BUTTON_TRIGGER_R = BIT(17), GAMEPAD_STATE_BUTTON_THUMB_L = BIT(18), GAMEPAD_STATE_BUTTON_THUMB_R = BIT(19), GAMEPAD_STATE_MISC_BUTTON_BACK = BIT(24), GAMEPAD_STATE_MISC_BUTTON_HOME = BIT(25), GAMEPAD_STATE_MISC_BUTTON_MENU = BIT(26), GAMEPAD_STATE_MISC_BUTTON_SYSTEM = BIT(27), }; // Represents which "seat" the gamepad is using. Multiple gamepads can be // connected at the same time, and the "seat" is the ID of each gamepad. // In the Legacy firmware it was possible for a gamepad to take more than one // seat, but since the v2.0 it might not be needed anymore. // TODO: Investigate if this really needs to be a "bit". typedef enum { GAMEPAD_SEAT_NONE = 0, GAMEPAD_SEAT_A = BIT(0), GAMEPAD_SEAT_B = BIT(1), GAMEPAD_SEAT_C = BIT(2), GAMEPAD_SEAT_D = BIT(3), // Masks GAMEPAD_SEAT_AB_MASK = (GAMEPAD_SEAT_A | GAMEPAD_SEAT_B), } uni_gamepad_seat_t; // uni_gamepad_t is a virtual gamepad. // Different parsers should populate this virtual gamepad accordingly. // For example, the virtual gamepad doesn't have a Hat, but has a D-pad. // If the real gamepad has a Hat, it should populate the D-pad instead. // // If the real device only has one joy-pad, it should populate the left side // of the virtual gamepad. // Example: a TV remote control should populate the left D-pad and the left // joypad. // // The virtual gamepad will then be processed by the dfferent "platforms". // // Virtual Gamepad layout: // // Left Center Right // // brake: 0-1023 Menu button accelerator: 0-1023 // L-shoulder button R-shoulder button // L-trigger button R-trigger button // d-pad buttons: A,B,X,Y, // l-joypad (axis: -512, 511) r-joypad (axis: -512, 511) // axis-l button axis-r button // // trigger's buttons & accelerator are shared physically. typedef struct { // Usage Page: 0x01 (Generic Desktop Controls) uint8_t dpad; int32_t axis_x; int32_t axis_y; int32_t axis_rx; int32_t axis_ry; // Usage Page: 0x02 (Sim controls) int32_t brake; int32_t throttle; // Usage Page: 0x06 (Generic dev controls) uint16_t battery; // Usage Page: 0x09 (Button) uint16_t buttons; // Misc buttons (from 0x0c (Consumer) and others) uint8_t misc_buttons; // FIXME: It might be OK to get rid of this variable. Or in any case, it // should be moved ouside uni_gamepad_t? // Indicates which states have been updated uint32_t updated_states; } uni_gamepad_t; // Represents the mapping. Each entry contains the new button to be used, // and not the value of the buttons. typedef struct { // Remaps for Dpad uint8_t dpad_up; uint8_t dpad_down; uint8_t dpad_left; uint8_t dpad_right; // Remaps for the buttons uint8_t button_a; uint8_t button_b; uint8_t button_x; uint8_t button_y; uint8_t button_shoulder_l; uint8_t button_shoulder_r; uint8_t button_trigger_l; uint8_t button_trigger_r; uint8_t button_thumb_l; uint8_t button_thumb_r; uint8_t misc_button_back; uint8_t misc_button_home; uint8_t misc_button_system; // Remaps for axis uint8_t axis_x; uint8_t axis_y; uint8_t axis_rx; uint8_t axis_ry; // Whether the axis should be inverted uint8_t axis_x_inverted; uint8_t axis_y_inverted; uint8_t axis_rx_inverted; uint8_t axis_ry_inverted; // Remaps for brake / throttle uint8_t brake; uint8_t throttle; } uni_gamepad_mappings_t; extern const uni_gamepad_mappings_t GAMEPAD_DEFAULT_MAPPINGS; void uni_gamepad_dump(const uni_gamepad_t* gp); uni_gamepad_t uni_gamepad_remap(const uni_gamepad_t* gp); void uni_gamepad_set_mappings(const uni_gamepad_mappings_t* mapping); #ifdef __cplusplus } #endif #endif // UNI_GAMEPAD_H
dmxj/icv
tests/get_connect.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved # """ get_connect.py Authors: rensike(<EMAIL>) Date: 2019/9/12 下午6:59 """ from skimage import measure import cv2 import numpy as np from icv.image.vis import imshow def counters(img_pth): img = cv2.imread(img_pth, 0) _, labels = cv2.connectedComponents(img) ids = list(set(labels.flatten().tolist())) print("ids: ", ids, ", labels: ", labels) for id in ids[1:]: w = np.where(labels == id) ground_truth_binary_mask = np.zeros_like(img, np.uint8) ground_truth_binary_mask[w] = 1 contours = measure.find_contours(ground_truth_binary_mask, 0.5) print(len(contours)) if __name__ == '__main__': # imshow("/Users/rensike/Work/radar/1.jpg") img = cv2.imread("/Users/rensike/Work/radar/0.png", 0) # w = np.where(img != 0) # # ymin = min(w[0]) # ymax = max(w[0]) # # xmin = min(w[1]) # xmax = max(w[1]) # # img1 = img[ymin:ymax,xmin:xmax] _, labels = cv2.connectedComponents(img) ids = list(set(labels.flatten().tolist())) max_id = 0 max_cnt = -1 for id in ids[1:]: w = np.where(labels == id) if img[w[0][0],w[1][0]] != 0: if len(w[0]) > max_cnt: max_cnt = len(w[0]) max_id = id w = np.where(labels == max_id) ymin = min(w[0]) ymax = max(w[0]) xmin = min(w[1]) xmax = max(w[1]) img1 = img[ymin:ymax,xmin:xmax] imshow(img1)
hazim79/behaviorsearch
src/bsearch/evaluation/DerivativeFitnessFunction.java
package bsearch.evaluation; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import org.nlogo.util.MersenneTwisterFast; import bsearch.app.BehaviorSearchException; import bsearch.app.SearchProtocol; import bsearch.nlogolink.ModelRunResult; import bsearch.representations.Chromosome; import bsearch.representations.DummyChromosome; /** * This class is a work-in-progress. Currently unused... */ public strictfp class DerivativeFitnessFunction implements FitnessFunction { private final SearchProtocol protocol; private final String paramName; private final double deltaDistance; private final MersenneTwisterFast rng; private List<Chromosome> SPECIAL_MUTATE_pointsqueue = new LinkedList<Chromosome>(); private List<Chromosome> SPECIAL_MUTATE_neighborsqueue = new LinkedList<Chromosome>(); public DerivativeFitnessFunction(SearchProtocol protocol, MersenneTwisterFast rng) throws BehaviorSearchException { this.protocol = protocol; this.paramName = protocol.fitnessDerivativeParameter; this.deltaDistance = protocol.fitnessDerivativeDelta; this.rng = rng; if (deltaDistance == 0) { throw new BehaviorSearchException("When taking the 'derivative' of the fitness function with respect to parameter X, the delta value (change in X) cannot be 0!"); } } private Chromosome getPointDeltaNearby(Chromosome point) throws BehaviorSearchException { //Special case: if we set paramName to "@MUTATE@" then it chooses a neighboring point // in the search space by using mutation (with the mutation rate specified by deltaDistance) // from the current point. if (paramName.equals("@MUTATE@")) { double mutRate = deltaDistance; int failedMutationCounter = 0; final int MAX_MUTATION_ATTEMPTS = 1000000; Chromosome neighbor = point.mutate(mutRate, rng); while (neighbor.equals(point) && failedMutationCounter < MAX_MUTATION_ATTEMPTS ) { neighbor = point.mutate(mutRate, rng); } if (failedMutationCounter == MAX_MUTATION_ATTEMPTS) { throw new BehaviorSearchException("An extremely large number of mutation attempts all resulted in no mutation - perhaps your mutation-rate is too low?"); } SPECIAL_MUTATE_pointsqueue.add(point); SPECIAL_MUTATE_neighborsqueue.add(neighbor); return neighbor; } LinkedHashMap<String, Object> newParamSettings = new LinkedHashMap<String,Object>(point.getParamSettings()); Object curVal = newParamSettings.get(paramName); if (curVal instanceof Number) { double val = ((Number) curVal).doubleValue(); double newVal = (val - deltaDistance); newParamSettings.put(paramName, newVal); } else { throw new BehaviorSearchException("Derivative-based fitness measurements currently only work with numerical parameters!"); } return new DummyChromosome(point.getSearchSpace(), newParamSettings); } public HashMap<Chromosome, Integer> getRunsNeeded(Chromosome point, int repetitionsRequested, ResultsArchive archive) throws BehaviorSearchException { LinkedHashMap<Chromosome, Integer> map = new LinkedHashMap<Chromosome,Integer>(1); map.put(point, StrictMath.max(0, repetitionsRequested - archive.getResultsCount(point))); Chromosome deltaComparePoint = getPointDeltaNearby(point); map.put(deltaComparePoint, StrictMath.max(0, repetitionsRequested - archive.getResultsCount(deltaComparePoint))); return map; } public int getMaximumRunsThatCouldBeNeeded(int repetitionsRequested) { return 2 * repetitionsRequested; } public double evaluate(Chromosome point, ResultsArchive archive) throws BehaviorSearchException { List<ModelRunResult> resultsSoFar = archive.getResults( point ); LinkedList<Double> condensedResults = new LinkedList<Double>(); for (ModelRunResult result: resultsSoFar) { List<Double> singleRunHistory = result.getPrimaryTimeSeries(); double dResult = protocol.fitnessCollecting.collectFrom(singleRunHistory); condensedResults.add(dResult); } double pointVal = protocol.fitnessCombineReplications.combine(condensedResults); Chromosome neighbor; if (paramName.equals("@MUTATE@")) { int index = SPECIAL_MUTATE_pointsqueue.indexOf(point); neighbor = SPECIAL_MUTATE_neighborsqueue.get(index); SPECIAL_MUTATE_pointsqueue.remove(index); SPECIAL_MUTATE_neighborsqueue.remove(index); } else { neighbor = getPointDeltaNearby( point ); } resultsSoFar = archive.getResults( neighbor ); condensedResults = new LinkedList<Double>(); for (ModelRunResult result: resultsSoFar) { List<Double> singleRunHistory = result.getPrimaryTimeSeries(); double dResult = protocol.fitnessCollecting.collectFrom(singleRunHistory); condensedResults.add(dResult); } double deltaComparePointVal = protocol.fitnessCombineReplications.combine(condensedResults); double denominator = deltaDistance; // Special case, to see how much fitness varies between neighbors in the search space if (paramName.equals("@MUTATE@")) { denominator = 1; } if (protocol.fitnessDerivativeUseAbs) { return StrictMath.abs((pointVal - deltaComparePointVal) / denominator); } else { return (pointVal - deltaComparePointVal) / denominator; } } public double compare(double v1, double v2) { if (protocol.fitnessMinimized) { return v2 - v1 ; } else { return v1 - v2 ; } } public boolean strictlyBetterThan(double v1, double v2) { return compare(v1,v2) > 0.0; } public double getWorstConceivableFitnessValue() { return protocol.fitnessMinimized?Double.POSITIVE_INFINITY:Double.NEGATIVE_INFINITY; } public double getBestConceivableFitnessValue() { return protocol.fitnessMinimized?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY; } public boolean reachedStopGoalFitness(double fitness) { return false; //TODO: not implemented (see comment in StandardFitnessFunction) /*if (!hasStopGoal) { return false; } else { if (protocol.fitnessMinimized) { return fitness <= stopGoalFitness; } else { return fitness >= stopGoalFitness; } }*/ } }
r-neal-kelly/nkr
nkr/include/nkr/generic/negatable/integer_tr.h
/* Copyright 2021 r-neal-kelly */ #pragma once #include "nkr/generic/negatable/integer_tr_dec.h" #include "nkr/generic/negatable/integer_tr_def.h"
NoFaceGoose/TabletopGames
src/main/java/games/sushigo/SGForwardModel.java
<reponame>NoFaceGoose/TabletopGames<gh_stars>0 package games.sushigo; import core.AbstractForwardModel; import core.AbstractGameState; import core.CoreConstants; import core.actions.AbstractAction; import core.components.Deck; import games.sushigo.actions.ChopSticksAction; import games.sushigo.actions.NigiriWasabiAction; import games.sushigo.actions.PlayCardAction; import games.sushigo.cards.SGCard; import utilities.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import static java.util.stream.Collectors.joining; public class SGForwardModel extends AbstractForwardModel { @Override protected void _setup(AbstractGameState firstState) { SGGameState SGGS = (SGGameState) firstState; SGParameters parameters = (SGParameters) SGGS.getGameParameters(); //Setup player scores SGGS.playerScore = new int[firstState.getNPlayers()]; SGGS.playerCardPicks = new int[firstState.getNPlayers()]; SGGS.playerExtraCardPicks = new int[firstState.getNPlayers()]; SGGS.playerTempuraAmount = new int[firstState.getNPlayers()]; SGGS.playerSashimiAmount = new int[firstState.getNPlayers()]; SGGS.playerDumplingAmount = new int[firstState.getNPlayers()]; SGGS.playerWasabiAvailable = new int[firstState.getNPlayers()]; SGGS.playerChopSticksAmount = new int[firstState.getNPlayers()]; SGGS.playerScoreToAdd = new int[firstState.getNPlayers()]; SGGS.playerChopsticksActivated = new boolean[firstState.getNPlayers()]; SGGS.playerExtraTurns = new int[firstState.getNPlayers()]; Arrays.fill(SGGS.getPlayerCardPicks(), -1); //Setup draw & discard piles SetupDrawpile(SGGS); SGGS.discardPile = new Deck<SGCard>("Discard pile", CoreConstants.VisibilityMode.VISIBLE_TO_ALL); //Setup player hands and fields SGGS.playerHands = new ArrayList<>(); SGGS.playerFields = new ArrayList<>(); switch (firstState.getNPlayers()) { case 2: SGGS.cardAmount = parameters.cardAmountTwoPlayers; break; case 3: SGGS.cardAmount = parameters.cardAmountThreePlayers; break; case 4: SGGS.cardAmount = parameters.cardAmountFourPlayers; break; case 5: SGGS.cardAmount = parameters.cardAmountFivePlayers; break; } for (int i = 0; i < SGGS.getNPlayers(); i++) { SGGS.playerHands.add(new Deck<SGCard>("Player" + i + " hand", CoreConstants.VisibilityMode.VISIBLE_TO_OWNER)); SGGS.playerFields.add(new Deck<SGCard>("Player" + "Card field", CoreConstants.VisibilityMode.VISIBLE_TO_ALL)); } DrawNewHands(SGGS); SGGS.getTurnOrder().setStartingPlayer(0); } public void DrawNewHands(SGGameState SGGS) { for (int i = 0; i < SGGS.getNPlayers(); i++) { for (int j = 0; j < SGGS.cardAmount; j++) { SGGS.playerHands.get(i).add(SGGS.drawPile.draw()); } } } private void SetupDrawpile(SGGameState SGGS) { SGParameters parameters = (SGParameters) SGGS.getGameParameters(); SGGS.drawPile = new Deck<SGCard>("Draw pile", CoreConstants.VisibilityMode.HIDDEN_TO_ALL); for (int i = 0; i < parameters.nMaki_3Cards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Maki_3)); } for (int i = 0; i < parameters.nMaki_2Cards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Maki_2)); } for (int i = 0; i < parameters.nMaki_1Cards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Maki_1)); } for (int i = 0; i < parameters.nChopstickCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Chopsticks)); } for (int i = 0; i < parameters.nTempuraCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Tempura)); } for (int i = 0; i < parameters.nSashimiCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Sashimi)); } for (int i = 0; i < parameters.nDumplingCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Dumpling)); } for (int i = 0; i < parameters.nSquidNigiriCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.SquidNigiri)); } for (int i = 0; i < parameters.nSalmonNigiriCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.SalmonNigiri)); } for (int i = 0; i < parameters.nEggNigiriCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.EggNigiri)); } for (int i = 0; i < parameters.nWasabiCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Wasabi)); } for (int i = 0; i < parameters.nPuddingCards; i++) { SGGS.drawPile.add(new SGCard(SGCard.SGCardType.Pudding)); } SGGS.drawPile.shuffle(new Random()); } @Override protected void _next(AbstractGameState currentState, AbstractAction action) { if (currentState.getGameStatus() == Utils.GameResult.GAME_END) return; //Perform action action.execute(currentState); //Rotate deck and reveal cards SGGameState SGGS = (SGGameState) currentState; int turn = SGGS.getTurnOrder().getTurnCounter(); if ((turn + 1) % SGGS.getNPlayers() == 0 && SGGS.getPlayerExtraTurns(SGGS.getCurrentPlayer()) <= 0) { RevealCards(SGGS); RemoveUsedChopsticks(SGGS); RotateDecks(SGGS); //Clear points for (int i = 0; i < SGGS.getNPlayers(); i++) { SGGS.setPlayerScoreToAdd(i, 0); } //clear picks Arrays.fill(SGGS.getPlayerCardPicks(), -1); } //Check if game/round over if (IsRoundOver(SGGS) && SGGS.getPlayerExtraTurns(SGGS.getCurrentPlayer()) <= 0) { GiveMakiPoints(SGGS); if (SGGS.getTurnOrder().getRoundCounter() >= 2) { GivePuddingPoints(SGGS); SetWinner(SGGS); currentState.setGameStatus(Utils.GameResult.GAME_END); return; } SGGS.getTurnOrder().endRound(currentState); return; } //End turn if (currentState.getGameStatus() == Utils.GameResult.GAME_ONGOING) { if (SGGS.getPlayerChopSticksActivated(SGGS.getCurrentPlayer()) && SGGS.getPlayerExtraTurns(SGGS.getCurrentPlayer()) > 0) { SGGS.setPlayerExtraTurns(SGGS.getCurrentPlayer(), SGGS.getPlayerExtraTurns(SGGS.getCurrentPlayer()) - 1); return; // if we use chopsticks it is still our go, so don't end player turn } //reset chopstick activation and end turn currentState.getTurnOrder().endPlayerTurn(currentState); } } private void RemoveUsedChopsticks(SGGameState SGGS) { for (int i = 0; i < SGGS.getNPlayers(); i++) { if (SGGS.getPlayerChopSticksActivated(i)) { for (int j = 0; j < SGGS.getPlayerFields().get(i).getSize(); j++) { if (SGGS.getPlayerFields().get(i).get(j).type == SGCard.SGCardType.Chopsticks) { SGGS.getPlayerFields().get(i).remove(j); SGGS.setPlayerChopSticksAmount(i, SGGS.getPlayerChopSticksAmount(i) - 1); break; } } SGGS.getPlayerDecks().get(i).add(new SGCard(SGCard.SGCardType.Chopsticks)); SGGS.setPlayerChopsticksActivated(i, false); } } } private void SetWinner(SGGameState SGGS) { int currentBestScore = 0; List<Integer> winners = new ArrayList<>(); for (int i = 0; i < SGGS.getNPlayers(); i++) { if (SGGS.getGameScore(i) > currentBestScore) { currentBestScore = (int) SGGS.getGameScore(i); winners.clear(); winners.add(i); } else if (SGGS.getGameScore(i) == currentBestScore) winners.add(i); } //More than 1 winner, check pudding amount if (winners.size() > 1) { List<Integer> trueWinners = new ArrayList<>(); int bestPuddingScore = 0; for (int i = 0; i < winners.size(); i++) { if (GetPuddingAmount(winners.get(i), SGGS) > bestPuddingScore) { bestPuddingScore = GetPuddingAmount(winners.get(i), SGGS); trueWinners.clear(); trueWinners.add(winners.get(i)); } else if (GetPuddingAmount(winners.get(i), SGGS) == bestPuddingScore) trueWinners.add(winners.get(i)); } if (trueWinners.size() > 1) { for (int i = 0; i < SGGS.getNPlayers(); i++) { SGGS.setPlayerResult(Utils.GameResult.LOSE, i); } for (int i = 0; i < trueWinners.size(); i++) { SGGS.setPlayerResult(Utils.GameResult.DRAW, trueWinners.get(i)); } } else { for (int i = 0; i < SGGS.getNPlayers(); i++) { SGGS.setPlayerResult(Utils.GameResult.LOSE, i); } SGGS.setPlayerResult(Utils.GameResult.WIN, trueWinners.get(0)); } } else { for (int i = 0; i < SGGS.getNPlayers(); i++) { SGGS.setPlayerResult(Utils.GameResult.LOSE, i); } SGGS.setPlayerResult(Utils.GameResult.WIN, winners.get(0)); } } private int GetPuddingAmount(int playerId, SGGameState SGGS) { int amount = 0; for (int i = 0; i < SGGS.getPlayerFields().get(playerId).getSize(); i++) { if (SGGS.getPlayerFields().get(playerId).get(i).type == SGCard.SGCardType.Pudding) amount++; } return amount; } private void GiveMakiPoints(SGGameState SGGS) { //Calculate maki points for each player int[] makiPlayerPoints = new int[SGGS.getNPlayers()]; for (int i = 0; i < SGGS.getNPlayers(); i++) { for (int j = 0; j < SGGS.getPlayerFields().get(i).getSize(); j++) { switch (SGGS.getPlayerFields().get(i).get(j).type) { case Maki_1: makiPlayerPoints[i] += 1; break; case Maki_2: makiPlayerPoints[i] += 2; break; case Maki_3: makiPlayerPoints[i] += 3; break; default: break; } } } //Calculate who has the most points and who has the second most points int currentBest = 0; int secondBest = 0; List<Integer> mostPlayers = new ArrayList<>(); List<Integer> secondPlayers = new ArrayList<>(); for (int i = 0; i < makiPlayerPoints.length; i++) { if (makiPlayerPoints[i] > currentBest) { secondBest = currentBest; secondPlayers.clear(); secondPlayers.addAll(mostPlayers); currentBest = makiPlayerPoints[i]; mostPlayers.clear(); mostPlayers.add(i); } else if (makiPlayerPoints[i] == currentBest) mostPlayers.add(i); else if (makiPlayerPoints[i] > secondBest) { secondBest = makiPlayerPoints[i]; secondPlayers.clear(); secondPlayers.add(i); } else if (makiPlayerPoints[i] == secondBest) secondPlayers.add(i); } //Calculate the score each player gets SGParameters parameters = (SGParameters) SGGS.getGameParameters(); int mostScore = parameters.valueMakiMost; int secondScore = parameters.valueMakiSecond; if (!mostPlayers.isEmpty()) mostScore /= mostPlayers.size(); if (!secondPlayers.isEmpty()) secondScore /= secondPlayers.size(); //Add score to players if (currentBest != 0) { for (int i = 0; i < mostPlayers.size(); i++) { SGGS.setGameScore(mostPlayers.get(i), (int) SGGS.getGameScore(mostPlayers.get(i)) + mostScore); } } if (secondBest != 0) { for (int i = 0; i < secondPlayers.size(); i++) { SGGS.setGameScore(secondPlayers.get(i), (int) SGGS.getGameScore(secondPlayers.get(i)) + secondScore); } } } private void GivePuddingPoints(SGGameState SGGS) { //Calculate maki points for each player int[] puddingPlayerPoints = new int[SGGS.getNPlayers()]; for (int i = 0; i < SGGS.getNPlayers(); i++) { for (int j = 0; j < SGGS.getPlayerFields().get(i).getSize(); j++) { switch (SGGS.getPlayerFields().get(i).get(j).type) { case Pudding: puddingPlayerPoints[i] += 3; break; default: break; } } } //Calculate who has the most points and who has the second most points SGParameters parameters = (SGParameters) SGGS.getGameParameters(); int currentBest = 0; int currentWorst = parameters.nPuddingCards + 1; List<Integer> mostPlayers = new ArrayList<>(); List<Integer> leastPlayers = new ArrayList<>(); for (int i = 0; i < puddingPlayerPoints.length; i++) { if (puddingPlayerPoints[i] > currentBest) { currentBest = puddingPlayerPoints[i]; mostPlayers.clear(); mostPlayers.add(i); } else if (puddingPlayerPoints[i] == currentBest) mostPlayers.add(i); else currentWorst = puddingPlayerPoints[i]; } if (currentBest > currentWorst) { for (int i = 0; i < puddingPlayerPoints.length; i++) { if (puddingPlayerPoints[i] < currentWorst) { currentWorst = puddingPlayerPoints[i]; leastPlayers.clear(); leastPlayers.add(i); } else if (puddingPlayerPoints[i] == currentWorst) leastPlayers.add(i); } } //Calculate the score each player gets int mostScore = parameters.valuePuddingMost; int leastScore = parameters.valuePuddingLeast; if (!mostPlayers.isEmpty()) mostScore /= mostPlayers.size(); if (!leastPlayers.isEmpty()) leastScore /= leastPlayers.size(); //Add score to players if (currentBest != 0) { for (int i = 0; i < mostPlayers.size(); i++) { SGGS.setGameScore(mostPlayers.get(i), (int) SGGS.getGameScore(mostPlayers.get(i)) + mostScore); } } for (int i = 0; i < leastPlayers.size(); i++) { SGGS.setGameScore(leastPlayers.get(i), (int) SGGS.getGameScore(leastPlayers.get(i)) + leastScore); } } boolean IsRoundOver(SGGameState SGGS) { for (int i = 0; i < SGGS.getPlayerDecks().size(); i++) { if (SGGS.getPlayerDecks().get(i).getSize() > 0) return false; } return true; } void RevealCards(SGGameState SGGS) { for (int i = 0; i < SGGS.getNPlayers(); i++) { //Moves the card from the players hand to field if (SGGS.getPlayerCardPicks()[i] < 0) SGGS.setPlayerCardPick(0, i); if (SGGS.getPlayerDecks().get(i).getSize() <= SGGS.getPlayerCardPicks()[i]) continue; SGCard cardToReveal = SGGS.getPlayerDecks().get(i).get(SGGS.getPlayerCardPicks()[i]); SGGS.getPlayerDecks().get(i).remove(cardToReveal); SGGS.getPlayerFields().get(i).add(cardToReveal); if (SGGS.getPlayerChopSticksActivated(i)) { if (SGGS.getPlayerCardPicks()[i] < SGGS.getPlayerExtraCardPicks()[i]) SGGS.setPlayerExtraCardPick(SGGS.getPlayerExtraCardPicks()[i] - 1, i); if (SGGS.getPlayerDecks().get(i).getSize() > SGGS.getPlayerExtraCardPicks()[i]) { SGCard extraCardToReveal = SGGS.getPlayerDecks().get(i).get(SGGS.getPlayerExtraCardPicks()[i]); SGGS.getPlayerDecks().get(i).remove(extraCardToReveal); SGGS.getPlayerFields().get(i).add(extraCardToReveal); } } //Add points to player SGGS.setGameScore(i, (int) SGGS.getGameScore(i) + SGGS.getPlayerScoreToAdd(i)); } } void RotateDecks(SGGameState SGGS) { SGGS.deckRotations++; Deck<SGCard> tempDeck; tempDeck = SGGS.getPlayerDecks().get(0).copy(); for (int i = 1; i < SGGS.getNPlayers(); i++) { SGGS.getPlayerDecks().set(i - 1, SGGS.getPlayerDecks().get(i).copy()); } SGGS.getPlayerDecks().set(SGGS.getNPlayers() - 1, tempDeck.copy()); } @Override protected List<AbstractAction> _computeAvailableActions(AbstractGameState gameState) { SGGameState SGGS = (SGGameState) gameState; List<AbstractAction> actions = new ArrayList<>(); Deck<SGCard> currentPlayerHand = SGGS.getPlayerDecks().get(SGGS.getCurrentPlayer()); for (int i = 0; i < currentPlayerHand.getSize(); i++) { if (SGGS.getPlayerCardPicks()[SGGS.getCurrentPlayer()] == i) continue; switch (currentPlayerHand.get(i).type) { case Maki_1: case Maki_2: case Maki_3: case Tempura: case Sashimi: case Dumpling: case Wasabi: case Chopsticks: case Pudding: actions.add(new PlayCardAction(SGGS.getCurrentPlayer(), currentPlayerHand.get(i).type)); break; case SquidNigiri: case SalmonNigiri: case EggNigiri: actions.add(new PlayCardAction(SGGS.getCurrentPlayer(), currentPlayerHand.get(i).type)); if (SGGS.getPlayerWasabiAvailable(SGGS.getCurrentPlayer()) > 0) actions.add(new NigiriWasabiAction(SGGS.getCurrentPlayer(), currentPlayerHand.get(i).type)); break; } } // remove duplicate actions actions = actions.stream().distinct().collect(Collectors.toList()); if (SGGS.getPlayerChopSticksAmount(SGGS.getCurrentPlayer()) > 0 && !SGGS.getPlayerChopSticksActivated(SGGS.getCurrentPlayer()) && SGGS.getPlayerDecks().get(SGGS.getCurrentPlayer()).getSize() > 1) { actions.add(new ChopSticksAction(SGGS.getCurrentPlayer())); } return actions; } @Override protected AbstractForwardModel _copy() { return new SGForwardModel(); } }
concord-consortium/rigse
rails/db/migrate/20090601220838_otml_files_otrunk_view_entries.rb
<reponame>concord-consortium/rigse class OtmlFilesOtrunkViewEntries < ActiveRecord::Migration[5.1] def self.up create_table :otml_files_otrunk_view_entries, :id => false do |t| t.integer :otml_file_id t.integer :otrunk_view_entry_id end add_index :otml_files_otrunk_view_entries, [:otml_file_id, :otrunk_view_entry_id], :name => :otf_otve, :unique => true end def self.down drop_table :otml_files_otrunk_view_entries end end
GregorR/plof3
cplof/src/impl/float.c
<reponame>GregorR/plof3 label(interp_psl_float); UNIMPL("psl_float");
Kymed/qstudy
client/src/components/profiles/ProfileAlertHandler.js
<filename>client/src/components/profiles/ProfileAlertHandler.js import React, {Fragment, useEffect, useContext } from 'react'; import io from "socket.io-client"; import ProfileContext from '../../context/profiles/profileContext'; import AlertContext from '../../context/alert/alertContext'; const ProfileAlertHandler = () => { const profileContext = useContext(ProfileContext); const alertContext = useContext(AlertContext); const { prompt, error, notification, clearPrompt, clearErrors, clearNotifications } = profileContext; const { setAlert } = alertContext; useEffect(() => { if (notification !== null) { setAlert(notification, 'success'); clearNotifications(); } if (prompt !== null) { setAlert(prompt, 'success'); clearPrompt(); } if (error !== null) { if (Array.isArray(error)) { error.forEach(err => setAlert(err, 'danger')); } else { setAlert(error, 'danger'); } clearErrors(); } }, [error, prompt, notification]); return ( <Fragment> </Fragment> ) } export default ProfileAlertHandler;
sarang-apps/darshan_browser
third_party/blink/web_tests/http/tests/devtools/network/network-initiator-from-console.js
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (async function() { TestRunner.addResult(`Tests that there is no javascript error when console evaluation causes resource loading.\n`); await TestRunner.loadModule('network_test_runner'); await TestRunner.showPanel('network'); TestRunner.reloadPage(step1); function step1() { TestRunner.networkManager.addEventListener(SDK.NetworkManager.Events.RequestStarted, onRequest); var str = ''; str += 'var s = document.createElement("script");'; str += 's.src = "resources/silent_script.js";'; str += 'document.head.appendChild(s);'; UI.context.flavor(SDK.ExecutionContext).evaluate({expression: str, objectGroup: 'console'}); } function onRequest(event) { var request = event.data; if (/silent_script.js/.test(request.url())) step2(); } function step2() { var results = NetworkTestRunner.findRequestsByURLPattern(/silent_script.js/); if (results.length === 0) return; TestRunner.completeTest(); } })();
parameter1/cms-apis
apis/rest/src/graphql/directives/linkage.js
/* eslint-disable no-param-reassign */ import { mapSchema, getDirective, MapperKind } from '@cms-apis/graphql/utils'; import createResolver from './linkage/create-resolver.js'; import getReturnType from '../utils/get-return-type.js'; export default function linkageDirectiveTransformer(schema, directiveName = 'linkage') { return mapSchema(schema, { [MapperKind.OBJECT_FIELD]: (fieldConfig) => { const directive = getDirective(schema, fieldConfig, directiveName); const args = directive && directive[0] ? directive[0] : null; const { astNode } = fieldConfig; if (args && astNode) { const returnType = getReturnType(fieldConfig.type); if (!/^Link(One|Many)$/.test(returnType.name)) { throw new Error('Unexptected return type encountered. Expected a LinkOne or LinkMany object.'); } const ref = returnType.name === 'LinkOne' ? 'ONE' : 'MANY'; const field = args.field || astNode.name.value; if (!field) throw new Error('No target linkage field was provided.'); const target = ref === 'ONE' ? `_edge.${field}` : `_connection.${field}`; if (!args.empty) astNode.$project = { [target]: 1 }; const linkage = { ...args, field, target, ref, }; astNode.$linkage = linkage; if (!fieldConfig.resolve) fieldConfig.resolve = createResolver(linkage); } }, }); }
newbigTech/im
dal/src/main/java/com/newbig/im/dal/model/SysUserRole.java
package com.newbig.im.dal.model; import javax.persistence.*; import java.util.Date; @Table(name = "sys_user_role") public class SysUserRole { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * user_id */ @Column(name = "user_id") private String userId; /** * 角色id */ @Column(name = "role_id") private String roleId; @Column(name = "gmt_create") private Date gmtCreate; @Column(name = "gmt_modify") private Date gmtModify; private String creator; private String modifier; @Column(name = "is_deleted") private Boolean isDeleted; /** * 有权限的组织id */ @Column(name = "privilege_org_ids") private String privilegeOrgIds; /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * 获取user_id * * @return user_id - user_id */ public String getUserId() { return userId; } /** * 设置user_id * * @param userId user_id */ public void setUserId(String userId) { this.userId = userId; } /** * 获取角色id * * @return role_id - 角色id */ public String getRoleId() { return roleId; } /** * 设置角色id * * @param roleId 角色id */ public void setRoleId(String roleId) { this.roleId = roleId; } /** * @return gmt_create */ public Date getGmtCreate() { return gmtCreate; } /** * @param gmtCreate */ public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } /** * @return gmt_modify */ public Date getGmtModify() { return gmtModify; } /** * @param gmtModify */ public void setGmtModify(Date gmtModify) { this.gmtModify = gmtModify; } /** * @return creator */ public String getCreator() { return creator; } /** * @param creator */ public void setCreator(String creator) { this.creator = creator; } /** * @return modifier */ public String getModifier() { return modifier; } /** * @param modifier */ public void setModifier(String modifier) { this.modifier = modifier; } /** * @return is_deleted */ public Boolean getIsDeleted() { return isDeleted; } /** * @param isDeleted */ public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } /** * 获取有权限的组织id * * @return privilege_org_ids - 有权限的组织id */ public String getPrivilegeOrgIds() { return privilegeOrgIds; } /** * 设置有权限的组织id * * @param privilegeOrgIds 有权限的组织id */ public void setPrivilegeOrgIds(String privilegeOrgIds) { this.privilegeOrgIds = privilegeOrgIds; } }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-s3control/include/aws/s3control/model/MultiRegionAccessPointReport.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/s3control/S3Control_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/DateTime.h> #include <aws/s3control/model/PublicAccessBlockConfiguration.h> #include <aws/s3control/model/MultiRegionAccessPointStatus.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/s3control/model/RegionReport.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace S3Control { namespace Model { /** * <p>A collection of statuses for a Multi-Region Access Point in the various * Regions it supports.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/MultiRegionAccessPointReport">AWS * API Reference</a></p> */ class AWS_S3CONTROL_API MultiRegionAccessPointReport { public: MultiRegionAccessPointReport(); MultiRegionAccessPointReport(const Aws::Utils::Xml::XmlNode& xmlNode); MultiRegionAccessPointReport& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const; /** * <p>The name of the Multi-Region Access Point.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the Multi-Region Access Point.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the Multi-Region Access Point.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the Multi-Region Access Point.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the Multi-Region Access Point.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the Multi-Region Access Point.</p> */ inline MultiRegionAccessPointReport& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the Multi-Region Access Point.</p> */ inline MultiRegionAccessPointReport& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the Multi-Region Access Point.</p> */ inline MultiRegionAccessPointReport& WithName(const char* value) { SetName(value); return *this;} /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline const Aws::String& GetAlias() const{ return m_alias; } /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline bool AliasHasBeenSet() const { return m_aliasHasBeenSet; } /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline void SetAlias(const Aws::String& value) { m_aliasHasBeenSet = true; m_alias = value; } /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline void SetAlias(Aws::String&& value) { m_aliasHasBeenSet = true; m_alias = std::move(value); } /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline void SetAlias(const char* value) { m_aliasHasBeenSet = true; m_alias.assign(value); } /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline MultiRegionAccessPointReport& WithAlias(const Aws::String& value) { SetAlias(value); return *this;} /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline MultiRegionAccessPointReport& WithAlias(Aws::String&& value) { SetAlias(std::move(value)); return *this;} /** * <p>The alias for the Multi-Region Access Point. For more information about the * distinction between the name and the alias of an Multi-Region Access Point, see * <a * href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingMultiRegionAccessPoints.html#multi-region-access-point-naming">Managing * Multi-Region Access Points</a>.</p> */ inline MultiRegionAccessPointReport& WithAlias(const char* value) { SetAlias(value); return *this;} /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; } /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; } /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; } /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); } /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline MultiRegionAccessPointReport& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;} /** * <p>When the Multi-Region Access Point create request was received.</p> */ inline MultiRegionAccessPointReport& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;} inline const PublicAccessBlockConfiguration& GetPublicAccessBlock() const{ return m_publicAccessBlock; } inline bool PublicAccessBlockHasBeenSet() const { return m_publicAccessBlockHasBeenSet; } inline void SetPublicAccessBlock(const PublicAccessBlockConfiguration& value) { m_publicAccessBlockHasBeenSet = true; m_publicAccessBlock = value; } inline void SetPublicAccessBlock(PublicAccessBlockConfiguration&& value) { m_publicAccessBlockHasBeenSet = true; m_publicAccessBlock = std::move(value); } inline MultiRegionAccessPointReport& WithPublicAccessBlock(const PublicAccessBlockConfiguration& value) { SetPublicAccessBlock(value); return *this;} inline MultiRegionAccessPointReport& WithPublicAccessBlock(PublicAccessBlockConfiguration&& value) { SetPublicAccessBlock(std::move(value)); return *this;} /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline const MultiRegionAccessPointStatus& GetStatus() const{ return m_status; } /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; } /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline void SetStatus(const MultiRegionAccessPointStatus& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline void SetStatus(MultiRegionAccessPointStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); } /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline MultiRegionAccessPointReport& WithStatus(const MultiRegionAccessPointStatus& value) { SetStatus(value); return *this;} /** * <p>The current status of the Multi-Region Access Point.</p> <p> * <code>CREATING</code> and <code>DELETING</code> are temporary states that exist * while the request is propogating and being completed. If a Multi-Region Access * Point has a status of <code>PARTIALLY_CREATED</code>, you can retry creation or * send a request to delete the Multi-Region Access Point. If a Multi-Region Access * Point has a status of <code>PARTIALLY_DELETED</code>, you can retry a delete * request to finish the deletion of the Multi-Region Access Point.</p> */ inline MultiRegionAccessPointReport& WithStatus(MultiRegionAccessPointStatus&& value) { SetStatus(std::move(value)); return *this;} /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline const Aws::Vector<RegionReport>& GetRegions() const{ return m_regions; } /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline bool RegionsHasBeenSet() const { return m_regionsHasBeenSet; } /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline void SetRegions(const Aws::Vector<RegionReport>& value) { m_regionsHasBeenSet = true; m_regions = value; } /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline void SetRegions(Aws::Vector<RegionReport>&& value) { m_regionsHasBeenSet = true; m_regions = std::move(value); } /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline MultiRegionAccessPointReport& WithRegions(const Aws::Vector<RegionReport>& value) { SetRegions(value); return *this;} /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline MultiRegionAccessPointReport& WithRegions(Aws::Vector<RegionReport>&& value) { SetRegions(std::move(value)); return *this;} /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline MultiRegionAccessPointReport& AddRegions(const RegionReport& value) { m_regionsHasBeenSet = true; m_regions.push_back(value); return *this; } /** * <p>A collection of the Regions and buckets associated with the Multi-Region * Access Point.</p> */ inline MultiRegionAccessPointReport& AddRegions(RegionReport&& value) { m_regionsHasBeenSet = true; m_regions.push_back(std::move(value)); return *this; } private: Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_alias; bool m_aliasHasBeenSet; Aws::Utils::DateTime m_createdAt; bool m_createdAtHasBeenSet; PublicAccessBlockConfiguration m_publicAccessBlock; bool m_publicAccessBlockHasBeenSet; MultiRegionAccessPointStatus m_status; bool m_statusHasBeenSet; Aws::Vector<RegionReport> m_regions; bool m_regionsHasBeenSet; }; } // namespace Model } // namespace S3Control } // namespace Aws
VitaliiHrushyn/JavaExternalClasses_Final_Project
RepairAgency/src/main/java/ua/training/repairagency/model/dao/interfaces/ApplicationDAO.java
<reponame>VitaliiHrushyn/JavaExternalClasses_Final_Project<filename>RepairAgency/src/main/java/ua/training/repairagency/model/dao/interfaces/ApplicationDAO.java package ua.training.repairagency.model.dao.interfaces; import java.util.List; import ua.training.repairagency.model.entities.application.Application; public interface ApplicationDAO extends GenericDAO<Application> { List<Application> getAllByQueryWithLimitAndOffset(String query, String... values); int coutnRowsByQuery(String query, String... values); }
luongnvUIT/prowide-iso20022
model-seev-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CancellationStatus26Choice.java
<reponame>luongnvUIT/prowide-iso20022 package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Status applying to the instruction cancellation request received. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CancellationStatus26Choice", propOrder = { "prcgSts", "rjctd", "pdgCxl" }) public class CancellationStatus26Choice { @XmlElement(name = "PrcgSts") protected CancellationProcessingStatus2 prcgSts; @XmlElement(name = "Rjctd") protected RejectedStatus31Choice rjctd; @XmlElement(name = "PdgCxl") protected PendingCancellationStatus10Choice pdgCxl; /** * Gets the value of the prcgSts property. * * @return * possible object is * {@link CancellationProcessingStatus2 } * */ public CancellationProcessingStatus2 getPrcgSts() { return prcgSts; } /** * Sets the value of the prcgSts property. * * @param value * allowed object is * {@link CancellationProcessingStatus2 } * */ public CancellationStatus26Choice setPrcgSts(CancellationProcessingStatus2 value) { this.prcgSts = value; return this; } /** * Gets the value of the rjctd property. * * @return * possible object is * {@link RejectedStatus31Choice } * */ public RejectedStatus31Choice getRjctd() { return rjctd; } /** * Sets the value of the rjctd property. * * @param value * allowed object is * {@link RejectedStatus31Choice } * */ public CancellationStatus26Choice setRjctd(RejectedStatus31Choice value) { this.rjctd = value; return this; } /** * Gets the value of the pdgCxl property. * * @return * possible object is * {@link PendingCancellationStatus10Choice } * */ public PendingCancellationStatus10Choice getPdgCxl() { return pdgCxl; } /** * Sets the value of the pdgCxl property. * * @param value * allowed object is * {@link PendingCancellationStatus10Choice } * */ public CancellationStatus26Choice setPdgCxl(PendingCancellationStatus10Choice value) { this.pdgCxl = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
kapeels/ohmage-server
src/org/ohmage/query/impl/AbstractUploadQuery.java
/******************************************************************************* * Copyright 2012 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.ohmage.query.impl; import java.sql.SQLException; import javax.sql.DataSource; /** * Abstract base class for any 'upload' Query that needs to manage duplicate * uploads. * * @author <NAME> */ public class AbstractUploadQuery extends Query { private static final int MYSQL_DUPLICATE_KEY_ERROR_CODE = 1062; /** * Creates this object. * * @param dataSource The DataSource to use when querying the database. */ public AbstractUploadQuery(DataSource dataSource) { super(dataSource); } /** * @return true if the Throwable represents an SQLException and the error code in the SQLException is 1062 (the MySQL error * code for dupes). * @return false otherwise */ protected boolean isDuplicate(Throwable t) { return (t.getCause() instanceof SQLException) && (((SQLException) t.getCause()).getErrorCode() == MYSQL_DUPLICATE_KEY_ERROR_CODE); } }
docfetcher/DocFetcher
src/net/sourceforge/docfetcher/model/parse/VorbisComment.java
<reponame>docfetcher/DocFetcher package net.sourceforge.docfetcher.model.parse; import java.io.DataInputStream; import java.io.IOException; /** * This class is created because several media formats * use the Vorbis Comment specification for metadata. * * @author psiahu */ public class VorbisComment { long bigToLittleEndianInteger(long bigEndian) { long byte0 = (bigEndian >> 24) & 0xFF; long byte1 = (bigEndian >> 16) & 0xFF; long byte2 = (bigEndian >> 8) & 0xFF; long byte3 = bigEndian & 0xFF; long littleEndian = byte0 | (byte1 << 8) | (byte2 << 16) | (byte3 << 24); return littleEndian; } void parse(DataInputStream dis, StringBuffer sb, boolean forViewing) throws IOException { // vendor_length long size = bigToLittleEndianInteger(dis.readInt()); // vendor string dis.skipBytes((int)size); // user_comment_list_length long commentCount = bigToLittleEndianInteger(dis.readInt()); // 100 is a safe-guard number to prevent an infinite loop due to corrupted data stream commentCount = Math.min(commentCount, 100); for (int i = 0; i < commentCount; i++) { // length long commentSize = bigToLittleEndianInteger(dis.readInt()); // This is another safe-guard against data corruption // If commentSize is too big we can run out of memory when reading comment to String if (commentSize > 100000) { dis.skipBytes((int)commentSize); continue; } byte[] comment = new byte[(int)commentSize]; dis.readFully(comment); String entry = new String(comment); if (forViewing == false) { String[] cells = entry.split("="); if (cells != null && cells.length >= 2) { entry = cells[1]; } } sb.append(entry + "\n"); } } }
amakid/go-ruleguard
analyzer/testdata/src/regression/issue360.go
package regression import "strings" func _(s1, s2 string) { _ = map[int]int{ strings.Compare("", ""): 0, // want `\Qdon't use strings.Compare` } _ = map[int]int{ 10: strings.Compare("", ""), // want `\Qdon't use strings.Compare` } _ = map[int]string{ 10: "a", strings.Compare(s1, s2): s2, // want `\Qdon't use strings.Compare` 20: "b", } _ = map[int]string{ 10: "a", 20: "b", strings.Compare(s1, s2): s2, // want `\Qdon't use strings.Compare` } _ = map[int]string{ strings.Compare(s1, s2): s2, // want `\Qdon't use strings.Compare` 10: "a", 20: "b", } }
GMHe/compose-parent
compose-sync/src/main/java/cn/compose/sync/canal/app/ActionByEventType.java
package cn.compose.sync.canal.app; import cn.compose.sync.canal.event.EventInfo; import cn.compose.sync.canal.service.IEventHandler; /** * 根据数据库+表名+事件类型 产生handler 抽象接口层 * @author maowei * @package_name com.vlinklink.sync.app * @date 2020/9/7 * @time 15:14 */ public interface ActionByEventType { IEventHandler createHandlerByEventType(EventInfo info); }
mnurzia/lsx
ext/pdjson.c
#include <ctype.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "pdjson.h" #define JSON_FLAG_ERROR (1u << 0) struct json_stack { enum json_type type; long count; }; /* Since errmsg is filled with sprintf(), it must never be filled with * unbounded input data (e.g. %s). */ static void json_error(struct json_stream *json, const char *fmt, ...) { if (!(json->flags & JSON_FLAG_ERROR)) { va_list ap; char *p = json->errmsg; json->flags |= JSON_FLAG_ERROR; p += sprintf(p, "error: %lu: ", (unsigned long)json->lineno); va_start(ap, fmt); vsprintf(p, fmt, ap); va_end(ap); } } static enum json_type push(struct json_stream *json, enum json_type type) { json->stack_top++; if (json->stack_top >= json->stack_size) { struct json_stack *stack; size_t size = json->stack_size ? json->stack_size * 2 : 8; stack = json->alloc(json->stack, size * sizeof(*json->stack), json->alloc_arg); if (!stack) { json_error(json, "out of memory"); return JSON_ERROR; } json->stack_size = size; json->stack = stack; } json->stack[json->stack_top].type = type; json->stack[json->stack_top].count = 0; return type; } static enum json_type pop(struct json_stream *json, int c, enum json_type expected) { if (json->stack == NULL || json->stack[json->stack_top].type != expected) { json_error(json, "unexpected byte, '%c'", c); return JSON_ERROR; } json->stack_top--; return expected == JSON_ARRAY ? JSON_ARRAY_END : JSON_OBJECT_END; } static int json_io_get(struct json_stream *json) { int c; if (json->peek >= -1) { c = json->peek; json->peek = -2; } else { c = json->fgetc(json->fgetc_arg); if (c < 0) c = -1; else json->position++; /* FIXME */ } return c; } static int json_io_peek(struct json_stream *json) { if (json->peek >= -1) return json->peek; return (json->peek = json_io_get(json)); } static enum json_type is_match(struct json_stream *json, const char *pattern, enum json_type type) { const char *p; for (p = pattern; *p; p++) if (*p != json_io_get(json)) return JSON_ERROR; return type; } static int pushchar(struct json_stream *json, int c) { if (json->data.string_fill == json->data.string_size) { size_t size = json->data.string_size * 2; char *buffer = json->alloc(json->data.string, size, json->alloc_arg); if (buffer == NULL) { json_error(json, "out of memory"); return -1; } else { json->data.string_size = size; json->data.string = buffer; } } json->data.string[json->data.string_fill++] = c; return 0; } static int init_string(struct json_stream *json) { json->data.string_fill = 0; if (json->data.string == NULL) { json->data.string_size = 1024; json->data.string = json->alloc(0, json->data.string_size, json->alloc_arg); if (json->data.string == NULL) { json_error(json, "out of memory"); return -1; } } json->data.string[0] = '\0'; return 0; } static int encode_utf8(struct json_stream *json, unsigned long c) { if (c < 0x80UL) { return pushchar(json, c); } else if (c < 0x0800UL) { return !((pushchar(json, (c >> 6 & 0x1F) | 0xC0) == 0) && (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); } else if (c < 0x010000UL) { if (c >= 0xd800 && c <= 0xdfff) { json_error(json, "invalid codepoint %06lx", c); return -1; } return !((pushchar(json, (c >> 12 & 0x0F) | 0xE0) == 0) && (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); } else if (c < 0x110000UL) { return !((pushchar(json, (c >> 18 & 0x07) | 0xF0) == 0) && (pushchar(json, (c >> 12 & 0x3F) | 0x80) == 0) && (pushchar(json, (c >> 6 & 0x3F) | 0x80) == 0) && (pushchar(json, (c >> 0 & 0x3F) | 0x80) == 0)); } else { json_error(json, "can't encode UTF-8 for %06lx", c); return -1; } } static int hexchar(int c) { switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return -1; } } static long read_unicode_cp(struct json_stream *json) { size_t i; long cp = 0; int shift = 12; for (i = 0; i < 4; i++) { int c = json_io_get(json); int hc; if (c == -1) { json_error(json, "%s", "unterminated string literal in unicode"); return -1; } else if ((hc = hexchar(c)) == -1) { json_error(json, "bad escape unicode byte, '%c'", c); return -1; } cp += hc * (1 << shift); shift -= 4; } return cp; } static int read_unicode(struct json_stream *json) { long cp, h, l; if ((cp = read_unicode_cp(json)) == -1) { return -1; } if (cp >= 0xd800 && cp <= 0xdbff) { int c; /* This is the high portion of a surrogate pair; we need to read the * lower portion to get the codepoint */ h = cp; c = json_io_get(json); if (c == -1) { json_error(json, "%s", "unterminated string literal in unicode"); return -1; } else if (c != '\\') { json_error(json, "invalid continuation for surrogate pair: '%c', " "expected '\\'", c); return -1; } c = json_io_get(json); if (c == -1) { json_error(json, "%s", "unterminated string literal in unicode"); return -1; } else if (c != 'u') { json_error(json, "invalid continuation for surrogate pair: '%c', " "expected 'u'", c); return -1; } if ((l = read_unicode_cp(json)) == -1) { return -1; } if (l < 0xdc00 || l > 0xdfff) { json_error(json, "invalid surrogate pair continuation \\u%04lx out " "of range (dc00-dfff)", l); return -1; } cp = ((h - 0xd800) * 0x400) + ((l - 0xdc00) + 0x10000); } else if (cp >= 0xdc00 && cp <= 0xdfff) { json_error(json, "dangling surrogate \\u%04lx", cp); return -1; } return encode_utf8(json, cp); } static int read_escaped(struct json_stream *json) { int c = json_io_get(json); if (c == -1) { json_error(json, "%s", "unterminated string literal in escape"); return -1; } else if (c == 'u') { if (read_unicode(json) != 0) return -1; } else { switch (c) { case '\\': case 'b': case 'f': case 'n': case 'r': case 't': case '/': case '"': { const char *codes = "\\bfnrt/\""; const char *p = strchr(codes, c); if (pushchar(json, "\\\b\f\n\r\t/\""[p - codes]) != 0) return -1; } break; default: json_error(json, "bad escaped byte, '%c'", c); return -1; } } return 0; } static int char_needs_escaping(int c) { if ((c >= 0) && (c < 0x20 || c == 0x22 || c == 0x5c)) { return 1; } return 0; } static int utf8_seq_length(char byte) { unsigned char u = byte; if (u < 0x80) return 1; if (0x80 <= u && u <= 0xBF) { /* second, third or fourth byte of a multi-byte * sequence, i.e. a "continuation byte" */ return 0; } else if (u == 0xC0 || u == 0xC1) { /* overlong encoding of an ASCII byte */ return 0; } else if (0xC2 <= u && u <= 0xDF) { /* 2-byte sequence */ return 2; } else if (0xE0 <= u && u <= 0xEF) { /* 3-byte sequence */ return 3; } else if (0xF0 <= u && u <= 0xF4) { /* 4-byte sequence */ return 4; } else { /* u >= 0xF5 * Restricted (start of 4-, 5- or 6-byte sequence) or invalid UTF-8 */ return 0; } } static int is_legal_utf8(const unsigned char *bytes, int length) { unsigned char a; const unsigned char *srcptr; if (0 == bytes || 0 == length) return 0; srcptr = bytes + length; switch (length) { default: return 0; /* Everything else falls through when true. */ case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; /* FALLTHROUGH */ case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; /* FALLTHROUGH */ case 2: a = (*--srcptr); switch (*bytes) { case 0xE0: if (a < 0xA0 || a > 0xBF) return 0; break; case 0xED: if (a < 0x80 || a > 0x9F) return 0; break; case 0xF0: if (a < 0x90 || a > 0xBF) return 0; break; case 0xF4: if (a < 0x80 || a > 0x8F) return 0; break; default: if (a < 0x80 || a > 0xBF) return 0; } /* FALLTHROUGH */ case 1: if (*bytes >= 0x80 && *bytes < 0xC2) return 0; } return *bytes <= 0xF4; } static int read_utf8(struct json_stream *json, int next_char) { int i; unsigned char buffer[4]; int count = utf8_seq_length(next_char); if (!count) { json_error(json, "%s", "Bad character."); return -1; } buffer[0] = next_char; for (i = 1; i < count; ++i) buffer[i] = json_io_get(json); if (!is_legal_utf8(buffer, count)) { json_error(json, "%s", "No legal UTF8 found"); return -1; } for (i = 0; i < count; ++i) if (pushchar(json, buffer[i]) != 0) return -1; return 0; } static enum json_type read_string(struct json_stream *json) { if (init_string(json) != 0) return JSON_ERROR; for (;;) { int c = json_io_get(json); if (c == -1) { json_error(json, "%s", "unterminated string literal"); return JSON_ERROR; } else if (c == '"') { if (pushchar(json, '\0') == 0) return JSON_STRING; else return JSON_ERROR; } else if (c == '\\') { if (read_escaped(json) != 0) return JSON_ERROR; } else if ((unsigned) c >= 0x80) { if (read_utf8(json, c) != 0) return JSON_ERROR; } else { if (char_needs_escaping(c)) { json_error(json, "%s", "unescaped control character in string"); return JSON_ERROR; } if (pushchar(json, c) != 0) return JSON_ERROR; } } return JSON_ERROR; } static int is_digit(int c) { return c >= 48 /*0*/ && c <= 57 /*9*/; } static int read_digits(struct json_stream *json) { unsigned nread = 0; while (is_digit(json_io_peek(json))) { if (pushchar(json, json_io_get(json)) != 0) return -1; nread++; } if (nread == 0) { return -1; } return 0; } static enum json_type read_number(struct json_stream *json, int c) { if (pushchar(json, c) != 0) return JSON_ERROR; if (c == '-') { c = json_io_get(json); if (is_digit(c)) { return read_number(json, c); } else { json_error(json, "unexpected byte, '%c'", c); } } else if (strchr("123456789", c) != NULL) { c = json_io_peek(json); if (is_digit(c)) { if (read_digits(json) != 0) return JSON_ERROR; } } /* Up to decimal or exponent has been read. */ c = json_io_peek(json); if (strchr(".eE", c) == NULL) { if (pushchar(json, '\0') != 0) return JSON_ERROR; else return JSON_NUMBER; } if (c == '.') { json_io_get(json); /* consume . */ if (pushchar(json, c) != 0) return JSON_ERROR; if (read_digits(json) != 0) return JSON_ERROR; } /* Check for exponent. */ c = json_io_peek(json); if (c == 'e' || c == 'E') { json_io_get(json); /* consume e/E */ if (pushchar(json, c) != 0) return JSON_ERROR; c = json_io_peek(json); if (c == '+' || c == '-') { json_io_get(json); /* consume */ if (pushchar(json, c) != 0) return JSON_ERROR; if (read_digits(json) != 0) return JSON_ERROR; } else if (is_digit(c)) { if (read_digits(json) != 0) return JSON_ERROR; } else { json_error(json, "unexpected byte in number, '%c'", c); return JSON_ERROR; } } if (pushchar(json, '\0') != 0) return JSON_ERROR; else return JSON_NUMBER; } static int json_isspace(int c) { switch (c) { case 0x09: case 0x0a: case 0x0d: case 0x20: return 1; } return 0; } /* Returns the next non-whitespace character in the stream. */ static int next(struct json_stream *json) { int c; while (json_isspace((c = json_io_get(json)))) if (c == '\n') json->lineno++; return c; } static enum json_type read_value(struct json_stream *json, int c) { json->ntokens++; switch (c) { case -1: json_error(json, "%s", "unexpected end of data"); return JSON_ERROR; case '{': return push(json, JSON_OBJECT); case '[': return push(json, JSON_ARRAY); case '"': return read_string(json); case 'n': return is_match(json, "ull", JSON_NULL); case 'f': return is_match(json, "alse", JSON_FALSE); case 't': return is_match(json, "rue", JSON_TRUE); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': if (init_string(json) != 0) return JSON_ERROR; return read_number(json, c); default: json_error(json, "unexpected byte, '%c'", c); return JSON_ERROR; } } enum json_type json_peek(struct json_stream *json) { enum json_type next = json_next(json); json->next = next; return next; } enum json_type json_next(struct json_stream *json) { int c; if (json->flags & JSON_FLAG_ERROR) return JSON_ERROR; if (json->next != 0) { enum json_type next = json->next; json->next = (enum json_type)0; return next; } if (json->ntokens > 0 && json->stack_top == (size_t)-1) { do { c = json_io_peek(json); if (json_isspace(c)) { c = json_io_get(json); } } while (json_isspace(c)); if (!(json->flags & JSON_FLAG_STREAMING) && c != -1) { return JSON_ERROR; } return JSON_DONE; } c = next(json); if (json->stack_top == (size_t)-1) return read_value(json, c); if (json->stack[json->stack_top].type == JSON_ARRAY) { if (json->stack[json->stack_top].count == 0) { if (c == ']') { return pop(json, c, JSON_ARRAY); } json->stack[json->stack_top].count++; return read_value(json, c); } else if (c == ',') { json->stack[json->stack_top].count++; return read_value(json, next(json)); } else if (c == ']') { return pop(json, c, JSON_ARRAY); } else { json_error(json, "unexpected byte, '%c'", c); return JSON_ERROR; } } else if (json->stack[json->stack_top].type == JSON_OBJECT) { if (json->stack[json->stack_top].count == 0) { enum json_type value; if (c == '}') { return pop(json, c, JSON_OBJECT); } /* No property value pairs yet. */ value = read_value(json, c); if (value != JSON_STRING) { json_error(json, "%s", "expected property name or '}'"); return JSON_ERROR; } else { json->stack[json->stack_top].count++; return value; } } else if ((json->stack[json->stack_top].count % 2) == 0) { /* Expecting comma followed by property name. */ if (c != ',' && c != '}') { json_error(json, "%s", "expected ',' or '}'"); return JSON_ERROR; } else if (c == '}') { return pop(json, c, JSON_OBJECT); } else { enum json_type value = read_value(json, next(json)); if (value != JSON_STRING) { json_error(json, "%s", "expected property name"); return JSON_ERROR; } else { json->stack[json->stack_top].count++; return value; } } } else if ((json->stack[json->stack_top].count % 2) == 1) { /* Expecting colon followed by value. */ if (c != ':') { json_error(json, "%s", "expected ':' after property name"); return JSON_ERROR; } else { json->stack[json->stack_top].count++; return read_value(json, next(json)); } } } json_error(json, "%s", "invalid parser state"); return JSON_ERROR; } void json_reset(struct json_stream *json) { json->stack_top = -1; json->ntokens = 0; json->flags &= ~JSON_FLAG_ERROR; json->errmsg[0] = '\0'; } const char * json_get_string(struct json_stream *json, size_t *length) { if (length != NULL) *length = json->data.string_fill; if (json->data.string == NULL) return ""; else return json->data.string; } double json_get_number(struct json_stream *json) { char *p = json->data.string; return p == NULL ? 0 : strtod(p, NULL); } const char * json_get_error(struct json_stream *json) { return json->flags & JSON_FLAG_ERROR ? json->errmsg : NULL; } unsigned long json_get_lineno(struct json_stream *json) { return json->lineno; } unsigned long json_get_position(struct json_stream *json) { return json->position; } size_t json_get_depth(struct json_stream *json) { return json->stack_top + 1; } static void * json_alloc_default(void *buf, size_t len, void *arg) { (void)arg; if (!len) { free(buf); return 0; } else { return realloc(buf, len); } } void json_open(struct json_stream *json, json_fgetc fgetc, void *arg, int flags) { json->lineno = 1; json->flags = flags; json->errmsg[0] = 0; json->ntokens = 0; json->next = 0; json->stack = NULL; json->stack_top = -1; json->stack_size = 0; json->data.string = NULL; json->data.string_size = 0; json->data.string_fill = 0; json->alloc = json_alloc_default; json->fgetc = fgetc; json->fgetc_arg = arg; json->position = 0; json->peek = -2; } void json_set_allocator(struct json_stream *json, json_alloc alloc, void *arg) { json->alloc = alloc; json->alloc_arg = arg; } void json_close(struct json_stream *json) { json->alloc(json->stack, 0, json->alloc_arg); json->stack = 0; json->alloc(json->data.string, 0, json->alloc_arg); json->data.string = 0; }
Subrato-oid/cs-algorithms
Divide and Conquer/Max Subarray Sum/c++/MAXIMUM_SUBARRAY_SUM.cpp
#include<iostream> using namespace std; sumofarray(int arr[], int n) { if(n==0) return 0; int ans=sumofarray(arr+1,n-1); return arr[0]+ans; } int main() { int n;cin>>n; while(n--) { int a; cin>>a; int arr[a]; for(int i=0;i<=n;i++) { cin>>arr[i]; cout<<sumofarray(arr,a); } } }
Thanatoz-1/EmotionStimuli
src/emotion/evaluation/evaluation.py
__author__ = "<NAME>" from .metrics import calc_precision, calc_recall, calc_fscore from .align_spans import gen_poss_align, align_spans from .convert_to_span import conv2span, conv2brown, get_counts from .align_spans import gen_poss_align, align_spans, perform_align_op from .metrics import calc_precision, calc_recall, calc_fscore, calc_jaccard_score from emotion.config import Config import random from tqdm import tqdm import copy from ..utils import Dataset import json class Evaluation: """Stores the results and documentation of the evaluation.""" def __init__( self, dataset: Dataset, role: str, threshold: int = 0.8, beta=1.0 ) -> None: """Initialize the Evaluation object. Args: dataset (Dataset): Dataset object containing the gold as well as the predicted annotations. annotations. role (str): the emotion role for which the annotations should be evaluated. threshold (int, optional): A predicted span of tags is only evaluated to TP if the jaccard score of this span and the aligned gold span is above the threshold. Defaults to 0.8. beta (int, optional): Value of beta used for calculating f-score. Defaults to 1. """ self.role = role self.threshold = threshold self.tp = 0 self.fp = 0 self.fn = 0 self.documentation = {} self.beta = beta self.evaluate(dataset=dataset) self.precision = calc_precision(tp=self.tp, fp=self.fp) self.recall = calc_recall(tp=self.tp, fn=self.fn) self.fscore = calc_fscore(prec=self.precision, rec=self.recall, beta=self.beta) def evaluate(self, dataset) -> None: """accumulate TP, FP and FN of all instances in the dataset and store the details of this evaluation. Args: dataset ([type]): Dataset object containing the gold as well as the predicted annotations. """ for id in dataset.instances: if self.role in dataset.instances[id].gold: # get the spans of tags in the gold and the predicted annotations. gld_spn = conv2span(dataset.instances[id].gold[self.role]) prd_spn = conv2span(dataset.instances[id].pred[self.role]) # generate all possible alignment__g2ps between the spans. poss_g2p = gen_poss_align(frm=gld_spn, to=prd_spn) poss_p2g = gen_poss_align(frm=prd_spn, to=gld_spn) # delete ambiguous alignment__g2ps to obtain final alignment__g2p alignment_g2p = align_spans( poss_g2p, poss_p2g, ops=["del_O", "del_no_choice", "del_shortest_jaccard", "del_rand"], ) self.documentation[id] = {} self.documentation[id]["tokens"] = dataset.instances[id].tokens self.documentation[id]["spans"] = {} self.documentation[id]["spans"]["gold"] = gld_spn self.documentation[id]["annotations"] = {} self.documentation[id]["spans"]["pred"] = prd_spn self.documentation[id]["eval"] = {} self.documentation[id]["eval"]["jaccard"] = [] self.documentation[id]["eval"]["pred_tag"] = [] self.documentation[id]["eval"]["counts"] = [] self.documentation[id]["annotations"]["gold"] = dataset.instances[ id ].gold[self.role] self.documentation[id]["annotations"]["pred"] = dataset.instances[ id ].pred[self.role] self.documentation[id]["eval"]["alignment"] = str(alignment_g2p) for gold_alignm in alignment_g2p: for pred_span in alignment_g2p[gold_alignm]: pred_alignm = alignment_g2p[gold_alignm][pred_span] jaccard = pred_alignm[1] pred_tag = pred_alignm[0] self.documentation[id]["eval"]["jaccard"].append(jaccard) self.documentation[id]["eval"]["pred_tag"].append(pred_tag) if jaccard == 0: if pred_tag == "O": # evaluates to FN. self.documentation[id]["eval"]["counts"].append("fn") self.fn += 1 else: # evaluates to FP. self.documentation[id]["eval"]["counts"].append("fp") self.fp += 1 elif jaccard > 0 and jaccard < self.threshold: if pred_tag == "O": # would evaluate to TN if jaccard-score would have # been above threshold. self.documentation[id]["eval"]["counts"].append( "- (tn<thrshld)" ) pass else: # would evalaute to TP if jaccard-score would have # been above threshold. Thus, evaluates to FN. self.documentation[id]["eval"]["counts"].append( "fn (<- tp<thrshld)" ) self.fn += 1 pass else: if pred_tag == ".": # full stops are not evaluated. self.documentation[id]["eval"]["counts"].append("-") pass elif pred_tag == "O": # evaluates to TN but is omitted here as TN are not # relevant for calculating precision, recall and f-score. self.documentation[id]["eval"]["counts"].append( "- (tn)" ) pass else: # evaluates to TP. self.documentation[id]["eval"]["counts"].append("tp") self.tp += 1 def print_doc(self) -> None: """Print the documentation.""" for id in self.documentation: print(f"ID:\t{id}\n{self.documentation[id]}\n") return None def print_eval(self) -> None: """Print calulated Precision, Recall and F-Score.""" print( f"precision:\t{self.precision}\nrecall:\t{self.recall[id]}\nf-score:\t{self.fscore}" ) return None def save_doc(self, filename: str) -> None: """Save the documentation in a new json-file. Args: filename (str): name and path of the json-file. """ with open(filename, "w") as doc_file: json.dump(self.documentation, doc_file) def save_eval(self, eval_name: str, filename: str) -> None: """Save the documentation either in an existing or a new json-file. Args: eval_name (str): name of the evaluation. Needed to identify the evaluation if one file contains multiple evaluations. filename (str): name of either an existing json-file containing evaluations or the name of a new file. """ try: with open(filename, "r") as eval_file: data = eval_file.read() eval_output = json.loads(data) eval_output[eval_name] = {} except: eval_output = {eval_name: {}} eval_output[eval_name]["size"] = len(self.documentation) eval_output[eval_name]["evaluated role"] = self.role eval_output[eval_name]["jaccard-threshold"] = self.threshold eval_output[eval_name]["amount TP"] = self.tp eval_output[eval_name]["amount FN"] = self.fn eval_output[eval_name]["amount FP"] = self.fp eval_output[eval_name]["precision"] = self.precision eval_output[eval_name]["recall"] = self.recall eval_output[eval_name]["f-score"] = self.fscore eval_output[eval_name]["beta for f-score"] = self.beta with open(filename, "w") as eval_file: json.dump(eval_output, eval_file) return None def metric_for_bilstm(tx_emb, ty, model, contains_srl=False): """Metric for evaluating the BiLSTM approach. Args: tx_emb ([type]): Embeddings containing token_ids, corresponding embeddings and srl feature if flag is ON! ty ([type]): Gold labels associated with every token (Shape may vary in case of SRL flag on) model ([type]): Keras model for inferencing. contains_srl (bool, optional): SRL flag to intuit model for SRL features. Defaults to False. Returns: (float, float, float): Tuple of (Precision, recall and F1_score) """ if contains_srl: tx, emb, srl = tx_emb[0], tx_emb[1], tx_emb[2] else: tx, emb = tx_emb[0], tx_emb[1] threshold = 0.8 id2lab = {Config.BILSTM_CLASSES[i]: i for i in Config.BILSTM_CLASSES} tp = 0 fp = 0 fn = 0 if contains_srl: predictions = model.predict([emb, srl]) else: predictions = model.predict(emb) for idx, i in tqdm(enumerate(range(len(tx))), total=len(tx), leave=False): try: toks = [ Config.ID2WORD[iod] for iod in tx[i] if Config.ID2WORD[iod] != "pad" ] gold = [id2lab[id] for id in ty[i] if id2lab[id] != "PAD"] preds = [ id2lab[iod] for iod in predictions[idx].argmax(-1) if id2lab[iod] != "PAD" ] gold_brown = conv2brown(toks, gold) pred_brown = conv2brown(toks, preds) counts, indices = get_counts( gold_brown, pred_brown, threshold, return_indices=True ) tmp_tp = tp tp += counts[0] fp += counts[1] fn += counts[2] if tp - tmp_tp >= 1: pass except Exception as e: print(tx[i], e) prec = calc_precision(tp, fp) rec = calc_recall(tp, fn) f1 = calc_fscore(prec, rec) return prec, rec, f1
a-bentofreire/abeamer
test/template/main.js
// ------------------------------------------------------------------------ $(window).on("load", function () { var independentCases = __IND_CASES__; try { var story = ABeamer.createStory(__FPS__); } catch (error) { console.error('[EXCEPTION]:', error); console.error('[CRITICAL]: ABeamer.createStory failed: ' + error); } if (story.logLevel === undefined || ABeamer.LL_VERBOSE === undefined) { console.error('[CRITICAL]: story.logLevel or ABeamer.LL_VERBOSE is missing'); } story.logLevel = ABeamer.LL_VERBOSE; // ------------------------------------------------------------------------ // Scene1 // ------------------------------------------------------------------------ try { var scene1 = story.scenes[0]; } catch (error) { console.error('[EXCEPTION]:', error); console.error('[CRITICAL]: scene1 = story.scenes[0] failed: ' + error); } __JS__ story.toExitOnRenderFinished = __EXIT_RENDER_ON_FINISHED__; try { story.render(story.bestPlaySpeed(), __RENDER_FRAME_OPTIONS__); __EXTRA_RENDER_CALLS__ } catch (error) { story.logError('[EXCEPTION]:' + error); console.error('[CRITICAL]: story.render failed:' + error); } });
spprod35/pve-manager
www/manager/qemu/StatusView.js
<filename>www/manager/qemu/StatusView.js Ext.define('PVE.qemu.StatusView', { extend: 'PVE.grid.ObjectGrid', alias: ['widget.pveQemuStatusView'], initComponent : function() { var me = this; var nodename = me.pveSelNode.data.node; if (!nodename) { throw "no node name specified"; } var vmid = me.pveSelNode.data.vmid; if (!vmid) { throw "no VM ID specified"; } var render_cpu = function(value, metaData, record, rowIndex, colIndex, store) { if (!me.getObjectValue('uptime')) { return '-'; } var maxcpu = me.getObjectValue('cpus', 1); if (!(Ext.isNumeric(value) && Ext.isNumeric(maxcpu) && (maxcpu >= 1))) { return '-'; } var per = (value * 100); return per.toFixed(1) + '% of ' + maxcpu.toString() + (maxcpu > 1 ? 'CPUs' : 'CPU'); }; var render_mem = function(value, metaData, record, rowIndex, colIndex, store) { var maxmem = me.getObjectValue('maxmem', 0); var per = (value / maxmem)*100; var text = "<div>" + PVE.Utils.totalText + ": " + PVE.Utils.format_size(maxmem) + "</div>" + "<div>" + PVE.Utils.usedText + ": " + PVE.Utils.format_size(value) + "</div>"; return text; }; var rows = { name: { header: gettext('Name'), defaultValue: 'no name specified' }, qmpstatus: { header: gettext('Status'), defaultValue: 'unknown' }, cpu: { header: gettext('CPU usage'), required: true, renderer: render_cpu }, cpus: { visible: false }, mem: { header: gettext('Memory usage'), required: true, renderer: render_mem }, maxmem: { visible: false }, uptime: { header: gettext('Uptime'), required: true, renderer: PVE.Utils.render_uptime }, ha: { header: gettext('Managed by HA'), required: true, renderer: PVE.Utils.format_boolean } }; Ext.applyIf(me, { cwidth1: 150, height: 166, rows: rows }); me.callParent(); } });
wangyue033/AI-PLATFORM
guns-base-support/guns-excel/src/main/java/cn/stylefeng/guns/excel/controller/ExcelExportDeployController.java
package cn.stylefeng.guns.excel.controller; import cn.stylefeng.guns.base.consts.ConstantsContext; import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo; import cn.stylefeng.guns.sys.core.util.FileDownload; import cn.stylefeng.guns.excel.entity.ExcelExportDeploy; import cn.stylefeng.guns.excel.model.params.ExcelExportDeployParam; import cn.stylefeng.guns.excel.service.ExcelExportDeployService; import cn.stylefeng.guns.sys.modular.system.entity.FileInfo; import cn.stylefeng.guns.sys.modular.system.model.UploadResult; import cn.stylefeng.guns.sys.modular.system.service.FileInfoService; import cn.stylefeng.roses.core.base.controller.BaseController; import cn.stylefeng.roses.kernel.model.response.ResponseData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import static cn.stylefeng.guns.excel.consts.ExcelConstants.EXCEL_FILE_TEMPLATE_PATH; /** * excel导出配置控制器 * * @author York * @Date 2019-11-26 16:52:02 */ @Controller @RequestMapping("/excelExportDeploy") public class ExcelExportDeployController extends BaseController { private String PREFIX = "/modular/excel"; @Autowired private FileInfoService fileInfoService; @Autowired private ExcelExportDeployService excelExportDeployService; /** * 跳转到主页面 * * @author York * @Date 2019-11-26 */ @RequestMapping("") public String index() { return PREFIX + "/excelExportDeploy.html"; } /** * 新增页面 * * @author York * @Date 2019-11-26 */ @RequestMapping("/add") public String add() { return PREFIX + "/excelExportDeploy_add.html"; } /** * 编辑页面 * * @author York * @Date 2019-11-26 */ @RequestMapping("/edit") public String edit() { return PREFIX + "/excelExportDeploy_edit.html"; } /** * 新增接口 * * @author York * @Date 2019-11-26 */ @RequestMapping("/addItem") @ResponseBody public ResponseData addItem(ExcelExportDeployParam excelExportDeployParam) { this.excelExportDeployService.add(excelExportDeployParam); return ResponseData.success(); } /** * 编辑接口 * * @author York * @Date 2019-11-26 */ @RequestMapping("/editItem") @ResponseBody public ResponseData editItem(ExcelExportDeployParam excelExportDeployParam) { this.excelExportDeployService.update(excelExportDeployParam); return ResponseData.success(); } /** * 删除接口 * * @author York * @Date 2019-11-26 */ @RequestMapping("/delete") @ResponseBody public ResponseData delete(ExcelExportDeployParam excelExportDeployParam) { this.excelExportDeployService.delete(excelExportDeployParam); return ResponseData.success(); } /** * 上传模版文件 * * @return */ @RequestMapping("/uploadTemplate") @ResponseBody public ResponseData uploadTemplate(@RequestPart("file") MultipartFile file) { try { if (file == null) { return ResponseData.error("请选择要上传的模版文件"); } //上传路径设置 String fileSavePath = ConstantsContext.getFileUploadPath(); fileSavePath = fileSavePath + EXCEL_FILE_TEMPLATE_PATH; UploadResult uploadResult = fileInfoService.uploadFile(file, fileSavePath); if (!uploadResult.getOriginalFilename().contains(".xls")) { return ResponseData.error("上传的模版文件必须为2003版的excel文件"); } return ResponseData.success(EXCEL_FILE_TEMPLATE_PATH + uploadResult.getFinalName()); } catch (Exception e) { e.printStackTrace(); return ResponseData.error(e.getMessage()); } } /** * 下载模板文件 * * @author fengshuonan * @Date 2019-2-23 10:48:29 */ @RequestMapping(path = "/download/{fileFinalName}") public void download(@PathVariable String fileFinalName, HttpServletResponse httpServletResponse) { //上传路径设置 String fileSavePath = ConstantsContext.getFileUploadPath(); fileSavePath = fileSavePath + EXCEL_FILE_TEMPLATE_PATH; //查找文件信息 FileInfo fileInfo = fileInfoService.getByFinalName(fileFinalName); try { FileDownload.fileDownload(httpServletResponse, fileSavePath + fileFinalName, fileInfo.getFileName()); } catch (Exception e) { e.printStackTrace(); } } /** * 查看详情接口 * * @author York * @Date 2019-11-26 */ @RequestMapping("/detail") @ResponseBody public ResponseData detail(ExcelExportDeployParam excelExportDeployParam) { ExcelExportDeploy detail = this.excelExportDeployService.getById(excelExportDeployParam.getId()); return ResponseData.success(detail); } /** * 查询列表 * * @author York * @Date 2019-11-26 */ @ResponseBody @RequestMapping("/list") public LayuiPageInfo list(ExcelExportDeployParam excelExportDeployParam) { return this.excelExportDeployService.findPageBySpec(excelExportDeployParam); } }
MrDelik/core
homeassistant/components/sonarr/entity.py
"""Base Entity for Sonarr.""" from __future__ import annotations from aiopyarr import SystemStatus from aiopyarr.models.host_configuration import PyArrHostConfiguration from aiopyarr.sonarr_client import SonarrClient from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.entity import DeviceInfo, Entity from .const import DOMAIN class SonarrEntity(Entity): """Defines a base Sonarr entity.""" def __init__( self, *, sonarr: SonarrClient, host_config: PyArrHostConfiguration, system_status: SystemStatus, entry_id: str, device_id: str, ) -> None: """Initialize the Sonarr entity.""" self._entry_id = entry_id self._device_id = device_id self.sonarr = sonarr self.host_config = host_config self.system_status = system_status @property def device_info(self) -> DeviceInfo | None: """Return device information about the application.""" if self._device_id is None: return None return DeviceInfo( identifiers={(DOMAIN, self._device_id)}, name="Activity Sensor", manufacturer="Sonarr", sw_version=self.system_status.version, entry_type=DeviceEntryType.SERVICE, configuration_url=self.host_config.base_url, )
cccht/RSSHub
lib/routes/haimaoba/comics.js
<gh_stars>1-10 const got = require('@/utils/got'); const cheerio = require('cheerio'); const iconv = require('iconv-lite'); const getChapters = (id, $, caches) => { const chapters = $('.text') .toArray() .reduce((acc, curr) => acc.concat(`http://www.haimaoba.com${$(curr).children('a').attr('href')}`), []); return Promise.all( chapters.splice(0, 10).map((link) => caches.tryGet(link, async () => { const { data } = await got.get(link, { responseType: 'buffer', host: 'www.haimaoba.com', Referer: `http://www.haima.com/catalog/${id}/`, }); const content = iconv.decode(new Buffer.from(data), 'gb2312'); const $ = cheerio.load(content); return { title: $('head > title').text(), link: link, description: $('.contentimg').html(), }; }) ) ); }; module.exports = async (ctx) => { const id = ctx.params.id; const { data } = await got.get(`http://www.haimaoba.com/catalog/${id}/`, { responseType: 'buffer', Host: 'www.haimaoba.com', Referer: 'http://www.haimaoba.com/', }); const content = iconv.decode(new Buffer.from(data), 'gb2312'); const $ = cheerio.load(content); const bookTitle = $('.t > h1').text(); const bookIntro = $('#zuop1C').text(); const chapters = await getChapters(id, $, ctx.cache); const rssData = (chapter) => ({ link: chapter.link, title: chapter.title, description: chapter.description, }); ctx.state.data = { title: `海猫吧 - ${bookTitle}`, link: `http://www.haimaoba.com/catalog/${id}/`, description: bookIntro, item: chapters.map(rssData), }; };
litsor/core
core/methods/strings/truncate.test.js
'use strict'; module.exports = { tests: [{ can: 'truncate string to length', left: 'Hello world', right: 5, output: 'Hello' }] };
substack/keybase-client
node_modules/kbpgp/node_modules/keybase-compressjs/outlib/LogDistanceModel.js
<filename>node_modules/kbpgp/node_modules/keybase-compressjs/outlib/LogDistanceModel.js /** Simple (log n)(n) distance model. */ var libs = [ require('./Util') ]; var body_fn = function (Util){ // lengthBitsModelFactory will be called with arguments 2, 4, 8, 16, etc // and must return an appropriate model or coder. var LogDistanceModel = function(size, extraStates, lgDistanceModelFactory, lengthBitsModelFactory) { var i; var bits = Util.fls(size-1); this.extraStates = +extraStates || 0; this.lgDistanceModel = lgDistanceModelFactory(1 + bits + extraStates); // this.distanceModel[n] used for distances which are n-bits long, // but only n-1 bits are encoded: the top bit is known to be one. this.distanceModel = []; for (i=2 ; i <= bits; i++) { var numBits = i - 1; this.distanceModel[i] = lengthBitsModelFactory(1<<numBits); } }; /* you can give this model arguments between 0 and (size-1), or else a negative argument which is one of the 'extra states'. */ LogDistanceModel.prototype.encode = function(distance) { if (distance < 2) { // small distance or an 'extra state' this.lgDistanceModel.encode(distance + this.extraStates); return; } var lgDistance = Util.fls(distance); console.assert(distance & (1<<(lgDistance-1))); // top bit is set console.assert(lgDistance >= 2); this.lgDistanceModel.encode(lgDistance + this.extraStates); // now encode the rest of the bits. var rest = distance & ((1 << (lgDistance-1)) - 1); this.distanceModel[lgDistance].encode(rest); }; LogDistanceModel.prototype.decode = function() { var lgDistance = this.lgDistanceModel.decode() - this.extraStates; if (lgDistance < 2) { return lgDistance; // this is a small distance or an 'extra state' } var rest = this.distanceModel[lgDistance].decode(); return (1 << (lgDistance-1)) + rest; }; return LogDistanceModel; }; module.exports = body_fn.apply(null, libs);
haohanscm/pds
src/main/java/com/haohan/platform/service/sys/modules/xiaodian/dao/pay/OrderPayRecordDao.java
package com.haohan.platform.service.sys.modules.xiaodian.dao.pay; import com.haohan.platform.service.sys.common.persistence.CrudDao; import com.haohan.platform.service.sys.common.persistence.annotation.MyBatisDao; import com.haohan.platform.service.sys.modules.xiaodian.entity.pay.OrderPayRecord; import java.math.BigDecimal; /** * 订单支付DAO接口 * @author haohan * @version 2017-12-10 */ @MyBatisDao public interface OrderPayRecordDao extends CrudDao<OrderPayRecord> { BigDecimal sumSaleAmount(OrderPayRecord orderPayRecord); }
gabrielbursztein2/time-management-web
src/components/routes/PrivateRoute.js
<reponame>gabrielbursztein2/time-management-web import React from 'react'; import { bool, string, node } from 'prop-types'; import { Route, Redirect, useLocation } from 'react-router-dom'; import routes from 'constants/routesPaths'; const PrivateRoute = ({ children, exact = false, path, authenticated }) => { const location = useLocation(); return authenticated ? ( <Route exact={exact} path={path}> {children} </Route> ) : ( <Redirect to={{ pathname: routes.login, state: { from: location } }} /> ); }; PrivateRoute.propTypes = { children: node.isRequired, path: string.isRequired, authenticated: bool.isRequired, exact: bool }; export default PrivateRoute;
converba/yeti-customer-portal
src/services/Rates.js
define(function (require) { var Request = require('../services/Request'); return { getRates (args) { const perPage = args.perPage || ''; const page = args.page || ''; return new Promise((resolve, reject) => { if(!args.jwt) { reject(new Error('Auth error: didn\'t authorized')) } else { Request.send({ api: `api/rest/customer/v1/rates?page[size]=${perPage}&page[number]=${page}`, params: { method: 'GET', headers: { Authorization: args.jwt, 'Content-Type': 'application/vnd.api+json' } } }).then(function (response) { if(response.data) { resolve({ rates: response.data, totalCount: response.meta['total-count'] }) } }).catch((e) => { reject(new Error('Auth error: didn\'t authorized')) }) } }); }, checkRate (args) { return new Promise((resolve, reject) => { if(!args.jwt || typeof(args.jwt) === 'undefined') { reject(new Error('Auth error: didn\'t authorized')); return; } if(!args.rateplanId) { reject(new Error('checkRate error: rateplan id not found')); return; } if(!args.number) { reject(new Error('checkRate error: number not found')); return; } Request.send({ api: 'api/rest/customer/v1/check-rate', params: { method: 'POST', headers: { Authorization: args.jwt, 'Content-Type': 'application/vnd.api+json' }, body: { data: { type: 'check-rates', attributes: { 'rateplan-id': args.rateplanId, 'number': args.number } } } } }).then(function (response) { if(response.data) { resolve(response.data) } }).catch((e) => { reject(new Error('Auth error: didn\'t authorized')) }) }); } }; });
umarmughal824/bootcamp-ecommerce
applications/migrations/0006_change_submission_types.py
# Generated by Django 2.2.10 on 2020-05-11 16:06 from django.db import migrations, models def update_submission_types(apps, schema_editor): """ Updates submission_type values in ApplicationStep to new values """ ApplicationStep = apps.get_model("applications", "ApplicationStep") ApplicationStep.objects.filter(submission_type="video_interview").update( submission_type="videointerviewsubmission" ) ApplicationStep.objects.filter(submission_type="quiz").update( submission_type="quizsubmission" ) def undo_update_submission_types(apps, schema_editor): """ Updates submission_type values in ApplicationStep to old values """ ApplicationStep = apps.get_model("applications", "ApplicationStep") ApplicationStep.objects.filter(submission_type="videointerviewsubmission").update( submission_type="video_interview" ) ApplicationStep.objects.filter(submission_type="quizsubmission").update( submission_type="quiz" ) class Migration(migrations.Migration): dependencies = [("applications", "0005_application_multiple_orders")] operations = [ migrations.AlterField( model_name="applicationstep", name="submission_type", field=models.CharField( choices=[ ("videointerviewsubmission", "Video Interview"), ("quizsubmission", "Quiz"), ("video_interview", "video_interview"), ("quiz", "quiz"), ], max_length=40, ), ), migrations.RunPython(update_submission_types, undo_update_submission_types), migrations.AlterField( model_name="applicationstep", name="submission_type", field=models.CharField( choices=[ ("videointerviewsubmission", "Video Interview"), ("quizsubmission", "Quiz"), ], max_length=40, ), ), ]
kaynewbie/algorithm
algorithm/LeetCode/Easy/maximum-depth-of-binary-tree.c
// // maximum-depth-of-binary-tree.c // algorithm // // Created by Kai on 2019/7/30. // Copyright © 2019 kai. All rights reserved. // #include "maximum-depth-of-binary-tree.h" #include "binary-tree.h" #define MAX(x, y) ((x > y) ? x : y) int depthInTree(TreeNode *tree, int depth); int depthInTree(TreeNode *tree, int depth) { if (tree == NULL) { return depth; } depth++; int depthLeft = depthInTree(tree->left, depth); int depthRight = depthInTree(tree->right, depth); return MAX(depthLeft, depthRight); } /* [3,9,20,null,null,15,7] */ void testMaxDepthInTree1(void) { const int length = 7; int array[length] = {3,9,20,0,0,15,7}; TreeNode *tree = createBinaryTree(array, length); int result = maxDepth(tree); printf("tree: "); preOrderRecursive(tree); printf("\n"); printf("max depth = %d\n", result); } void testMaxDepthInTree(void) { testMaxDepthInTree1(); }
SpongePowered/Common
src/main/java/org/spongepowered/common/network/channel/raw/SpongeRawLoginDataChannel.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.spongepowered.common.network.channel.raw; import org.spongepowered.api.network.EngineConnection; import org.spongepowered.api.network.EngineConnectionSide; import org.spongepowered.api.network.channel.ChannelBuf; import org.spongepowered.api.network.channel.ChannelException; import org.spongepowered.api.network.channel.raw.RawDataChannel; import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataChannel; import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataRequestHandler; import org.spongepowered.api.network.channel.raw.handshake.RawHandshakeDataRequestResponse; import org.spongepowered.common.network.channel.ConnectionUtil; import org.spongepowered.common.network.channel.PacketSender; import org.spongepowered.common.network.channel.PacketUtil; import org.spongepowered.common.network.channel.SpongeChannel; import org.spongepowered.common.network.channel.TransactionResult; import org.spongepowered.common.network.channel.TransactionStore; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import net.minecraft.network.protocol.Packet; @SuppressWarnings("unchecked") public class SpongeRawLoginDataChannel implements RawHandshakeDataChannel { private final SpongeRawDataChannel parent; private final Map<Class<?>, RawHandshakeDataRequestHandler<?>> requestHandlers = new ConcurrentHashMap<>(); public SpongeRawLoginDataChannel(final SpongeRawDataChannel parent) { this.parent = parent; } private <C extends EngineConnection> RawHandshakeDataRequestHandler<? super C> getRequestHandler(final C connection) { return (RawHandshakeDataRequestHandler<? super C>) SpongeChannel.getRequestHandler(connection, this.requestHandlers); } @Override public RawDataChannel parent() { return this.parent; } @Override public <C extends EngineConnection> void setRequestHandler(final EngineConnectionSide<C> side, final RawHandshakeDataRequestHandler<? super C> handler) { Objects.requireNonNull(side, "side"); this.setRequestHandler(SpongeChannel.getConnectionClass(side), handler); } @Override public void setRequestHandler(final RawHandshakeDataRequestHandler<EngineConnection> handler) { this.setRequestHandler(EngineConnection.class, handler); } @Override public <C extends EngineConnection> void setRequestHandler(final Class<C> connectionType, final RawHandshakeDataRequestHandler<? super C> handler) { Objects.requireNonNull(connectionType, "connectionType"); Objects.requireNonNull(handler, "handler"); this.requestHandlers.put(connectionType, handler); } <C extends EngineConnection> void handleRequestPayload(final C connection, final ChannelBuf payload, final int transactionId) { final RawHandshakeDataRequestHandler<? super C> handler = this.getRequestHandler(connection); final RawHandshakeDataRequestResponse response = new RawHandshakeDataRequestResponse() { private boolean completed; private void checkCompleted() { if (this.completed) { throw new ChannelException("The request response was already completed."); } this.completed = true; } @Override public void fail(final ChannelException exception) { Objects.requireNonNull(exception, "exception"); this.checkCompleted(); PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, transactionId)); } @Override public void success(final Consumer<ChannelBuf> response) { Objects.requireNonNull(response, "response"); this.checkCompleted(); final ChannelBuf payload; try { payload = SpongeRawLoginDataChannel.this.parent.encodePayload(response); } catch (final Throwable t) { SpongeRawLoginDataChannel.this.parent.handleException(connection, new ChannelException("Failed to encode login data response", t), null); PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, transactionId)); return; } PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(payload, transactionId)); } }; boolean success = false; if (handler != null) { try { handler.handleRequest(payload, connection, response); success = true; } catch (final Throwable t) { this.parent.handleException(connection, new ChannelException("Failed to handle login data request", t), null); } } if (!success) { PacketSender.sendTo(connection, PacketUtil.createLoginPayloadResponse(null, transactionId)); } } void handleTransactionResponse(final EngineConnection connection, final Object stored, final TransactionResult result) { if (!(stored instanceof Consumer)) { return; } ((Consumer<TransactionResult>) stored).accept(result); } @Override public CompletableFuture<ChannelBuf> sendTo(final EngineConnection connection, final Consumer<ChannelBuf> payload) { ConnectionUtil.checkHandshakePhase(connection); final CompletableFuture<ChannelBuf> future = new CompletableFuture<>(); final ChannelBuf buf; try { buf = this.parent.encodePayload(payload); } catch (final Throwable t) { this.parent.handleException(connection, t, future); return future; } final TransactionStore transactionStore = ConnectionUtil.getTransactionStore(connection); final int transactionId = transactionStore.nextId(); final Consumer<TransactionResult> resultConsumer = result -> { if (result.isSuccess()) { future.complete(result.getPayload()); } else { this.parent.handleException(connection, result.getCause(), future); } }; final Packet<?> mcPacket = PacketUtil.createLoginPayloadRequest(this.parent.key(), buf, transactionId); PacketSender.sendTo(connection, mcPacket, sendFuture -> { if (sendFuture.isSuccess()) { transactionStore.put(transactionId, this.parent, resultConsumer); } else { // The packet already failed before it could reach the client future.completeExceptionally(sendFuture.cause()); } }); return future; } }
alphonsetai/RGA
RadeonGPUAnalyzerGUI/include/qt/rgGlobalSettingsModel.h
#pragma once // C++. #include <map> // Qt. #include <QVariant> // Local. #include <RadeonGPUAnalyzerGUI/include/qt/rgSettingsModelBase.h> // Forward declarations. struct rgGlobalSettings; enum rgGlobalSettingsControls { LogFileLocation, DisassemblyViewColumns, AlwaysUseGeneratedProjectNames, Count }; class rgGlobalSettingsModel : public rgSettingsModelBase { Q_OBJECT public: rgGlobalSettingsModel(std::shared_ptr<rgGlobalSettings> pBuildSettings, unsigned int modelCount); virtual ~rgGlobalSettingsModel() = default; // Retrieve the current user-configured build settings. std::shared_ptr<rgGlobalSettings> GetGlobalSettings() const; // Retrieve the pending build settings. Pending changes differ from the original values, but have not yet been saved by the user. std::shared_ptr<rgGlobalSettings> GetPendingGlobalSettings() const; // Set the build settings void SetBuildSettings(std::shared_ptr<rgGlobalSettings> pBuildSettings); // Replace the user's altered settings into the program instance. void SubmitPendingChanges(); // A model-specific implementation used to update a model value. virtual void UpdateModelValue(int control, const QVariant& value, bool updateInitialValue) override; // Verify the validity of all pending settings. Fill the incoming vector with error info. virtual bool ValidatePendingSettings(std::vector<rgInvalidFieldInfo>& errorFields) override; protected: // A model-specific implementation to initialize all model values. virtual void InitializeModelValuesImpl() override; private: // Get the pending value of a target control. bool GetPendingValue(rgGlobalSettingsControls control, QVariant& value) const; // Update the given control's value in the given settings structure. void UpdateSetting(int control, const QVariant& value, std::shared_ptr<rgGlobalSettings> pBuildSettings); // The target build settings being edited by this model. std::shared_ptr<rgGlobalSettings> m_pGlobalSettings = nullptr; // The pending build settings to be saved. std::shared_ptr<rgGlobalSettings> m_pPendingGlobalSettings = nullptr; };
ppdaicorp/stargate
gate-server/src/main/java/com/ppdai/stargate/job/HandlerRegistry.java
package com.ppdai.stargate.job; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; public class HandlerRegistry<T extends IHandler> { private Map<String, T> taskHandlerMap = new ConcurrentHashMap<>(); public HandlerRegistry(List<T> taskHandlers) { if (!CollectionUtils.isEmpty(taskHandlers)) { taskHandlerMap = taskHandlers.stream() .collect(Collectors.toMap(IHandler::getName, Function.identity())); } } public void register(T handler) { this.taskHandlerMap.put(handler.getName(), handler); } public Optional<T> getHandler(String name) { return Optional.ofNullable(taskHandlerMap.get(name)); } }
prameetu/CP_codes
CODEFORCES/eshan_loves_big_array.cpp
#include <bits/stdc++.h> #define MOD 1000000007 #define ll long long int #define rep(i,a,b) for(ll i=a;i<b;i++) using namespace std; void ans() { int n; cin >> n; vector <int> v(n); int min(101); rep(i,0,n) cin >> v[i]; auto min_ele = *min_element(v.begin(),v.end()); int cnt(0); rep(i,0,n) { if(v[i] == min_ele) cnt++; } cout << n-cnt << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { ans(); } }
martianworm17/tp_junit
com.tp.test/mockobject/PubTest.java
<reponame>martianworm17/tp_junit package mockobject; import org.jmock.Mockery; import junit.framework.TestCase; public class PubTest { // class Mock { // Mockery context = new Mockery(); // // public void testSubReceivesMessage() { // // // Set up // final Sub sub = context.mock(Sub.class); // // Pub pub = new Pub(); // pub.add(sub); // // final String message = "message"; // // // expectations // context.checking(new Expectations() { // oneOf (sub).receive(message); // }); // // // execute // pub.publish(message); // // // verify // context.assertIsSatisfied(); // // // } // } }
hanztura/hrsalespipes
hrsalespipes/jobs/rules.py
def is_allowed_to_edit_close_job(user, job): if job.status is None: return True # check if job is open if job.status.is_job_open: return True # check if user is allowed to bypass if user.has_perm('jobs.can_edit_closed_job'): return True return False def is_associate_or_consultant(user, job_candidate): """Check if a user is an assocaite or consulant of a pipeline record. """ # if user no employee assigned, then not allowed employee = getattr(user, 'as_employee', None) if not employee: return False associate_id = job_candidate.associate_id if associate_id: print(associate_id, employee.pk) if associate_id == employee.pk: return True consultant_id = job_candidate.consultant_id if consultant_id: print(consultant_id, employee.pk) if consultant_id == employee.pk: return True return False def is_allowed_to_view_or_edit(user, job_candidate): """Return True if user has permission to view all Pipelines OR is an associate or consultant of the Pipeline. """ if user.has_perm('jobs.view_all_job_candidates'): return True return is_associate_or_consultant(user, job_candidate)
yudong2015/openpitrix
pkg/service/runtime/permission.go
// Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. // Auto generated by 'go run gen_helper.go', DO NOT EDIT. package runtime import ( "context" "openpitrix.io/openpitrix/pkg/constants" "openpitrix.io/openpitrix/pkg/db" "openpitrix.io/openpitrix/pkg/gerr" "openpitrix.io/openpitrix/pkg/models" "openpitrix.io/openpitrix/pkg/pi" "openpitrix.io/openpitrix/pkg/util/ctxutil" ) func CheckRuntimesPermission(ctx context.Context, resourceIds []string) ([]*models.Runtime, error) { if len(resourceIds) == 0 { return nil, nil } var sender = ctxutil.GetSender(ctx) var runtimes []*models.Runtime _, err := pi.Global().DB(ctx). Select(models.RuntimeColumns...). From(constants.TableRuntime). Where(db.Eq(constants.ColumnRuntimeId, resourceIds)).Load(&runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } if sender != nil { for _, runtime := range runtimes { if !runtime.OwnerPath.CheckPermission(sender) && runtime.Owner != sender.UserId { return nil, gerr.New(ctx, gerr.PermissionDenied, gerr.ErrorResourceAccessDenied, runtime.RuntimeId) } } } if len(runtimes) == 0 { return nil, gerr.New(ctx, gerr.NotFound, gerr.ErrorResourceNotFound, resourceIds) } return runtimes, nil } func CheckRuntimePermission(ctx context.Context, resourceId string) (*models.Runtime, error) { if len(resourceId) == 0 { return nil, nil } var sender = ctxutil.GetSender(ctx) var runtimes []*models.Runtime _, err := pi.Global().DB(ctx). Select(models.RuntimeColumns...). From(constants.TableRuntime). Where(db.Eq(constants.ColumnRuntimeId, resourceId)).Load(&runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } if sender != nil { for _, runtime := range runtimes { if !runtime.OwnerPath.CheckPermission(sender) { return nil, gerr.New(ctx, gerr.PermissionDenied, gerr.ErrorResourceAccessDenied, runtime.RuntimeId) } } } if len(runtimes) == 0 { return nil, gerr.New(ctx, gerr.NotFound, gerr.ErrorResourceNotFound, resourceId) } return runtimes[0], nil } func CheckRuntimeCredentialsPermission(ctx context.Context, resourceIds []string) ([]*models.RuntimeCredential, error) { if len(resourceIds) == 0 { return nil, nil } var sender = ctxutil.GetSender(ctx) var runtimecredentials []*models.RuntimeCredential _, err := pi.Global().DB(ctx). Select(models.RuntimeCredentialColumns...). From(constants.TableRuntimeCredential). Where(db.Eq(constants.ColumnRuntimeCredentialId, resourceIds)).Load(&runtimecredentials) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } if sender != nil { for _, runtimecredential := range runtimecredentials { if !runtimecredential.OwnerPath.CheckPermission(sender) && runtimecredential.Owner != sender.UserId { return nil, gerr.New(ctx, gerr.PermissionDenied, gerr.ErrorResourceAccessDenied, runtimecredential.RuntimeCredentialId) } } } if len(runtimecredentials) == 0 { return nil, gerr.New(ctx, gerr.NotFound, gerr.ErrorResourceNotFound, resourceIds) } return runtimecredentials, nil } func CheckRuntimeCredentialPermission(ctx context.Context, resourceId string) (*models.RuntimeCredential, error) { if len(resourceId) == 0 { return nil, nil } var sender = ctxutil.GetSender(ctx) var runtimecredentials []*models.RuntimeCredential _, err := pi.Global().DB(ctx). Select(models.RuntimeCredentialColumns...). From(constants.TableRuntimeCredential). Where(db.Eq(constants.ColumnRuntimeCredentialId, resourceId)).Load(&runtimecredentials) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } if sender != nil { for _, runtimecredential := range runtimecredentials { if !runtimecredential.OwnerPath.CheckPermission(sender) { return nil, gerr.New(ctx, gerr.PermissionDenied, gerr.ErrorResourceAccessDenied, runtimecredential.RuntimeCredentialId) } } } if len(runtimecredentials) == 0 { return nil, gerr.New(ctx, gerr.NotFound, gerr.ErrorResourceNotFound, resourceId) } return runtimecredentials[0], nil }
HooraOnline/treenetweb
src/react-native/Image.js
<reponame>HooraOnline/treenetweb<gh_stars>0 import View from "./View"; import {makeStyles} from "@material-ui/core/styles"; export default function Image(props) { let {style={},source} = props; const styles = { main: { // filter:style.tintColor?'invert(408%) sepia(1009%) saturate(175%) hue-rotate(86deg) brightness(118%) contrast(119%)':' -webkit-filter: invert(90%) hue-rotate(175deg); filter: invert(70%) hue-rotate(175deg);', filter:style.tintColor?'invert(408%) sepia(1009%) saturate(0%) hue-rotate(86deg) brightness(118%) contrast(119%)':'', 'object-fit': 'cover', }, } const useStyles = makeStyles(styles); const classes = useStyles(); let style2=Object.assign({},style); style2.display='flex'; style2.flexDirection=style2.flexDirection || 'column'; style2.marginRight=style2.marginRight || style2.marginStart ||style2.marginHorizontal ||style2.margin; style2.marginLeft=style2.marginLeft|| style2.marginEnd ||style2.marginHorizontal ||style2.margin; style2.marginTop=style2.marginTop ||style2.marginVertical ||style2.margin; style2.marginBottom=style2.marginBottom ||style2.marginVertical ||style2.margin; style2.paddingRight=style2.paddingRight || style2.paddingStart ||style2.paddingHorizontal || style2.padding; style2.paddingLeft=style2.paddingLeft|| style2.paddingEnd ||style2.paddingHorizontal || style2.padding; style2.paddingTop=style2.paddingTop ||style2.paddingVertical ||style2.padding; style2.paddingBottom=style2.paddingBottom ||style2.paddingVertical ||style2.padding; style2.border=`${style2.borderWidth}px ${style2.borderStyle||'solid'} ${style2.borderColor || '#000'}` style2.borderTop=`${style2.borderTopWidth}px ${style2.borderStyle||'solid'} ${style2.borderTopColor || style2.borderColor || '#000'}` style2.borderBottom=`${style2.borderBottomWidth}px ${style2.borderStyle||'solid'} ${style2.borderBottomColor|| style2.borderColor || '#000'}` style2.borderRight=`${style2.borderRightWidth ||style2.borderStartWidth}px ${ style2.borderStyle||'solid'} ${style2.borderRightColor|| style2.borderStartColor|| style2.borderColor || '#000'}` style2.borderLeft=`${style2.borderLeftWidth ||style2.borderEndWidth}px ${style2.borderStyle||'solid'} ${style2.borderLeftColor|| style2.borderEndColor|| style2.borderColor || '#000'}` style2.borderTopRightRadius=style2.borderTopRightRadius || style2.borderTopStartRadius || style2.borderRadius; style2.borderTopLeftRadius=style2.borderTopLeftRadius || style2.borderTopEndRadius || style2.borderRadius; style2.borderBottomRightRadius=style2.borderBottomRightRadius || style2.borderBottomStartRadius || style2.borderRadius; style2.borderBottomLeftRadius=style2.borderBottomLeftRadius || style2.borderBottomEndRadius || style2.borderRadius; if(style2.left==undefined) style2.left=style2.end; if(style2.right==undefined) style2.right=style2.start; style2.shadowOffset && (style2['-webkit-box-shadow']= `${style2.shadowOffset.width}px ${style2.shadowOffset.height}px 4px ${hex2rgb(style2.shadowColor,style2.shadowOpacity || 1)}`); style2.zIndex= style2.zIndex || style2.elevation; /* if(style.tintColor){//for support image icon tint color in react project style.color=style.tintColor; style.fontSize=style.width || style.height; return ( <View {...props} style={style} className={props.source} /> ); }*/ return ( <img src={source} {...props} style={style2} className={classes.main} /> ); }
gogrlx/grlx
certs/tls.go
package certs import ( "bufio" "bytes" "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "math/big" "net" "os" "time" "github.com/spf13/viper" log "github.com/taigrr/log-socket/log" ) func publicKey(priv interface{}) interface{} { switch k := priv.(type) { case *rsa.PrivateKey: return &k.PublicKey case *ecdsa.PrivateKey: return &k.PublicKey case ed25519.PrivateKey: return k.Public().(ed25519.PublicKey) default: return nil } } var notBefore = time.Now() func genCACert() { RootCAPriv := viper.GetString("RootCAPriv") RootCA := viper.GetString("RootCA") _, err := os.Stat(RootCAPriv) if !os.IsNotExist(err) { _, err = os.Stat(RootCAPriv) if !os.IsNotExist(err) { log.Trace("Found a RootCA keypair, not generating a new one...") return } } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) caCert := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: viper.GetStringSlice("Organization"), }, NotBefore: notBefore, NotAfter: notBefore.Add(viper.GetDuration("CertificateValidTime")), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}, BasicConstraintsValid: true, } caCert.IsCA = true caPrivKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { log.Panic(err.Error()) } // create the CA caBytes, err := x509.CreateCertificate(rand.Reader, &caCert, &caCert, &caPrivKey.PublicKey, caPrivKey) if err != nil { log.Panic(err.Error()) } // pem encode caPEM := new(bytes.Buffer) pem.Encode(caPEM, &pem.Block{ Type: "CERTIFICATE", Bytes: caBytes, }) certOut, err := os.Create(RootCA) if err != nil { log.Fatalf("%v", err) } if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: caBytes}); err != nil { log.Fatalf("%v", err) } if err := certOut.Close(); err != nil { log.Fatalf("%v", err) } log.Debugf("wrote %s", RootCA) keyOut, err := os.OpenFile(RootCAPriv, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatalf("%v", err) } privBytes, err := x509.MarshalPKCS8PrivateKey(caPrivKey) if err != nil { log.Fatalf("Unable to marshal private key: %v", err) } if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { log.Fatalf("Failed to write data to key.pem: %v", err) } if err := keyOut.Close(); err != nil { log.Fatalf("Error closing key.pem: %v", err) } } func GenCert() { // check if certificates already exist first CertFile := viper.GetString("CertFile") KeyFile := viper.GetString("KeyFile") RootCA := viper.GetString("RootCA") _, err := os.Stat(CertFile) if !os.IsNotExist(err) { _, err = os.Stat(KeyFile) if !os.IsNotExist(err) { log.Trace("Found a TLS keypair, not generating a new one...") return } } genCACert() file, err := os.Open(RootCA) if err != nil { log.Panic(err) } defer file.Close() stats, statsErr := file.Stat() if statsErr != nil { log.Panic(err) } var size int64 = stats.Size() bytes := make([]byte, size) bufr := bufio.NewReader(file) _, err = bufr.Read(bytes) block, _ := pem.Decode(bytes) caCert, err := x509.ParseCertificate(block.Bytes) if err != nil { log.Panic(err.Error()) } file2, err := os.Open(viper.GetString("RootCAPriv")) if err != nil { log.Panic(err) } defer file2.Close() stats, statsErr = file2.Stat() if statsErr != nil { log.Panic(err) } size = stats.Size() bytes2 := make([]byte, size) bufr2 := bufio.NewReader(file2) _, err = bufr2.Read(bytes2) block2, _ := pem.Decode(bytes2) caPriv, err := x509.ParsePKCS8PrivateKey(block2.Bytes) if err != nil { log.Panic(err.Error()) } hosts := viper.GetStringSlice("CertHosts") var priv interface{} priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { log.Fatalf("Failed to generate private key: %v", err) } // ECDSA, ED25519 and RSA subject keys should have the DigitalSignature // KeyUsage bits set in the x509.Certificate template keyUsage := x509.KeyUsageDigitalSignature keyUsage |= x509.KeyUsageCertSign serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { log.Fatalf("Failed to generate serial number: %v", err) } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: viper.GetStringSlice("Organization"), }, NotBefore: notBefore, NotAfter: notBefore.Add(viper.GetDuration("CertificateValidTime")), KeyUsage: keyUsage, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } for _, h := range hosts { if ip := net.ParseIP(h); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, h) } } template.IsCA = false derBytes, err := x509.CreateCertificate(rand.Reader, &template, caCert, publicKey(priv), caPriv) if err != nil { log.Fatalf("Failed to create certificate: %v", err) } certOut, err := os.Create(CertFile) if err != nil { log.Fatalf("Failed to open cert.pem for writing: %v", err) } if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { log.Fatalf("Failed to write data to cert.pem: %v", err) } if err := certOut.Close(); err != nil { log.Fatalf("Error closing cert.pem: %v", err) } log.Debug("wrote cert.pem") keyOut, err := os.OpenFile(KeyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatalf("Failed to open key.pem for writing: %v", err) return } privBytes, err := x509.MarshalPKCS8PrivateKey(priv) if err != nil { log.Fatalf("Unable to marshal private key: %v", err) } if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { log.Fatalf("Failed to write data to key.pem: %v", err) } if err := keyOut.Close(); err != nil { log.Fatalf("Error closing key.pem: %v", err) } log.Debug("wrote key.pem") } func RotateTLSCerts() { //TODO }
Sy14r/Cryptbreaker
imports/api/counters/methods.js
<reponame>Sy14r/Cryptbreaker /** * Meteor methods */ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import SimpleSchema from 'simpl-schema'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { LoggedInMixin } from 'meteor/tunifight:loggedin-mixin'; import { MethodHooks } from 'meteor/lacosta:method-hooks'; import { CallPromiseMixin } from 'meteor/didericis:callpromise-mixin'; import Counters from './counters.js'; /** **************** Helpers **************** */ const mixins = [LoggedInMixin, MethodHooks, CallPromiseMixin]; // not logged in error message const checkLoggedInError = { error: 'notLogged', message: 'You need to be logged in to call this method', reason: 'You need to login', }; /** **************** Methods **************** */ /** * countersIncrease */ // eslint-disable-next-line no-unused-vars, arrow-body-style const beforeHookExample = (methodArgs, methodOptions) => { // console.log('countersIncrease before hook'); // perform tasks return methodArgs; }; // eslint-disable-next-line no-unused-vars, arrow-body-style const afterHookExample = (methodArgs, returnValue, methodOptions) => { // console.log('countersIncrease: after hook:'); // perform tasks return returnValue; }; export const countersIncrease = new ValidatedMethod({ name: 'counters.increase', mixins, beforeHooks: [beforeHookExample], afterHooks: [afterHookExample], checkLoggedInError, checkRoles: { roles: ['admin', 'user'], rolesError: { error: 'not-allowed', message: 'You are not allowed to call this method', }, }, validate: new SimpleSchema({ _id: { type: String, optional: false, }, }).validator(), run({ _id }) { // console.log('counters.increase', _id); if (Meteor.isServer) { // secure code - not available on the client } // call code on client and server (optimistic UI) return Counters.update( { _id }, { $inc: { count: 1, }, } ); }, }); /** * used for example test in methods.tests.js */ export const countersInsert = new ValidatedMethod({ name: 'counters.insert', mixin: [CallPromiseMixin], validate: null, run() { const _id = Random.id(); // console.log('counters.insert', _id); const counterId = Counters.insert({ _id, count: Number(0), }); return counterId; }, });
Lionjudge9061-corp/oci-go-sdk
artifacts/update_container_repository_details.go
<filename>artifacts/update_container_repository_details.go<gh_stars>0 // Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Container Images API // // API covering the Registry (https://docs.cloud.oracle.com/iaas/Content/Registry/Concepts/registryoverview.htm) services. // Use this API to manage resources such as container images and repositories. // package artifacts import ( "github.com/oracle/oci-go-sdk/v36/common" ) // UpdateContainerRepositoryDetails Update container repository request details. type UpdateContainerRepositoryDetails struct { // Whether the repository is immutable. Images cannot be overwritten in an immutable repository. IsImmutable *bool `mandatory:"false" json:"isImmutable"` // Whether the repository is public. A public repository allows unauthenticated access. IsPublic *bool `mandatory:"false" json:"isPublic"` Readme *ContainerRepositoryReadme `mandatory:"false" json:"readme"` } func (m UpdateContainerRepositoryDetails) String() string { return common.PointerString(m) }
panpawang/java-demo
design-pattern/src/main/java/builder/vacation/Vacation.java
package builder.vacation; import java.util.ArrayList; import java.util.List; public class Vacation { String name; List<Accommodation> accommodations = new ArrayList<Accommodation>(); List<String> events = new ArrayList<String>(); public void setName(String name) { this.name = name; } public void setAccommodations(List<Accommodation> accommodations) { this.accommodations = accommodations; } public void setEvents(List<String> events) { this.events = events; } public String toString() { StringBuffer display = new StringBuffer(); display.append("---- " + this.name + " ----\n"); for (Accommodation a : accommodations) { display.append(a); } for (String e : events) { display.append(e + "\n"); } return display.toString(); } }
storage4grid/PROFESS-PROFEV
connector/priceConnector.py
""" Created on Mär 27 12:18 2019 @author: nishit """ import datetime from connector.apiConnector import ApiConnector from utils_intern.messageLogger import MessageLogger logger = MessageLogger.get_logger_parent() class PriceConnector(ApiConnector): def __init__(self, url, config, house): super().__init__(url, config, house, "price") def update_url(self): today = datetime.datetime.now() start_date = today.strftime("%Y-%m-%d") today = today + datetime.timedelta(days=2) end_date = today.strftime("%Y-%m-%d") pos = self.url.find("/prices") base_url = self.url[0:pos + 7] self.url = base_url + "/" + start_date + "/" + end_date def extract_data(self, raw_data): time_series = raw_data["Publication_MarketDocument"]["TimeSeries"] data = [] if isinstance(time_series, list): for time_frame in time_series: self.extract_time_series(data, time_frame) elif isinstance(time_series, dict): self.extract_time_series(data, time_series) if len(data) < 48: logger.error("Less than 48 hrs of price data") logger.debug("raw price data = "+str(raw_data)) logger.debug("raw price data = " + str(raw_data)) return data def extract_time_series(self, data, time_frame): unit = time_frame["price_Measure_Unit.name"] start_time = time_frame["Period"]["timeInterval"]["start"] start_time = datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%MZ") start_time = start_time.timestamp() for point in time_frame["Period"]["Point"]: position = int(point["position"]) - 1 price = float(point["price.amount"]) t = start_time + (position - 1) * 3600 data.append([t, price, unit])
whp1473/flymock
flymock/src/main/java/com/hoping/owl/flymock/placeholder/handle/NaturalHandle.java
package com.hoping.owl.flymock.placeholder.handle; import com.hoping.owl.flymock.FlyRandom; import com.hoping.owl.flymock.placeholder.AbstractPlaceholderHandle; import com.hoping.owl.flymock.placeholder.PlaceholderHandle; import com.hoping.owl.flymock.placeholder.PlaceholderWrap; import java.util.List; /** * Created by <NAME> on 2019/4/10 * * @author <NAME> */ public class NaturalHandle extends AbstractPlaceholderHandle<Integer> { @Override public Integer invoke(PlaceholderWrap placeholderWrap) { List<String> args = placeholderWrap.getArgs(); if (args == null || args.size() == 0) { return FlyRandom.natural(); } if (args.size() == 1) { return FlyRandom.natural(Integer.parseInt(args.get(0))); } if (args.size() == 2) { return FlyRandom.natural(Integer.parseInt(args.get(0)), Integer.parseInt(args.get(1))); } return FlyRandom.natural(); } @Override public String key() { return "natural"; } }
BurningBright/lucene
contrib/xml-query-parser/src/java/org/apache/lucene/xmlparser/builders/SpanNearBuilder.java
package org.apache.lucene.xmlparser.builders; import java.util.ArrayList; import org.apache.lucene.search.spans.SpanNearQuery; import org.apache.lucene.search.spans.SpanQuery; import org.apache.lucene.xmlparser.DOMUtils; import org.apache.lucene.xmlparser.ParserException; import org.w3c.dom.Element; import org.w3c.dom.Node; public class SpanNearBuilder extends SpanBuilderBase { SpanQueryBuilder factory; public SpanNearBuilder(SpanQueryBuilder factory) { this.factory=factory; } public SpanQuery getSpanQuery(Element e) throws ParserException { String slopString=DOMUtils.getAttributeOrFail(e,"slop"); int slop=Integer.parseInt(slopString); boolean inOrder=DOMUtils.getAttribute(e,"inOrder",false); ArrayList spans=new ArrayList(); for (Node kid = e.getFirstChild(); kid != null; kid = kid.getNextSibling()) { if (kid.getNodeType() == Node.ELEMENT_NODE) { spans.add(factory.getSpanQuery((Element) kid)); } } SpanQuery[] spanQueries=(SpanQuery[]) spans.toArray(new SpanQuery[spans.size()]); SpanNearQuery snq=new SpanNearQuery(spanQueries,slop,inOrder); return snq; } }
neepoo/acwing
advanced/01dp/01_dp/02_lis/1012/main.go
<filename>advanced/01dp/01_dp/02_lis/1012/main.go /* https://www.acwing.com/problem/content/1012/ 某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统。 但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。 某天,雷达捕捉到敌国的导弹来袭。 由于该系统还在试用阶段,所以只有一套系统,因此有可能不能拦截所有的导弹。 输入导弹依次飞来的高度(雷达给出的高度数据是不大于30000的正整数,导弹数不超过1000),计算这套系统最多能拦截多少导弹,如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。 输入格式 共一行,输入导弹依次飞来的高度。 输出格式 第一行包含一个整数,表示最多能拦截的导弹数。 第二行包含一个整数,表示要拦截所有导弹最少要配备的系统数。 数据范围 雷达给出的高度数据是不大于 30000 的正整数,导弹数不超过 1000。 输入样例: 389 207 155 300 299 170 158 65 输出样例: 6 2 */ package main import ( "bufio" . "fmt" "os" "strconv" "strings" ) const N = 1010 var ( n int a, f, g [N]int ) func max(a int, b int) int { if a > b { return a } return b } func main() { reader := bufio.NewReader(os.Stdin) scanner := bufio.NewScanner(reader) scanner.Scan() line := scanner.Text() tokens := strings.Split(line, " ") n = len(tokens) var ans int for idx, s := range tokens { v, _ := strconv.Atoi(s) a[idx+1] = v } for i := 1; i <= n; i++ { f[i] = 1 for j := 1; j < i; j++ { if a[j] >= a[i] { f[i] = max(f[i], f[j]+1) } } ans = max(ans, f[i]) } Println(ans) // question2 var cnt int for i := 1; i <= n; i++ { k := 1 // 第几个导弹系统 // 找到比他高或相等的最低的一个 for k <= cnt && a[i] > g[k] { k++ } g[k] = a[i] if k > cnt{ cnt = k } } Println(cnt) }
pengcash/MEUH
sdk/appcenter/src/main/java/com/microsoft/appcenter/utils/context/UserIdContext.java
<gh_stars>1-10 /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ package com.microsoft.appcenter.utils.context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import com.microsoft.appcenter.utils.AppCenterLog; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static com.microsoft.appcenter.AppCenter.LOG_TAG; import static com.microsoft.appcenter.Constants.COMMON_SCHEMA_PREFIX_SEPARATOR; /** * Utility to store and retrieve values for user identifiers. */ public class UserIdContext { /** * Custom App User ID prefix for Common Schema. */ private static final String CUSTOM_PREFIX = "c"; /** * Maximum allowed length for user identifier for App Center server. */ @VisibleForTesting public static final int USER_ID_APP_CENTER_MAX_LENGTH = 256; /** * Unique instance. */ private static UserIdContext sInstance; /** * Current user identifier. */ private String mUserId; /** * Global listeners collection. */ private final Set<Listener> mListeners = Collections.newSetFromMap(new ConcurrentHashMap<Listener, Boolean>()); /** * Get unique instance. * * @return unique instance. */ public static synchronized UserIdContext getInstance() { if (sInstance == null) { sInstance = new UserIdContext(); } return sInstance; } @VisibleForTesting public static synchronized void unsetInstance() { sInstance = null; } /** * Check if userId is valid for One Collector. * * @param userId userId. * @return true if valid, false otherwise. */ public static boolean checkUserIdValidForOneCollector(String userId) { if (userId == null) { return true; } if (userId.isEmpty()) { AppCenterLog.error(LOG_TAG, "userId must not be empty."); return false; } int prefixIndex = userId.indexOf(COMMON_SCHEMA_PREFIX_SEPARATOR); if (prefixIndex >= 0) { String prefix = userId.substring(0, prefixIndex); if (!prefix.equals(CUSTOM_PREFIX)) { AppCenterLog.error(LOG_TAG, String.format("userId prefix must be '%s%s', '%s%s' is not supported.", CUSTOM_PREFIX, COMMON_SCHEMA_PREFIX_SEPARATOR, prefix, COMMON_SCHEMA_PREFIX_SEPARATOR)); return false; } else if (prefixIndex == userId.length() - 1) { AppCenterLog.error(LOG_TAG, "userId must not be empty."); return false; } } return true; } /** * Check if userId is valid for App Center. * * @param userId userId. * @return true if valid, false otherwise. */ public static boolean checkUserIdValidForAppCenter(String userId) { if (userId != null && userId.length() > USER_ID_APP_CENTER_MAX_LENGTH) { AppCenterLog.error(LOG_TAG, "userId is limited to " + USER_ID_APP_CENTER_MAX_LENGTH + " characters."); return false; } return true; } /** * Add 'c:' prefix to userId if the userId has no prefix. * * @param userId userId. * @return prefixed userId or null if the userId was null. */ public static String getPrefixedUserId(String userId) { if (userId != null && !userId.contains(COMMON_SCHEMA_PREFIX_SEPARATOR)) { return CUSTOM_PREFIX + COMMON_SCHEMA_PREFIX_SEPARATOR + userId; } return userId; } /** * Adds listener to user context. * * @param listener listener to be notified of changes. */ public void addListener(@NonNull Listener listener) { mListeners.add(listener); } /** * Removes a specific listener. * * @param listener listener to be removed. */ public void removeListener(@NonNull Listener listener) { mListeners.remove(listener); } /** * Get current identifier. * * @return user identifier. */ public synchronized String getUserId() { return mUserId; } /** * Set current user identifier. * * @param userId user identifier. */ public void setUserId(String userId) { if (!updateUserId(userId)) { return; } /* Call listeners so that they can react on new token. */ for (Listener listener : mListeners) { listener.onNewUserId(mUserId); } } /** * Update user identifier. * * @param userId user identifier. * @return true if user identifier is updated. */ private synchronized boolean updateUserId(String userId) { if (TextUtils.equals(mUserId, userId)) { return false; } mUserId = userId; return true; } public interface Listener { /** * Called whenever a new user id set. * * @param userId user identifier. */ void onNewUserId(String userId); } }
jcook00/q2-api-client
q2_api_client/clients/base_q2_client.py
<reponame>jcook00/q2-api-client<filename>q2_api_client/clients/base_q2_client.py from q2_api_client.clients.rest_client import RestClient from q2_api_client.endpoints.mobile_ws_endpoints import LoginEndpoint from q2_api_client.utils.url import URL class BaseQ2Client(RestClient): def __init__(self, **kwargs): super().__init__(**kwargs) self._connect_timeout = kwargs.get('connect_timeout', 60) self._read_timeout = kwargs.get('read_timeout', 120) self._scheme = kwargs.get('scheme', "https") self._base_path = kwargs.get('base_path') self._headers['Accept'] = "application/json" self._headers['q2token'] = kwargs.get('q2token') if kwargs.get('q2token') is not None else self._get_q2token() def _get_q2token(self): """Sends a logon POST request and returns the Q2 token from the response headers. :return: the q2token header value :rtype: str :raises HTTPError: failed to authenticate """ request_body = {'userId': self._username, 'password': <PASSWORD>} endpoint = LoginEndpoint.LOGON_USER.value response = self._post(url=self._build_url(endpoint), json=request_body) response.raise_for_status() return response.headers.get('q2token') def _build_url(self, endpoint='/'): """Builds a URL using the endpoint. :param str endpoint: the endpoint to add to the path :return: the URL :rtype: str """ path = endpoint if self._base_path is None else "".join((self._base_path, endpoint)) url = URL(scheme=self._scheme, host=self._host, port=self._port, path=path) return url.build()
xfs-network/xfswallet-chrome
src/App.js
<filename>src/App.js import React, { Component, createContext, useContext, useState } from "react"; import { Switch, Route, Redirect, Router, } from "react-router-dom"; import './App.css'; import Initial from "./Initial"; import CreatePage from "./CreatePage"; import HomePage from "./HomePage"; import AuthPage from "./AuthPage" import SendPage from "./SendPage"; import AccoutMgrPage from "./AccoutMgrPage"; import AccountDetailPage from "./AccountDetailPage"; import CreateWalletPage from "./CreateWalletPage"; import KeyExportPage from "./KeyExportPage"; import KeyImportPage from "./KeyImportPage"; import NetworkMgrPage from "./NetworkMgrPage"; import NewNetwork from "./newnetwork"; import NetworkDetail from "./networkdetail"; import ResetNoncePage from "./resetnoncepage"; import ConnectPage from './ConnectPage'; import SendTxPage from './SendTxPage'; function PrivateRoute({ children, initialed, authed,path, ...props }) { console.log('privateroute', path); return <Route {...props} render={() => { if (initialed && authed) { return (children); }else if(!initialed){ return <Redirect to={{ pathname: '/initial', state: {from: path}, }} /> } else { return <Redirect to={{ pathname: '/auth', state: {from: path}, }} /> } }} /> } function setTimeoutAsync(t) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, t); }) } function ProvideAuth({ children, authed }) { return ( <div> {children} </div> ); } function InitialRoute({ children, initialed, ...props }) { const {history} = props; const {location: {state}} = history; if (initialed) { history.replace(state.from||'/'); } return <Route {...props}> {children} </Route>; } function AuthRoute({ children, authed, ...props }) { const {history} = props; const {location: {state}} = history; if (authed) { history.replace(state.from||'/'); } return <Route {...props}> {React.cloneElement(children)} </Route>; } async function checkAuth(globaldb) { let last = await globaldb.getPasswordLockTime(); if (!last){ return false; } let now = new Date().getTime(); return !(now - last > 0); } async function checkInitialization(globaldb) { let pass = await globaldb.getPassword(); if (!pass) { return false; } return true; } class App extends Component { constructor(props) { super(props); this.state = { authed: false, initialed: false, pageState: false, launchParams: {} } } async componentDidMount() { const {history, db: { extradb, globaldb } } = this.props; let initiated = await checkInitialization(globaldb); let authed = await checkAuth(globaldb); this.setState({ initialed: initiated, authed: authed}); const pageState = await extradb.popPageState(); if (pageState){ console.log('pushle', pageState); this.setState({launchParams: {...pageState}}); history.push(pageState.page); } } async unlockPassword(){ this.setState({authed: true }); } async setupPassword(){ this.setState({initialed: true }); } render() { return ( <ProvideAuth {...this.state}> <Router {...this.props}> <Switch> <PrivateRoute exact path="/" {...this.props} {...this.state}> <HomePage {...this.props} {...this.state}/> </PrivateRoute> <InitialRoute exact path="/initial" {...this.props} {...this.state}> <Initial {...this.props} {...this.state }/> </InitialRoute> <AuthRoute exact path="/auth" {...this.props} {...this.state} > <AuthPage {...this.props} unlockPasswordFn={()=>{this.unlockPassword()}}/> </AuthRoute> <Route exact path="/createpage"> <CreatePage {...this.props} setupPasswordFn={()=>{this.setupPassword()}} unlockPasswordFn={()=>{this.unlockPassword()}} /> </Route> <Route exact path="/keyimport" {...this.props} {...this.state}> <KeyImportPage {...this.props}/> </Route> <PrivateRoute exact path="/send" {...this.props} {...this.state}> <SendPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/accountmgr" {...this.props} {...this.state}> <AccoutMgrPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/accountdetail" {...this.props} {...this.state}> <AccountDetailPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/accountdetail" {...this.props} {...this.state}> <AccountDetailPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/createwallet" {...this.props} {...this.state}> <CreateWalletPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/keyexport" {...this.props} {...this.state}> <KeyExportPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/keyimport" {...this.props} {...this.state}> <KeyImportPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/networkmgr" {...this.props} {...this.state}> <NetworkMgrPage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/newnetwork" {...this.props} {...this.state}> <NewNetwork {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/networkdetail" {...this.props} {...this.state}> <NetworkDetail {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/resetnonce" {...this.props} {...this.state}> <ResetNoncePage {...this.props}/> </PrivateRoute> <PrivateRoute exact path="/connect" {...this.props} {...this.state}> <ConnectPage {...this.props} {...this.state}/> </PrivateRoute> <PrivateRoute exact path="/sendtx" {...this.props} {...this.state}> <SendTxPage {...this.props} {...this.state}/> </PrivateRoute> </Switch> </Router> </ProvideAuth> ); } } export default App;
binosys/mtc2016_architecture_sample
app/src/test/java/de/binosys/android/mtc2016/business/DeviceManagerTest.java
/* * Copyright Binosys GmbH(c) 2015. All rights reserved. */ package de.binosys.android.mtc2016.business; import org.junit.Test; public class DeviceManagerTest { @Test public void testGetDeviceWith() throws Exception { } @Test public void testGetAllDevices() throws Exception { } }
perandersson/everstore-server
Shared/Mutex/Unix/UnixMutex.cpp
// // Copyright (c) 2019 West Coast Code AB. All rights reserved. // #include "UnixMutex.hpp" #include "../../Process/Process.hpp" #include "../../Log/Log.hpp" #include <sys/mman.h> #include <sys/fcntl.h> ESErrorCode OsMutex::Create(const string& name, OsMutex* mutex) { memset(mutex, 0, sizeof(OsMutex)); const string sharedMemoryName = #ifdef __APPLE__ string("/tmp/everstore/") + name; #else string("/") + name; #endif // Setup the actual mutex object mutex->ptr = nullptr; mutex->onHost = true; memset(mutex->name, 0, sizeof(mutex->name)); strncpy(mutex->name, sharedMemoryName.c_str(), sharedMemoryName.size()); // Give us a handle used for share memory access - used for inter-process support of the mutex #ifdef __APPLE__ int shm_fd = open(mutex->name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); #else int shm_fd = shm_open(mutex->name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); #endif if (shm_fd == -1) { Log::Write(Log::Error, "UnixMutex | %s failed to open share memory handle", mutex->name); return ESERR_MUTEX_CREATE; } // Use truncate as a way to set the size of the shared memory to a specific amount if (ftruncate(shm_fd, sizeof(pthread_mutex_t)) == -1) { close(shm_fd); shm_unlink(mutex->name); return ESERR_MUTEX_CREATE; } // Map the memory to the mutex mutex->ptr = (pthread_mutex_t*) mmap(nullptr, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); // From documentation "http://man7.org/linux/man-pages/man3/shm_open.3.html": // After a call to mmap(2) the file descriptor may be closed without affecting the // memory mapping. close(shm_fd); if (mutex->ptr == nullptr) { Log::Write(Log::Error, "UnixMutex | No shared memory received for %s ", mutex->name); shm_unlink(mutex->name); return ESERR_MUTEX_CREATE; } memset(mutex->ptr, 0, sizeof(pthread_mutex_t)); // Initialize shared mutex model pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); #ifndef _POSIX_THREAD_PROCESS_SHARED #error "This platform does not support process shared mutex!" #else auto ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); if (ret != 0) { Log::Write(Log::Error, "UnixMutex | %s failed on pthread_mutexattr_setpshared", mutex->name); return ESERR_MUTEX_CREATE; } #endif pthread_mutex_init(mutex->ptr, &attr); pthread_mutexattr_destroy(&attr); return 0; } ESErrorCode OsMutex::Destroy(OsMutex* mutex) { // Verify if the mutex is already destroyed if (IsInvalid(mutex)) { return ESERR_MUTEX_DESTROYED; } // Release the mutexes internal memory if on the host. This is only needed to be done once, and should thus be done // by the application using the mutex last (the server and not the worker) if (mutex->onHost) { pthread_mutex_destroy(mutex->ptr); } // Unmap the memory for the mutex munmap(mutex->ptr, sizeof(pthread_mutex_t)); shm_unlink(mutex->name); return ESERR_NO_ERROR; } ESErrorCode OsMutex::Lock(OsMutex* mutex, uint32_t timeout) { if (IsInvalid(mutex)) { return ESERR_MUTEX_DESTROYED; } // TODO OSX do not support pthread_mutex_timedlock. Find an alternate solution for it const int ret = pthread_mutex_lock(mutex->ptr); return ret == 0 ? ESERR_NO_ERROR : ESERR_MUTEX_LOCK_FAILED; } ESErrorCode OsMutex::Unlock(OsMutex* mutex) { if (IsInvalid(mutex)) { return ESERR_MUTEX_DESTROYED; } const int ret = pthread_mutex_unlock(mutex->ptr); return ret == 0 ? ESERR_NO_ERROR : ESERR_MUTEX_LOCK_FAILED; } ESErrorCode OsMutex::ShareWith(OsMutex* mutex, OsProcess* process) { if (IsInvalid(mutex)) { return ESERR_MUTEX_DESTROYED; } if (OsProcess::IsInvalid(process)) { Log::Write(Log::Error, "UnixMutex | Failed to share %s over UnixSocket(%d)", mutex->name, process->unixSocket); return ESERR_INVALID_ARGUMENT; } // Send the name of the lock to the sub-process. It's up to the child-process to attach itself to the mutex const auto writtenBytes = OsProcess::Write(process, mutex->name, sizeof mutex->name); if (writtenBytes != sizeof mutex->name) { return ESERR_PIPE_WRITE; } return ESERR_NO_ERROR; } ESErrorCode OsMutex::LoadFromProcess(OsMutex* mutex, OsProcess* process) { if (mutex == nullptr) { return ESERR_INVALID_ARGUMENT; } if (OsProcess::IsInvalid(process)) { return ESERR_PROCESS_DESTROYED; } memset(mutex, 0, sizeof(OsMutex)); // Read the name of the mutex so that we can attach it to this process const auto readBytes = OsProcess::Read(process, mutex->name, sizeof mutex->name); if (readBytes != sizeof mutex->name) { Log::Write(Log::Error, "OsMutex | Failed to read from UnixSocket(%d)", process->unixSocket); return ESERR_PIPE_READ; } // Open the shared memory. It should already exist because it should've been created by the parent process #ifdef __APPLE__ int shm_fd = open(mutex->name, O_RDWR, S_IRUSR | S_IWUSR); #else int shm_fd = shm_open(mutex->name, O_RDWR, S_IRUSR | S_IWUSR); #endif if (shm_fd == -1) { Log::Write(Log::Error, "UnixMutex | %s failed to open share memory handle", mutex->name); return ESERR_MUTEX_ATTACH; } // Map the memory to the mutex mutex->ptr = (pthread_mutex_t*) mmap(nullptr, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); // From documentation "http://man7.org/linux/man-pages/man3/shm_open.3.html": // After a call to mmap(2) the file descriptor may be closed without affecting the // memory mapping. close(shm_fd); if (mutex->ptr == nullptr) { Log::Write(Log::Error, "UnixMutex | No shared memory received for %s ", mutex->name); shm_unlink(mutex->name); return ESERR_MUTEX_ATTACH; } return ESERR_NO_ERROR; }
qinfangj/UniWebProject
components/forms/facilityData/formModels/alignmentsModel.js
<reponame>qinfangj/UniWebProject "use strict"; import fields from '../../../constants/fields'; import inputTypes from '../../../constants/inputTypes'; import optionsStoreKeys from '../../../constants/optionsStoreKeys'; import validators from '../../validators'; const alignmentsModel = { fields: [ { name: fields.ANALYSIS_TYPE_ID, width: 2, label: "Analysis type", inputType: inputTypes.DROPDOWN, optionsKey: optionsStoreKeys.PIPELINE_ANALYSIS_TYPES, required: true, },{ // "runs_output_folders" name: fields.RUN_ID, width: 5, label: "Run", inputType: inputTypes.DROPDOWN, optionsKey: optionsStoreKeys.RUNS_OUTPUT_FOLDERS, required: true, },{ // "basecallings_output_folders", name: fields.BASECALLING_ID, width: 5, label: "Unaligned data output folder", inputType: inputTypes.SEC_DROPDOWN, refModelName: "facilityDataForms.alignments." + fields.RUN_ID, optionsKey: optionsStoreKeys.BASECALLINGS_OUTPUT_FOLDERS_FOR_RUN, required: true, },{ name: fields.MAPPING_TOOL_ID, width: 2, label: "Mapping tool", inputType: inputTypes.DROPDOWN, optionsKey: optionsStoreKeys.MAPPING_TOOLS, required: true, },{ name: fields.ELAND_OUTPUT_DIR, width: 8, label: "Alignment output folder", inputType: inputTypes.TEXT, required: true, },{ name: fields.HAS_QC_PDFS, width: 2, label: "QC report", inputType: inputTypes.CHECKBOX, style: {marginTop: "34px", marginLeft: "10px"}, },{ name: fields.CONFIG_FILE_CONTENT, width: 12, label: "Config file content", inputType: inputTypes.TEXTAREA, rows: 5, },{ name: fields.COMMENT, width: 12, label: "Comment", inputType: inputTypes.TEXTAREA, } ], model: "alignments" }; export default alignmentsModel;
PhaseDMS/phase
src/transmittals/migrations/0055_auto_20160303_1439.py
from django.db import migrations, models import transmittals.fields import privatemedia.storage class Migration(migrations.Migration): dependencies = [ ('transmittals', '0054_outgoingtransmittal_archived_pdf'), ] operations = [ migrations.AlterField( model_name='outgoingtransmittal', name='archived_pdf', field=transmittals.fields.OgtFileField(storage=privatemedia.storage.ProtectedStorage(), upload_to=transmittals.fields.ogt_file_path, null=True, verbose_name='Archived PDF', blank=True), ), ]
dummas2008/AndroidChromium
app/src/main/java/org/chromium/chrome/browser/bookmarks/BookmarkActionBar.java
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.bookmarks; import android.content.Context; import android.support.v7.widget.Toolbar.OnMenuItemClickListener; import android.text.TextUtils; import android.util.AttributeSet; import android.view.MenuItem; import android.view.View.OnClickListener; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkItem; import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkModelObserver; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.document.TabDelegate; import org.chromium.chrome.browser.widget.selection.SelectableListToolbar; import org.chromium.chrome.browser.widget.selection.SelectionDelegate; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.bookmarks.BookmarkType; import org.chromium.content_public.browser.LoadUrlParams; import java.util.List; /** * Main action bar of bookmark UI. It is responsible for displaying title and buttons * associated with the current context. */ public class BookmarkActionBar extends SelectableListToolbar<BookmarkId> implements BookmarkUIObserver, OnMenuItemClickListener, OnClickListener { private BookmarkItem mCurrentFolder; private BookmarkDelegate mDelegate; private BookmarkModelObserver mBookmarkModelObserver = new BookmarkModelObserver() { @Override public void bookmarkModelChanged() { onSelectionStateChange(mDelegate.getSelectionDelegate().getSelectedItemsAsList()); } }; public BookmarkActionBar(Context context, AttributeSet attrs) { super(context, attrs); setNavigationOnClickListener(this); inflateMenu(R.menu.bookmark_action_bar_menu); setOnMenuItemClickListener(this); getMenu().findItem(R.id.selection_mode_edit_menu_id).setTitle(R.string.edit_bookmark); getMenu().findItem(R.id.selection_mode_move_menu_id) .setTitle(R.string.bookmark_action_bar_move); getMenu().findItem(R.id.selection_mode_delete_menu_id) .setTitle(R.string.bookmark_action_bar_delete); getMenu() .findItem(R.id.selection_open_in_incognito_tab_id) .setTitle(ChromeFeatureList.isEnabled(ChromeFeatureList.INCOGNITO_STRINGS) ? R.string.contextmenu_open_in_private_tab : R.string.contextmenu_open_in_incognito_tab); // Wait to enable the selection mode group until the BookmarkDelegate is set. The // SelectionDelegate is retrieved from the BookmarkDelegate. getMenu().setGroupEnabled(R.id.selection_mode_menu_group, false); } @Override public void onNavigationBack() { if (mIsSearching) { super.onNavigationBack(); return; } mDelegate.openFolder(mCurrentFolder.getParentId()); } @Override public boolean onMenuItemClick(MenuItem menuItem) { hideOverflowMenu(); if (menuItem.getItemId() == R.id.edit_menu_id) { BookmarkAddEditFolderActivity.startEditFolderActivity(getContext(), mCurrentFolder.getId()); return true; } else if (menuItem.getItemId() == R.id.close_menu_id) { BookmarkUtils.finishActivityOnPhone(getContext()); return true; } else if (menuItem.getItemId() == R.id.search_menu_id) { mDelegate.openSearchUI(); return true; } SelectionDelegate<BookmarkId> selectionDelegate = mDelegate.getSelectionDelegate(); if (menuItem.getItemId() == R.id.selection_mode_edit_menu_id) { List<BookmarkId> list = selectionDelegate.getSelectedItemsAsList(); assert list.size() == 1; BookmarkItem item = mDelegate.getModel().getBookmarkById(list.get(0)); if (item.isFolder()) { BookmarkAddEditFolderActivity.startEditFolderActivity(getContext(), item.getId()); } else { BookmarkUtils.startEditActivity(getContext(), item.getId()); } return true; } else if (menuItem.getItemId() == R.id.selection_mode_move_menu_id) { List<BookmarkId> list = selectionDelegate.getSelectedItemsAsList(); if (list.size() >= 1) { BookmarkFolderSelectActivity.startFolderSelectActivity(getContext(), list.toArray(new BookmarkId[list.size()])); } return true; } else if (menuItem.getItemId() == R.id.selection_mode_delete_menu_id) { mDelegate.getModel().deleteBookmarks( selectionDelegate.getSelectedItems().toArray(new BookmarkId[0])); return true; } else if (menuItem.getItemId() == R.id.selection_open_in_new_tab_id) { openBookmarksInNewTabs(selectionDelegate.getSelectedItemsAsList(), new TabDelegate(false), mDelegate.getModel()); selectionDelegate.clearSelection(); return true; } else if (menuItem.getItemId() == R.id.selection_open_in_incognito_tab_id) { openBookmarksInNewTabs(selectionDelegate.getSelectedItemsAsList(), new TabDelegate(true), mDelegate.getModel()); selectionDelegate.clearSelection(); return true; } assert false : "Unhandled menu click."; return false; } void showLoadingUi() { setTitle(null); setNavigationButton(NAVIGATION_BUTTON_NONE); getMenu().findItem(R.id.search_menu_id).setVisible(false); getMenu().findItem(R.id.edit_menu_id).setVisible(false); } @Override protected void showNormalView() { super.showNormalView(); if (mDelegate == null) { getMenu().findItem(R.id.search_menu_id).setVisible(false); getMenu().findItem(R.id.edit_menu_id).setVisible(false); } } /** * Sets the delegate to use to handle UI actions related to this action bar. * @param delegate A {@link BookmarkDelegate} instance to handle all backend interaction. */ public void onBookmarkDelegateInitialized(BookmarkDelegate delegate) { mDelegate = delegate; mDelegate.addUIObserver(this); if (!delegate.isDialogUi()) getMenu().removeItem(R.id.close_menu_id); delegate.getModel().addObserver(mBookmarkModelObserver); getMenu().setGroupEnabled(R.id.selection_mode_menu_group, true); } // BookmarkUIObserver implementations. @Override public void onDestroy() { if (mDelegate == null) return; mDelegate.removeUIObserver(this); mDelegate.getModel().removeObserver(mBookmarkModelObserver); } @Override public void onFolderStateSet(BookmarkId folder) { mCurrentFolder = mDelegate.getModel().getBookmarkById(folder); getMenu().findItem(R.id.search_menu_id).setVisible(true); getMenu().findItem(R.id.edit_menu_id).setVisible(mCurrentFolder.isEditable()); // If this is the root folder, we can't go up anymore. if (folder.equals(mDelegate.getModel().getRootFolderId())) { setTitle(R.string.bookmarks); setNavigationButton(NAVIGATION_BUTTON_NONE); return; } if (mDelegate.getModel().getTopLevelFolderParentIDs().contains(mCurrentFolder.getParentId()) && TextUtils.isEmpty(mCurrentFolder.getTitle())) { setTitle(R.string.bookmarks); } else { setTitle(mCurrentFolder.getTitle()); } setNavigationButton(NAVIGATION_BUTTON_BACK); } @Override public void onSearchStateSet() {} @Override public void onSelectionStateChange(List<BookmarkId> selectedBookmarks) { super.onSelectionStateChange(selectedBookmarks); // The super class registers itself as a SelectionObserver before // #onBookmarkDelegateInitialized() is called. Return early if mDelegate has not been set. if (mDelegate == null) return; if (mIsSelectionEnabled) { // Editing a bookmark action on multiple selected items doesn't make sense. So disable. getMenu().findItem(R.id.selection_mode_edit_menu_id).setVisible( selectedBookmarks.size() == 1); getMenu().findItem(R.id.selection_open_in_incognito_tab_id) .setVisible(PrefServiceBridge.getInstance().isIncognitoModeEnabled()); // It does not make sense to open a folder in new tab. for (BookmarkId bookmark : selectedBookmarks) { BookmarkItem item = mDelegate.getModel().getBookmarkById(bookmark); if (item != null && item.isFolder()) { getMenu().findItem(R.id.selection_open_in_new_tab_id).setVisible(false); getMenu().findItem(R.id.selection_open_in_incognito_tab_id).setVisible(false); break; } } // Partner bookmarks can't move, so if the selection includes a partner bookmark, // disable the move button. for (BookmarkId bookmark : selectedBookmarks) { if (bookmark.getType() == BookmarkType.PARTNER) { getMenu().findItem(R.id.selection_mode_move_menu_id).setVisible(false); break; } } } else { mDelegate.notifyStateChange(this); } } private static void openBookmarksInNewTabs( List<BookmarkId> bookmarks, TabDelegate tabDelegate, BookmarkModel model) { for (BookmarkId id : bookmarks) { tabDelegate.createNewTab(new LoadUrlParams(model.getBookmarkById(id).getUrl()), TabLaunchType.FROM_LONGPRESS_BACKGROUND, null); } } }
AliYildizoz909/photo-channel-spa
src/redux/actions/home/homeActionCreators.js
<gh_stars>1-10 import { GET_FEED, GET_MOST_CHANNELS, GET_MOST_COMMENTS, GET_MOST_PHOTOS } from "./homeActionTypes" export const getMostChannelsSuccess = (channels) => ({ type: GET_MOST_CHANNELS, payload: channels }) export const getMostPhotosSuccess = (photos) => ({ type: GET_MOST_PHOTOS, payload: photos }) export const getMostCommentsSuccess = (photos) => ({ type: GET_MOST_COMMENTS, payload: photos }) export const getFeedSuccess = (photos) => ({ type: GET_FEED, payload: photos })
Alexgta/hackerrank
src/main/java/com/hackerrank/stdinout/SimpleScanner.java
package com.hackerrank.stdinout; import java.util.Scanner; public class SimpleScanner { //Write your code here static boolean flag = true; static int B,H; static { Scanner scan = new Scanner(System.in); B = scan.nextInt(); H = scan.nextInt(); try{ if(B <= 0 || H <= 0){ flag = false; throw new Exception("Breadth and height must be positive"); } } catch(Exception e){ System.out.println(e); } } public static void main(String[] args) { if(flag) { int area = B * H; System.out.print(area); } } public void checkType() { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); for(int i=0; i < t; i++) { try { long x=sc.nextLong(); System.out.println(x+" can be fitted in:"); if(x>=-128 && x<=127)System.out.println("* byte"); //Complete the code if(x >= -Math.pow(2, 15) && x <= Math.pow(2, 15) - 1) System.out.println("* short"); if(x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) System.out.println("* int"); if(x >= -Math.pow(2, 63) && x <= Math.pow(2, 63) - 1) System.out.println("* long"); } catch(Exception e) { System.out.println(sc.next()+" can't be fitted anywhere."); } } } public void readFewLines() { // read and print int, double, String Scanner scan = new Scanner(System.in); int a = scan.nextInt(); double b = scan.nextDouble(); scan.next(); String c = scan.next(); scan.close(); System.out.println(a); System.out.println(b); System.out.println(c); } //public static void main(String[] args) { public void printSome() { // using System.out.format Scanner sc=new Scanner(System.in); System.out.println("================================"); for(int i=0;i<3;i++) { String s1=sc.next(); int x = sc.nextInt(); System.out.format("%-15s%03d%n", s1, x); } System.out.println("================================"); } }
cdrage/ocdev
pkg/devfile/parser/data/common/project_helper.go
<reponame>cdrage/ocdev package common import "fmt" // GetDefaultSource get information about primary source // returns 3 strings: remote name, remote URL, reference(revision) func (ps GitLikeProjectSource) GetDefaultSource() (string, string, string, error) { // get git checkout information // if there are multiple remotes we are ignoring them, as we don't need to setup git repository as it is defined here, // the only thing that we need is to download the content var remoteName, remoteURL, revision string if ps.CheckoutFrom != nil && ps.CheckoutFrom.Revision != "" { revision = ps.CheckoutFrom.Revision } if len(ps.Remotes) > 1 { if ps.CheckoutFrom == nil { return "", "", "", fmt.Errorf("there are multiple git remotes but no checkoutFrom information") } remoteName = ps.CheckoutFrom.Remote if val, ok := ps.Remotes[remoteName]; ok { remoteURL = val } else { return "", "", "", fmt.Errorf("checkoutFrom.Remote is not defined in Remotes") } } else { // there is only one remote, using range to get it as there are not indexes for name, url := range ps.Remotes { remoteName = name remoteURL = url } } return remoteName, remoteURL, revision, nil }
maciejg-git/vue-bootstrap-icons
dist-remix/remix/Editor/strikethrough.js
<gh_stars>0 import { h } from 'vue' export default { name: "Strikethrough", vendor: "Rx", type: "", tags: ["strikethrough"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"rx-strikethrough","innerHTML":" <g> <path fill='none' d='M0 0h24v24H0z'/> <path d='M17.154 14c.23.516.346 1.09.346 1.72 0 1.342-.524 2.392-1.571 3.147C14.88 19.622 13.433 20 11.586 20c-1.64 0-3.263-.381-4.87-1.144V16.6c1.52.877 3.075 1.316 4.666 1.316 2.551 0 3.83-.732 3.839-2.197a2.21 2.21 0 0 0-.648-1.603l-.12-.117H3v-2h18v2h-3.846zm-4.078-3H7.629a4.086 4.086 0 0 1-.481-.522C6.716 9.92 6.5 9.246 6.5 8.452c0-1.236.466-2.287 1.397-3.153C8.83 4.433 10.271 4 12.222 4c1.471 0 2.879.328 4.222.984v2.152c-1.2-.687-2.515-1.03-3.946-1.03-2.48 0-3.719.782-3.719 2.346 0 .42.218.786.654 1.099.436.313.974.562 1.613.75.62.18 1.297.414 2.03.699z'/> </g>"}, ) } }
tsung-sc/Tsung-Go-shopping-project
models/goodsColor.go
package models import ( _ "github.com/jinzhu/gorm" ) type GoodsColor struct { Id int ColorName string ColorValue string Status int Checked bool `gorm:"-"` } func (GoodsColor) TableName() string { return "goods_color" }
angiechangpagne/ZeusMedia
flux-origins/components/Slider/CategorySlider/styles.js
import { colorGreyLight1 } from "../../../assets/base"; import { Dimensions } from "react-native"; export const SCREEN_HEIGHT = Dimensions.get("window").height; export const styles = { colorGreyLight1: { color: colorGreyLight1 }, viewPager: { height: SCREEN_HEIGHT }, reload: { position: "absolute", top: 10, right: 60, borderRadius: 50, width: 50, height: 50 }, dots: { position: "absolute", top: 10, right: 15, borderRadius: 50, width: 50, height: 50 } };
chunzhao/presto
presto-orc/src/test/java/com/facebook/presto/orc/TestTupleDomainFilterUtils.java
<gh_stars>0 /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.orc; import com.facebook.presto.Session; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.orc.TupleDomainFilter.BigintMultiRange; import com.facebook.presto.orc.TupleDomainFilter.BigintRange; import com.facebook.presto.orc.TupleDomainFilter.BigintValues; import com.facebook.presto.orc.TupleDomainFilter.BooleanValue; import com.facebook.presto.orc.TupleDomainFilter.BytesRange; import com.facebook.presto.orc.TupleDomainFilter.BytesValues; import com.facebook.presto.orc.TupleDomainFilter.DoubleRange; import com.facebook.presto.orc.TupleDomainFilter.FloatRange; import com.facebook.presto.orc.TupleDomainFilter.LongDecimalRange; import com.facebook.presto.orc.TupleDomainFilter.MultiRange; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.predicate.Domain; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.ExpressionDomainTranslator; import com.facebook.presto.sql.planner.LiteralEncoder; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.TypeProvider; import com.facebook.presto.sql.tree.BetweenPredicate; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.DoubleLiteral; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.GenericLiteral; import com.facebook.presto.sql.tree.InListExpression; import com.facebook.presto.sql.tree.InPredicate; import com.facebook.presto.sql.tree.IsNullPredicate; import com.facebook.presto.sql.tree.Literal; import com.facebook.presto.sql.tree.LongLiteral; import com.facebook.presto.sql.tree.NotExpression; import com.facebook.presto.sql.tree.NullLiteral; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.StringLiteral; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import io.airlift.slice.Slice; import io.airlift.slice.Slices; import org.joda.time.DateTime; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager; import static com.facebook.presto.orc.TupleDomainFilter.IS_NOT_NULL; import static com.facebook.presto.orc.TupleDomainFilter.IS_NULL; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.CharType.createCharType; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.DecimalType.createDecimalType; import static com.facebook.presto.spi.type.Decimals.encodeScaledValue; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.HyperLogLogType.HYPER_LOG_LOG; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.sql.ExpressionUtils.or; import static com.facebook.presto.sql.planner.LiteralEncoder.getMagicLiteralFunctionSignature; import static com.facebook.presto.sql.tree.BooleanLiteral.FALSE_LITERAL; import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.EQUAL; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.GREATER_THAN; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.GREATER_THAN_OR_EQUAL; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.IS_DISTINCT_FROM; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.LESS_THAN; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.LESS_THAN_OR_EQUAL; import static com.facebook.presto.sql.tree.ComparisonExpression.Operator.NOT_EQUAL; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.type.ColorType.COLOR; import static io.airlift.slice.SizeOf.SIZE_OF_LONG; import static java.util.Collections.nCopies; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestTupleDomainFilterUtils { private static final Session TEST_SESSION = testSessionBuilder() .setCatalog("tpch") .setSchema("tiny") .build(); private static final Symbol C_BIGINT = new Symbol("c_bigint"); private static final Symbol C_DOUBLE = new Symbol("c_double"); private static final Symbol C_VARCHAR = new Symbol("c_varchar"); private static final Symbol C_BOOLEAN = new Symbol("c_boolean"); private static final Symbol C_BIGINT_1 = new Symbol("c_bigint_1"); private static final Symbol C_DOUBLE_1 = new Symbol("c_double_1"); private static final Symbol C_VARCHAR_1 = new Symbol("c_varchar_1"); private static final Symbol C_TIMESTAMP = new Symbol("c_timestamp"); private static final Symbol C_DATE = new Symbol("c_date"); private static final Symbol C_COLOR = new Symbol("c_color"); private static final Symbol C_HYPER_LOG_LOG = new Symbol("c_hyper_log_log"); private static final Symbol C_VARBINARY = new Symbol("c_varbinary"); private static final Symbol C_DECIMAL_26_5 = new Symbol("c_decimal_26_5"); private static final Symbol C_DECIMAL_23_4 = new Symbol("c_decimal_23_4"); private static final Symbol C_INTEGER = new Symbol("c_integer"); private static final Symbol C_CHAR = new Symbol("c_char"); private static final Symbol C_DECIMAL_21_3 = new Symbol("c_decimal_21_3"); private static final Symbol C_DECIMAL_12_2 = new Symbol("c_decimal_12_2"); private static final Symbol C_DECIMAL_6_1 = new Symbol("c_decimal_6_1"); private static final Symbol C_DECIMAL_3_0 = new Symbol("c_decimal_3_0"); private static final Symbol C_DECIMAL_2_0 = new Symbol("c_decimal_2_0"); private static final Symbol C_SMALLINT = new Symbol("c_smallint"); private static final Symbol C_TINYINT = new Symbol("c_tinyint"); private static final Symbol C_REAL = new Symbol("c_real"); private static final TypeProvider TYPES = TypeProvider.copyOf(ImmutableMap.<Symbol, Type>builder() .put(C_BIGINT, BIGINT) .put(C_DOUBLE, DOUBLE) .put(C_VARCHAR, VARCHAR) .put(C_BOOLEAN, BOOLEAN) .put(C_BIGINT_1, BIGINT) .put(C_DOUBLE_1, DOUBLE) .put(C_VARCHAR_1, VARCHAR) .put(C_TIMESTAMP, TIMESTAMP) .put(C_DATE, DATE) .put(C_COLOR, COLOR) // Equatable, but not orderable .put(C_HYPER_LOG_LOG, HYPER_LOG_LOG) // Not Equatable or orderable .put(C_VARBINARY, VARBINARY) .put(C_DECIMAL_26_5, createDecimalType(26, 5)) .put(C_DECIMAL_23_4, createDecimalType(23, 4)) .put(C_INTEGER, INTEGER) .put(C_CHAR, createCharType(10)) .put(C_DECIMAL_21_3, createDecimalType(21, 3)) .put(C_DECIMAL_12_2, createDecimalType(12, 2)) .put(C_DECIMAL_6_1, createDecimalType(6, 1)) .put(C_DECIMAL_3_0, createDecimalType(3, 0)) .put(C_DECIMAL_2_0, createDecimalType(2, 0)) .put(C_SMALLINT, SMALLINT) .put(C_TINYINT, TINYINT) .put(C_REAL, REAL) .build()); private Metadata metadata; private LiteralEncoder literalEncoder; @BeforeClass public void setup() { metadata = createTestMetadataManager(); literalEncoder = new LiteralEncoder(metadata.getBlockEncodingSerde()); } @Test public void testBoolean() { assertEquals(toFilter(equal(C_BOOLEAN, TRUE_LITERAL)), BooleanValue.of(true, false)); assertEquals(toFilter(equal(C_BOOLEAN, FALSE_LITERAL)), BooleanValue.of(false, false)); assertEquals(toFilter(not(equal(C_BOOLEAN, TRUE_LITERAL))), BooleanValue.of(false, false)); assertEquals(toFilter(not(equal(C_BOOLEAN, FALSE_LITERAL))), BooleanValue.of(true, false)); assertEquals(toFilter(isDistinctFrom(C_BOOLEAN, TRUE_LITERAL)), BooleanValue.of(false, true)); assertEquals(toFilter(isDistinctFrom(C_BOOLEAN, FALSE_LITERAL)), BooleanValue.of(true, true)); } @Test public void testBigint() { assertEquals(toFilter(equal(C_BIGINT, bigintLiteral(2L))), BigintRange.of(2L, 2L, false)); assertEquals(toFilter(not(equal(C_BIGINT, bigintLiteral(2L)))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 1L, false), BigintRange.of(3L, Long.MAX_VALUE, false)), false)); assertEquals(toFilter(lessThan(C_BIGINT, bigintLiteral(2L))), BigintRange.of(Long.MIN_VALUE, 1L, false)); assertEquals(toFilter(lessThanOrEqual(C_BIGINT, bigintLiteral(2L))), BigintRange.of(Long.MIN_VALUE, 2L, false)); assertEquals(toFilter(not(lessThan(C_BIGINT, bigintLiteral(2L)))), BigintRange.of(2L, Long.MAX_VALUE, false)); assertEquals(toFilter(not(lessThanOrEqual(C_BIGINT, bigintLiteral(2L)))), BigintRange.of(3L, Long.MAX_VALUE, false)); assertEquals(toFilter(greaterThan(C_BIGINT, bigintLiteral(2L))), BigintRange.of(3L, Long.MAX_VALUE, false)); assertEquals(toFilter(greaterThanOrEqual(C_BIGINT, bigintLiteral(2L))), BigintRange.of(2L, Long.MAX_VALUE, false)); assertEquals(toFilter(not(greaterThan(C_BIGINT, bigintLiteral(2L)))), BigintRange.of(Long.MIN_VALUE, 2L, false)); assertEquals(toFilter(not(greaterThanOrEqual(C_BIGINT, bigintLiteral(2L)))), BigintRange.of(Long.MIN_VALUE, 1L, false)); assertEquals(toFilter(in(C_BIGINT, ImmutableList.of(1, 10, 100))), BigintValues.of(new long[] {1, 10, 100}, false)); assertEquals(toFilter(not(in(C_BIGINT, ImmutableList.of(1, 10, 100)))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 0L, false), BigintRange.of(2L, 9L, false), BigintRange.of(11L, 99L, false), BigintRange.of(101, Long.MAX_VALUE, false)), false)); assertEquals(toFilter(between(C_BIGINT, bigintLiteral(1L), bigintLiteral(10L))), BigintRange.of(1L, 10L, false)); assertEquals(toFilter(not(between(C_BIGINT, bigintLiteral(1L), bigintLiteral(10L)))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 0L, false), BigintRange.of(11L, Long.MAX_VALUE, false)), false)); assertEquals(toFilter(isDistinctFrom(C_BIGINT, bigintLiteral(1L))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 0L, false), BigintRange.of(2L, Long.MAX_VALUE, false)), true)); assertEquals(toFilter(not(isDistinctFrom(C_BIGINT, bigintLiteral(1L)))), BigintRange.of(1, 1, false)); assertEquals(toFilter(isNull(C_BIGINT)), IS_NULL); assertEquals(toFilter(not(isNull(C_BIGINT))), IS_NOT_NULL); assertEquals(toFilter(isNotNull(C_BIGINT)), IS_NOT_NULL); assertEquals(toFilter(not(isNotNull(C_BIGINT))), IS_NULL); assertEquals(toFilter(or(equal(C_BIGINT, bigintLiteral(2L)), isNull(C_BIGINT))), BigintRange.of(2, 2, true)); assertEquals(toFilter(or(not(equal(C_BIGINT, bigintLiteral(2L))), isNull(C_BIGINT))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 1L, false), BigintRange.of(3L, Long.MAX_VALUE, false)), true)); assertEquals(toFilter(or(in(C_BIGINT, ImmutableList.of(1, 10, 100)), isNull(C_BIGINT))), BigintValues.of(new long[] {1, 10, 100}, true)); assertEquals(toFilter(or(not(in(C_BIGINT, ImmutableList.of(1, 10, 100))), isNull(C_BIGINT))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, 0L, false), BigintRange.of(2L, 9L, false), BigintRange.of(11L, 99L, false), BigintRange.of(101, Long.MAX_VALUE, false)), true)); } @Test public void testDouble() { assertEquals(toFilter(equal(C_DOUBLE, doubleLiteral(1.2))), DoubleRange.of(1.2, false, false, 1.2, false, false, false)); assertEquals(toFilter(notEqual(C_DOUBLE, doubleLiteral(1.2))), MultiRange.of(ImmutableList.of( DoubleRange.of(Double.MIN_VALUE, true, true, 1.2, false, true, false), DoubleRange.of(1.2, false, true, Double.MAX_VALUE, true, true, false)), false)); assertEquals(toFilter(in(C_DOUBLE, ImmutableList.of(1.2, 3.4, 5.6))), MultiRange.of(ImmutableList.of( DoubleRange.of(1.2, false, false, 1.2, false, false, false), DoubleRange.of(3.4, false, false, 3.4, false, false, false), DoubleRange.of(5.6, false, false, 5.6, false, false, false)), false)); assertEquals(toFilter(isDistinctFrom(C_DOUBLE, doubleLiteral(1.2))), MultiRange.of(ImmutableList.of( DoubleRange.of(Double.MIN_VALUE, true, true, 1.2, false, true, false), DoubleRange.of(1.2, false, true, Double.MAX_VALUE, true, true, false)), true)); assertEquals(toFilter(between(C_DOUBLE, doubleLiteral(1.2), doubleLiteral(3.4))), DoubleRange.of(1.2, false, false, 3.4, false, false, false)); } @Test public void testFloat() { Expression realLiteral = toExpression(realValue(1.2f), TYPES.get(C_REAL)); assertEquals(toFilter(equal(C_REAL, realLiteral)), FloatRange.of(1.2f, false, false, 1.2f, false, false, false)); assertEquals(toFilter(not(equal(C_REAL, realLiteral))), MultiRange.of(ImmutableList.of( FloatRange.of(Float.MIN_VALUE, true, true, 1.2f, false, true, false), FloatRange.of(1.2f, false, true, Float.MAX_VALUE, true, true, false)), false)); assertEquals(toFilter(or(isNull(C_REAL), equal(C_REAL, realLiteral))), FloatRange.of(1.2f, false, false, 1.2f, false, false, true)); assertEquals(toFilter(or(isNull(C_REAL), notEqual(C_REAL, realLiteral))), MultiRange.of(ImmutableList.of( FloatRange.of(Float.MIN_VALUE, true, true, 1.2f, false, true, false), FloatRange.of(1.2f, false, true, Float.MAX_VALUE, true, true, false)), true)); } @Test public void testDecimal() { Slice decimal = longDecimal("-999999999999999999.999"); Expression decimalLiteral = toExpression(decimal, TYPES.get(C_DECIMAL_21_3)); assertEquals(toFilter(equal(C_DECIMAL_21_3, decimalLiteral)), LongDecimalRange.of(decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, false, decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, false, false)); assertEquals(toFilter(not(equal(C_DECIMAL_21_3, decimalLiteral))), MultiRange.of(ImmutableList.of( LongDecimalRange.of(Long.MIN_VALUE, Long.MIN_VALUE, true, true, decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, true, false), LongDecimalRange.of(decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, true, Long.MAX_VALUE, Long.MAX_VALUE, true, true, false)), false)); assertEquals(toFilter(or(isNull(C_DECIMAL_21_3), equal(C_DECIMAL_21_3, decimalLiteral))), LongDecimalRange.of(decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, false, decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, false, true)); assertEquals(toFilter(or(isNull(C_DECIMAL_21_3), not(equal(C_DECIMAL_21_3, decimalLiteral)))), MultiRange.of(ImmutableList.of( LongDecimalRange.of(Long.MIN_VALUE, Long.MIN_VALUE, true, true, decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, true, false), LongDecimalRange.of(decimal.getLong(0), decimal.getLong(SIZE_OF_LONG), false, true, Long.MAX_VALUE, Long.MAX_VALUE, true, true, false)), true)); } @Test public void testVarchar() { assertEquals(toFilter(equal(C_VARCHAR, stringLiteral("abc", VARCHAR))), BytesRange.of(toBytes("abc"), false, toBytes("abc"), false, false)); assertEquals(toFilter(not(equal(C_VARCHAR, stringLiteral("abc", VARCHAR)))), MultiRange.of(ImmutableList.of( BytesRange.of(null, true, toBytes("abc"), true, false), BytesRange.of(toBytes("abc"), true, null, true, false)), false)); assertEquals(toFilter(lessThan(C_VARCHAR, stringLiteral("abc", VARCHAR))), BytesRange.of(null, true, toBytes("abc"), true, false)); assertEquals(toFilter(lessThanOrEqual(C_VARCHAR, stringLiteral("abc", VARCHAR))), BytesRange.of(null, true, toBytes("abc"), false, false)); assertEquals(toFilter(between(C_VARCHAR, stringLiteral("apple", VARCHAR), stringLiteral("banana", VARCHAR))), BytesRange.of(toBytes("apple"), false, toBytes("banana"), false, false)); assertEquals(toFilter(or(isNull(C_VARCHAR), equal(C_VARCHAR, stringLiteral("abc", VARCHAR)))), BytesRange.of(toBytes("abc"), false, toBytes("abc"), false, true)); assertEquals(toFilter(in(C_VARCHAR, ImmutableList.of(stringLiteral("Ex", createVarcharType(7)), stringLiteral("oriente")))), BytesValues.of(new byte[][] {toBytes("Ex"), toBytes("oriente")}, false)); } @Test public void testDate() { long days = TimeUnit.MILLISECONDS.toDays(DateTime.parse("2019-06-01").getMillis()); assertEquals(toFilter(equal(C_DATE, dateLiteral("2019-06-01"))), BigintRange.of(days, days, false)); assertEquals(toFilter(not(equal(C_DATE, dateLiteral("2019-06-01")))), BigintMultiRange.of(ImmutableList.of( BigintRange.of(Long.MIN_VALUE, days - 1, false), BigintRange.of(days + 1, Long.MAX_VALUE, false)), false)); assertEquals(toFilter(lessThan(C_DATE, dateLiteral("2019-06-01"))), BigintRange.of(Long.MIN_VALUE, days - 1, false)); assertEquals(toFilter(lessThanOrEqual(C_DATE, dateLiteral("2019-06-01"))), BigintRange.of(Long.MIN_VALUE, days, false)); assertEquals(toFilter(not(lessThan(C_DATE, dateLiteral("2019-06-01")))), BigintRange.of(days, Long.MAX_VALUE, false)); assertEquals(toFilter(not(lessThanOrEqual(C_DATE, dateLiteral("2019-06-01")))), BigintRange.of(days + 1, Long.MAX_VALUE, false)); } private static byte[] toBytes(String value) { return Slices.utf8Slice(value).getBytes(); } private TupleDomainFilter toFilter(Expression expression) { Optional<Map<Symbol, Domain>> domains = fromPredicate(expression).getTupleDomain().getDomains(); assertTrue(domains.isPresent()); Domain domain = Iterables.getOnlyElement(domains.get().values()); return TupleDomainFilterUtils.toFilter(domain); } private TupleDomainOrcPredicate.ColumnReference columnReference(ColumnHandle column, Type type) { return new TupleDomainOrcPredicate.ColumnReference<>(column, 0, type); } private ExpressionDomainTranslator.ExtractionResult fromPredicate(Expression originalPredicate) { return ExpressionDomainTranslator.fromPredicate(metadata, TEST_SESSION, originalPredicate, TYPES); } private static ComparisonExpression equal(Symbol symbol, Expression expression) { return equal(symbol.toSymbolReference(), expression); } private static ComparisonExpression notEqual(Symbol symbol, Expression expression) { return notEqual(symbol.toSymbolReference(), expression); } private static ComparisonExpression greaterThan(Symbol symbol, Expression expression) { return greaterThan(symbol.toSymbolReference(), expression); } private static ComparisonExpression greaterThanOrEqual(Symbol symbol, Expression expression) { return greaterThanOrEqual(symbol.toSymbolReference(), expression); } private static ComparisonExpression lessThan(Symbol symbol, Expression expression) { return lessThan(symbol.toSymbolReference(), expression); } private static ComparisonExpression lessThanOrEqual(Symbol symbol, Expression expression) { return lessThanOrEqual(symbol.toSymbolReference(), expression); } private static ComparisonExpression isDistinctFrom(Symbol symbol, Expression expression) { return isDistinctFrom(symbol.toSymbolReference(), expression); } private static Expression isNotNull(Symbol symbol) { return isNotNull(symbol.toSymbolReference()); } private static IsNullPredicate isNull(Symbol symbol) { return new IsNullPredicate(symbol.toSymbolReference()); } private InPredicate in(Symbol symbol, List<?> values) { return in(symbol.toSymbolReference(), TYPES.get(symbol), values); } private static BetweenPredicate between(Symbol symbol, Expression min, Expression max) { return new BetweenPredicate(symbol.toSymbolReference(), min, max); } private static Expression isNotNull(Expression expression) { return new NotExpression(new IsNullPredicate(expression)); } private static IsNullPredicate isNull(Expression expression) { return new IsNullPredicate(expression); } private InPredicate in(Expression expression, Type expressisonType, List<?> values) { List<Type> types = nCopies(values.size(), expressisonType); List<Expression> expressions = literalEncoder.toExpressions(values, types); return new InPredicate(expression, new InListExpression(expressions)); } private static BetweenPredicate between(Expression expression, Expression min, Expression max) { return new BetweenPredicate(expression, min, max); } private static ComparisonExpression equal(Expression left, Expression right) { return comparison(EQUAL, left, right); } private static ComparisonExpression notEqual(Expression left, Expression right) { return comparison(NOT_EQUAL, left, right); } private static ComparisonExpression greaterThan(Expression left, Expression right) { return comparison(GREATER_THAN, left, right); } private static ComparisonExpression greaterThanOrEqual(Expression left, Expression right) { return comparison(GREATER_THAN_OR_EQUAL, left, right); } private static ComparisonExpression lessThan(Expression left, Expression expression) { return comparison(LESS_THAN, left, expression); } private static ComparisonExpression lessThanOrEqual(Expression left, Expression right) { return comparison(LESS_THAN_OR_EQUAL, left, right); } private static ComparisonExpression isDistinctFrom(Expression left, Expression right) { return comparison(IS_DISTINCT_FROM, left, right); } private static NotExpression not(Expression expression) { return new NotExpression(expression); } private static ComparisonExpression comparison(ComparisonExpression.Operator operator, Expression expression1, Expression expression2) { return new ComparisonExpression(operator, expression1, expression2); } private static Literal bigintLiteral(long value) { if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) { return new GenericLiteral("BIGINT", Long.toString(value)); } return new LongLiteral(Long.toString(value)); } private static DoubleLiteral doubleLiteral(double value) { return new DoubleLiteral(Double.toString(value)); } private static StringLiteral stringLiteral(String value) { return new StringLiteral(value); } private static Expression stringLiteral(String value, Type type) { return cast(stringLiteral(value), type); } private static Literal dateLiteral(String value) { return new GenericLiteral("DATE", value); } private static NullLiteral nullLiteral() { return new NullLiteral(); } private static Expression nullLiteral(Type type) { return cast(new NullLiteral(), type); } private static Expression cast(Symbol symbol, Type type) { return cast(symbol.toSymbolReference(), type); } private static Expression cast(Expression expression, Type type) { return new Cast(expression, type.getTypeSignature().toString()); } private static FunctionCall colorLiteral(long value) { return new FunctionCall(QualifiedName.of(getMagicLiteralFunctionSignature(COLOR).getName()), ImmutableList.of(bigintLiteral(value))); } private Expression varbinaryLiteral(Slice value) { return toExpression(value, VARBINARY); } private static FunctionCall function(String functionName, Expression... args) { return new FunctionCall(QualifiedName.of(functionName), ImmutableList.copyOf(args)); } private static Long shortDecimal(String value) { return new BigDecimal(value).unscaledValue().longValueExact(); } private static Slice longDecimal(String value) { return encodeScaledValue(new BigDecimal(value)); } private static Long realValue(float value) { return (long) Float.floatToIntBits(value); } private Expression toExpression(Object object, Type type) { return literalEncoder.toExpression(object, type); } }
eveardown/aws-sdk-java
aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/PutSigningProfileRequest.java
<reponame>eveardown/aws-sdk-java /* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.signer.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/signer-2017-08-25/PutSigningProfile" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PutSigningProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the signing profile to be created. * </p> */ private String profileName; /** * <p> * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. * </p> */ private SigningMaterial signingMaterial; /** * <p> * The ID of the signing profile to be created. * </p> */ private String platformId; /** * <p> * A subfield of <code>platform</code>. This specifies any different configuration options that you want to apply to * the chosen platform (such as a different <code>hash-algorithm</code> or <code>signing-algorithm</code>). * </p> */ private SigningPlatformOverrides overrides; /** * <p> * Map of key-value pairs for signing. These can include any information that you want to use during signing. * </p> */ private java.util.Map<String, String> signingParameters; /** * <p> * Tags to be associated with the signing profile being created. * </p> */ private java.util.Map<String, String> tags; /** * <p> * The name of the signing profile to be created. * </p> * * @param profileName * The name of the signing profile to be created. */ public void setProfileName(String profileName) { this.profileName = profileName; } /** * <p> * The name of the signing profile to be created. * </p> * * @return The name of the signing profile to be created. */ public String getProfileName() { return this.profileName; } /** * <p> * The name of the signing profile to be created. * </p> * * @param profileName * The name of the signing profile to be created. * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withProfileName(String profileName) { setProfileName(profileName); return this; } /** * <p> * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. * </p> * * @param signingMaterial * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. */ public void setSigningMaterial(SigningMaterial signingMaterial) { this.signingMaterial = signingMaterial; } /** * <p> * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. * </p> * * @return The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. */ public SigningMaterial getSigningMaterial() { return this.signingMaterial; } /** * <p> * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. * </p> * * @param signingMaterial * The AWS Certificate Manager certificate that will be used to sign code with the new signing profile. * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withSigningMaterial(SigningMaterial signingMaterial) { setSigningMaterial(signingMaterial); return this; } /** * <p> * The ID of the signing profile to be created. * </p> * * @param platformId * The ID of the signing profile to be created. */ public void setPlatformId(String platformId) { this.platformId = platformId; } /** * <p> * The ID of the signing profile to be created. * </p> * * @return The ID of the signing profile to be created. */ public String getPlatformId() { return this.platformId; } /** * <p> * The ID of the signing profile to be created. * </p> * * @param platformId * The ID of the signing profile to be created. * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withPlatformId(String platformId) { setPlatformId(platformId); return this; } /** * <p> * A subfield of <code>platform</code>. This specifies any different configuration options that you want to apply to * the chosen platform (such as a different <code>hash-algorithm</code> or <code>signing-algorithm</code>). * </p> * * @param overrides * A subfield of <code>platform</code>. This specifies any different configuration options that you want to * apply to the chosen platform (such as a different <code>hash-algorithm</code> or * <code>signing-algorithm</code>). */ public void setOverrides(SigningPlatformOverrides overrides) { this.overrides = overrides; } /** * <p> * A subfield of <code>platform</code>. This specifies any different configuration options that you want to apply to * the chosen platform (such as a different <code>hash-algorithm</code> or <code>signing-algorithm</code>). * </p> * * @return A subfield of <code>platform</code>. This specifies any different configuration options that you want to * apply to the chosen platform (such as a different <code>hash-algorithm</code> or * <code>signing-algorithm</code>). */ public SigningPlatformOverrides getOverrides() { return this.overrides; } /** * <p> * A subfield of <code>platform</code>. This specifies any different configuration options that you want to apply to * the chosen platform (such as a different <code>hash-algorithm</code> or <code>signing-algorithm</code>). * </p> * * @param overrides * A subfield of <code>platform</code>. This specifies any different configuration options that you want to * apply to the chosen platform (such as a different <code>hash-algorithm</code> or * <code>signing-algorithm</code>). * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withOverrides(SigningPlatformOverrides overrides) { setOverrides(overrides); return this; } /** * <p> * Map of key-value pairs for signing. These can include any information that you want to use during signing. * </p> * * @return Map of key-value pairs for signing. These can include any information that you want to use during * signing. */ public java.util.Map<String, String> getSigningParameters() { return signingParameters; } /** * <p> * Map of key-value pairs for signing. These can include any information that you want to use during signing. * </p> * * @param signingParameters * Map of key-value pairs for signing. These can include any information that you want to use during signing. */ public void setSigningParameters(java.util.Map<String, String> signingParameters) { this.signingParameters = signingParameters; } /** * <p> * Map of key-value pairs for signing. These can include any information that you want to use during signing. * </p> * * @param signingParameters * Map of key-value pairs for signing. These can include any information that you want to use during signing. * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withSigningParameters(java.util.Map<String, String> signingParameters) { setSigningParameters(signingParameters); return this; } public PutSigningProfileRequest addSigningParametersEntry(String key, String value) { if (null == this.signingParameters) { this.signingParameters = new java.util.HashMap<String, String>(); } if (this.signingParameters.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.signingParameters.put(key, value); return this; } /** * Removes all the entries added into SigningParameters. * * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest clearSigningParametersEntries() { this.signingParameters = null; return this; } /** * <p> * Tags to be associated with the signing profile being created. * </p> * * @return Tags to be associated with the signing profile being created. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * Tags to be associated with the signing profile being created. * </p> * * @param tags * Tags to be associated with the signing profile being created. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * Tags to be associated with the signing profile being created. * </p> * * @param tags * Tags to be associated with the signing profile being created. * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } public PutSigningProfileRequest addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public PutSigningProfileRequest clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getProfileName() != null) sb.append("ProfileName: ").append(getProfileName()).append(","); if (getSigningMaterial() != null) sb.append("SigningMaterial: ").append(getSigningMaterial()).append(","); if (getPlatformId() != null) sb.append("PlatformId: ").append(getPlatformId()).append(","); if (getOverrides() != null) sb.append("Overrides: ").append(getOverrides()).append(","); if (getSigningParameters() != null) sb.append("SigningParameters: ").append(getSigningParameters()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PutSigningProfileRequest == false) return false; PutSigningProfileRequest other = (PutSigningProfileRequest) obj; if (other.getProfileName() == null ^ this.getProfileName() == null) return false; if (other.getProfileName() != null && other.getProfileName().equals(this.getProfileName()) == false) return false; if (other.getSigningMaterial() == null ^ this.getSigningMaterial() == null) return false; if (other.getSigningMaterial() != null && other.getSigningMaterial().equals(this.getSigningMaterial()) == false) return false; if (other.getPlatformId() == null ^ this.getPlatformId() == null) return false; if (other.getPlatformId() != null && other.getPlatformId().equals(this.getPlatformId()) == false) return false; if (other.getOverrides() == null ^ this.getOverrides() == null) return false; if (other.getOverrides() != null && other.getOverrides().equals(this.getOverrides()) == false) return false; if (other.getSigningParameters() == null ^ this.getSigningParameters() == null) return false; if (other.getSigningParameters() != null && other.getSigningParameters().equals(this.getSigningParameters()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getProfileName() == null) ? 0 : getProfileName().hashCode()); hashCode = prime * hashCode + ((getSigningMaterial() == null) ? 0 : getSigningMaterial().hashCode()); hashCode = prime * hashCode + ((getPlatformId() == null) ? 0 : getPlatformId().hashCode()); hashCode = prime * hashCode + ((getOverrides() == null) ? 0 : getOverrides().hashCode()); hashCode = prime * hashCode + ((getSigningParameters() == null) ? 0 : getSigningParameters().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public PutSigningProfileRequest clone() { return (PutSigningProfileRequest) super.clone(); } }
cosailer/mass_storage_device
LUFA/Documentation/html/struct_u_s_b___mouse_report___data__t.js
var struct_u_s_b___mouse_report___data__t = [ [ "Button", "struct_u_s_b___mouse_report___data__t.html#a5decb2fc16d8eb2328087d2118928009", null ], [ "X", "struct_u_s_b___mouse_report___data__t.html#a0f5f23c127f4335288a9f4d897e64a67", null ], [ "Y", "struct_u_s_b___mouse_report___data__t.html#a72378a099407d1f26ec6906e26bc667b", null ] ];
dcais/aggra
src/main/java/com/github/dcais/aggra/cons/HttpConstants.java
<reponame>dcais/aggra<gh_stars>0 package com.github.dcais.aggra.cons; public interface HttpConstants { //LOG_MAX_CHAR_COUNT int LMCC_UNKNOW = -99; int LMCC_ALL = -1; int LMCC_DEFAULT = 512; String HEAD_KEY_CONTENT_TYPE = "Content-Type"; String CONTENT_TYPE_TXT_PLAIN = "text/plain"; int DEFAULT_TIMEOUT = -1; int DEFAULT_CONNECT_TIMEOUT = -1; int DEFAULT_RETRY_COUNT = -1; }
fuchstraumer/Caelestis
old/src/scene/BaseScene.cpp
#include "scene/BaseScene.hpp" #include "scene/Window.hpp" #include "scene/InputHandler.hpp" #include "core/Instance.hpp" #include "core/LogicalDevice.hpp" #include "core/PhysicalDevice.hpp" #include "command/CommandPool.hpp" #include "command/TransferPool.hpp" #include "render/Framebuffer.hpp" #include "render/Renderpass.hpp" #include "render/Swapchain.hpp" #include "render/DepthStencil.hpp" #include "resources/Multisampling.hpp" #include "render/GraphicsPipeline.hpp" #include "resource/Buffer.hpp" #include "resource/DescriptorPool.hpp" #include "resource/DescriptorSet.hpp" #include "resource/DescriptorSetLayout.hpp" #include "resource/PipelineLayout.hpp" #include "resource/ShaderModule.hpp" #include "alloc/Allocator.hpp" #include "util/easylogging++.h" #ifdef USE_EXPERIMENTAL_FILESYSTEM #include <experimental/filesystem> #endif #include <thread> using namespace vpr; namespace vpsk { vulpesSceneConfig BaseScene::SceneConfiguration = vulpesSceneConfig(); bool BaseScene::CameraLock = false; fpsCamera BaseScene::camera = fpsCamera(); vpsk_state_t BaseScene::VPSKState = vpsk_state_t(); std::atomic<bool> BaseScene::ShouldResize(false); std::vector<uint16_t> BaseScene::pipelineCacheHandles = std::vector<uint16_t>(); BaseScene::BaseScene(const uint32_t& _width, const uint32_t& _height) : width(_width), height(_height) { const bool verbose_logging = BaseScene::SceneConfiguration.VerboseLogging; ImGui::CreateContext(); window = std::make_unique<Window>(_width, _height, BaseScene::SceneConfiguration.ApplicationName); const VkApplicationInfo app_info{ VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, BaseScene::SceneConfiguration.ApplicationName.c_str(), VK_MAKE_VERSION(0,1,0), BaseScene::SceneConfiguration.EngineName.c_str(), VK_MAKE_VERSION(0,1,0), VK_API_VERSION_1_0 }; instance = std::make_unique<Instance>(false, &app_info, window->glfwWindow()); window->SetWindowUserPointer(this); LOG_IF(verbose_logging, INFO) << "VkInstance created."; device = std::make_unique<Device>(instance.get(), instance->GetPhysicalDevice(), true); swapchain = std::make_unique<Swapchain>(instance.get(), device.get()); LOG_IF(verbose_logging, INFO) << "Swapchain created."; VkSemaphoreCreateInfo semaphore_info{ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, nullptr, 0 }; VkResult result = vkCreateSemaphore(device->vkHandle(), &semaphore_info, nullptr, &semaphores[0]); VkAssert(result); result = vkCreateSemaphore(device->vkHandle(), &semaphore_info, nullptr, &semaphores[1]); VkAssert(result); renderCompleteSemaphores.resize(1); result = vkCreateSemaphore(device->vkHandle(), &semaphore_info, nullptr, &renderCompleteSemaphores[0]); VkAssert(result); presentFences.resize(swapchain->ImageCount()); VkFenceCreateInfo fence_info = vk_fence_create_info_base; for (auto& fence : presentFences) { result = vkCreateFence(device->vkHandle(), &fence_info, nullptr, &fence); VkAssert(result); } result = vkCreateFence(device->vkHandle(), &fence_info, nullptr, &acquireFence); VkAssert(result); // init frame limiters. limiter_a = std::chrono::system_clock::now(); limiter_b = std::chrono::system_clock::now(); input_handler::LastX = swapchain->Extent().width / 2.0f; input_handler::LastY = swapchain->Extent().height / 2.0f; LOG_IF(verbose_logging, INFO) << "BaseScene setup complete."; transferPool = std::make_unique<TransferPool>(device.get()); } BaseScene::~BaseScene() { gui.reset(); transferPool.reset(); swapchain.reset(); for (const auto& fence : presentFences) { vkDestroyFence(device->vkHandle(), fence, nullptr); } vkDestroyFence(device->vkHandle(), acquireFence, nullptr); vkDestroySemaphore(device->vkHandle(), semaphores[1], nullptr); vkDestroySemaphore(device->vkHandle(), semaphores[0], nullptr); #ifdef USE_EXPERIMENTAL_FILESYSTEM cleanupShaderCacheFiles(); #endif window.reset(); } void BaseScene::UpdateMouseActions() { ImGuiIO& io = ImGui::GetIO(); if (!io.WantCaptureMouse) { if (ImGui::IsMouseDragging(0)) { mouseDrag(0, io.MousePos.x, io.MousePos.y); } else if (ImGui::IsMouseDragging(1)) { mouseDrag(1, io.MousePos.x, io.MousePos.y); } if (ImGui::IsMouseDown(0) && !ImGui::IsMouseDragging(0)) { mouseDown(0, io.MouseClickedPos[0].x, io.MouseClickedPos[0].y); } if (ImGui::IsMouseDown(1) && !ImGui::IsMouseDragging(1)) { mouseDown(1, io.MouseClickedPos[1].x, io.MouseClickedPos[1].y); } if (ImGui::IsMouseReleased(0)) { mouseUp(0, io.MousePos.x, io.MousePos.y); } mouseScroll(0, io.MouseWheel); } input_handler::MouseDx = 0.0f; input_handler::MouseDy = 0.0f; } void BaseScene::mouseDrag(const int& button, const float & rot_x, const float & rot_y) { } void BaseScene::mouseScroll(const int& button, const float & zoom_delta) { } void BaseScene::mouseDown(const int& button, const float& x, const float& y) { } void BaseScene::mouseUp(const int& button, const float & x, const float & y) { } void BaseScene::PipelineCacheCreated(const uint16_t & cache_id) { pipelineCacheHandles.push_back(cache_id); } void BaseScene::createTransferCmdPool() { VkCommandPoolCreateInfo pool_info = vk_command_pool_info_base; pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; pool_info.flags = device->QueueFamilyIndices.Transfer; transferPool = std::make_unique<TransferPool>(device.get()); } void BaseScene::CreateTransferPool() { LOG(INFO) << "Creating primary graphics and transfer command pools..."; createTransferCmdPool(); } void BaseScene::RecreateSwapchain() { LOG_IF(BaseScene::SceneConfiguration.VerboseLogging, INFO) << "Began to recreate swapchain..."; // First wait to make sure nothing is in use. vkDeviceWaitIdle(device->vkHandle()); transferPool.reset(); WindowResized(); device->vkAllocator->Recreate(); vpr::RecreateSwapchainAndSurface(instance.get(), swapchain.get()); device->VerifyPresentationSupport(); /* Done destroying resources, recreate resources and objects now */ ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = static_cast<float>(swapchain->Extent().width); io.DisplaySize.y = static_cast<float>(swapchain->Extent().height); input_handler::LastX = swapchain->Extent().width / 2.0f; input_handler::LastY = swapchain->Extent().height / 2.0f; RecreateObjects(); vkDeviceWaitIdle(device->vkHandle()); LOG_IF(BaseScene::SceneConfiguration.VerboseLogging, INFO) << "Swapchain recreation successful."; } void BaseScene::RenderLoop() { frameTime = static_cast<float>(BaseScene::SceneConfiguration.FrameTimeMs / 1000.0); LOG(INFO) << "Entering rendering loop."; while(!glfwWindowShouldClose(window->glfwWindow())) { glfwPollEvents(); if (ShouldResize.exchange(false)) { RecreateSwapchain(); } limitFrame(); UpdateMouseActions(); if(SceneConfiguration.EnableGUI) { gui->NewFrame(window->glfwWindow()); } UpdateMovement(static_cast<float>(BaseScene::SceneConfiguration.FrameTimeMs)); // Acquire image, which will run async while we record commands uint32_t idx = 0; acquireNextImage(&idx); if (idx == std::numeric_limits<uint32_t>::max()) { continue; } RecordCommands(); // Submit recorded commands. Waits for semaphores specified when acquiring images. submitFrame(&idx); submitExtra(idx); waitForFrameComplete(idx); endFrame(idx); Buffer::DestroyStagingResources(device.get()); } } void BaseScene::UpdateMovement(const float& delta_time) { frameTime = delta_time; ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = delta_time; if (io.WantCaptureKeyboard) { return; } if (input_handler::Keys[GLFW_KEY_W]) { if (SceneConfiguration.CameraType == cameraType::FPS) { camera.SetPosition(camera.GetPosition() + SceneConfiguration.MovementSpeed * camera.GetFrontVector() * 0.1f); } } if (input_handler::Keys[GLFW_KEY_A]) { if (SceneConfiguration.CameraType == cameraType::FPS) { camera.SetPosition(camera.GetPosition() - SceneConfiguration.MovementSpeed * camera.GetRightVector() * 0.1f); } } if (input_handler::Keys[GLFW_KEY_D]) { if (SceneConfiguration.CameraType == cameraType::FPS) { camera.SetPosition(camera.GetPosition() + SceneConfiguration.MovementSpeed * camera.GetRightVector() * 0.1f); } } if (input_handler::Keys[GLFW_KEY_S]) { if (SceneConfiguration.CameraType == cameraType::FPS) { camera.SetPosition(camera.GetPosition() - SceneConfiguration.MovementSpeed * camera.GetFrontVector() * 0.1f); } } if (input_handler::Keys[GLFW_KEY_RIGHT_BRACKET]) { SceneConfiguration.MovementSpeed += 10.0f; } if (input_handler::Keys[GLFW_KEY_LEFT_BRACKET]) { SceneConfiguration.MovementSpeed -= 10.0f; } } void BaseScene::limitFrame() { if(!BaseScene::SceneConfiguration.LimitFramerate) { return; } limiter_a = std::chrono::system_clock::now(); std::chrono::duration<double, std::milli> work_time = limiter_a - limiter_b; if(work_time.count() < BaseScene::SceneConfiguration.FrameTimeMs) { std::chrono::duration<double, std::milli> delta_ms(BaseScene::SceneConfiguration.FrameTimeMs - work_time.count()); auto delta_ms_dur = std::chrono::duration_cast<std::chrono::milliseconds>(delta_ms); std::this_thread::sleep_for(std::chrono::milliseconds(delta_ms_dur.count())); } limiter_b = std::chrono::system_clock::now(); } void BaseScene::submitExtra(const uint32_t frame_idx) { return; } void BaseScene::acquireNextImage(uint32_t* image_idx_ptr) { VkResult result = VK_SUCCESS; result = vkAcquireNextImageKHR(device->vkHandle(), swapchain->vkHandle(), AcquireMaxTime, semaphores[0], acquireFence, image_idx_ptr); switch (result) { case VK_ERROR_OUT_OF_DATE_KHR: LOG(WARNING) << "Received VK_ERROR_OUT_OF_DATE_KHR on trying to acquire an image, recreating swapchain..."; RecreateSwapchain(); *image_idx_ptr = std::numeric_limits<uint32_t>::max(); case VK_SUBOPTIMAL_KHR: LOG(WARNING) << "Received VK_SUBOPTIMAL_KHR on trying to acquire an image, recreating swapchain..."; RecreateSwapchain(); *image_idx_ptr = std::numeric_limits<uint32_t>::max(); default: VkAssert(result); break; } if (WaitForAcquire) { result = vkWaitForFences(device->vkHandle(), 1, &acquireFence, VK_TRUE, AcquireWaitTime); VkAssert(result); } } void BaseScene::submitFrame(uint32_t* image_idx_ptr) { VkSubmitInfo submit_info = vk_submit_info_base; VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT }; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = &semaphores[0]; submit_info.pWaitDstStageMask = wait_stages; submit_info.commandBufferCount = static_cast<uint32_t>(frameCmdBuffers.size()); submit_info.pCommandBuffers = frameCmdBuffers.data(); submit_info.signalSemaphoreCount = static_cast<uint32_t>(renderCompleteSemaphores.size()); submit_info.pSignalSemaphores = renderCompleteSemaphores.data(); VkResult result = vkQueueSubmit(device->GraphicsQueue(), 1, &submit_info, presentFences[*image_idx_ptr]); switch(result) { case VK_ERROR_DEVICE_LOST: LOG(WARNING) << "vkQueueSubmit returned VK_ERROR_DEVICE_LOST"; break; default: VkAssert(result); break; } } void BaseScene::presentFrame(const uint32_t idx) { VkPresentInfoKHR present_info{ VK_STRUCTURE_TYPE_PRESENT_INFO_KHR }; present_info.waitSemaphoreCount = 1; present_info.pWaitSemaphores = &renderCompleteSemaphores[0]; present_info.swapchainCount = 1; present_info.pSwapchains = &swapchain->vkHandle(); present_info.pImageIndices = &idx; present_info.pResults = nullptr; VkResult result = vkQueuePresentKHR(device->GraphicsQueue(), &present_info); VkAssert(result); } void BaseScene::waitForFrameComplete(const uint32_t idx) { VkResult result = vkWaitForFences(device->vkHandle(), 1, &presentFences[idx], VK_TRUE, 2); VkAssert(result); result = vkResetFences(device->vkHandle(), 1, &acquireFence); VkAssert(result); result = vkResetFences(device->vkHandle(), 1, &presentFences[idx]); VkAssert(result); } void BaseScene::renderGUI(VkCommandBuffer& gui_buffer, const VkCommandBufferBeginInfo& begin_info, const size_t& frame_idx) const { if(!SceneConfiguration.EnableGUI) { LOG(ERROR) << "Tried to render the GUI, when the GUI is disabled in the SceneConfiguration!"; throw std::runtime_error("Tried to render the GUI, when the GUI is disabled in the SceneConfiguration!"); } ImGui::Render(); gui->UpdateBuffers(); vkBeginCommandBuffer(gui_buffer, &begin_info); gui->DrawFrame(gui_buffer); vkEndCommandBuffer(gui_buffer); } glm::mat4 BaseScene::GetViewMatrix() const noexcept { return camera.GetView(); } glm::mat4 BaseScene::GetProjectionMatrix() const noexcept { glm::mat4 result = camera.GetProjection(); result[1][1] *= -1.0f; result[2][2] *= 0.50f; result[3][2] *= 0.50f; return result; } const glm::vec3 & BaseScene::GetCameraPosition() const noexcept { return camera.GetPosition(); } void BaseScene::SetCameraPosition(const glm::vec3& new_camera_pos) noexcept { camera.SetPosition(new_camera_pos); } void BaseScene::SetCameraTarget(const glm::vec3& target_pos) { camera.LookAt(camera.GetPosition(), target_pos); } void BaseScene::AddFrameCmdBuffer(const VkCommandBuffer & buffer_to_submit) { frameCmdBuffers.push_back(buffer_to_submit); } }
msbtec/frontend-sigfapeap
src/pages/private/AvaliacaoSolicitacao/ResponderSolicitacao/index.js
import React, { useRef, } from 'react'; import { FiCheckCircle } from 'react-icons/fi'; import { BiArrowBack } from 'react-icons/bi'; import { store } from 'react-notifications-component'; import { useHistory } from 'react-router-dom'; import { Card } from '../../../../components/Card'; import { Form } from '../../../../components/Form'; import { Button } from '../../../../components/Button'; import { useAuth } from '../../../../hooks/auth'; import api from '../../../../services/api'; import { StyledModal } from './styles'; export default function Atividades({ setSolicitacao, item, }) { const reference = useRef(null); const history = useHistory(); const { user } = useAuth(); function handleSubmit(status) { try { const formData = new FormData(); formData.append("status", status); formData.append("user_id", item.user_id); api.put(`requests/${item.id}`, formData).then(({ data }) => { setSolicitacao(false); store.addNotification({ message: `Solicitação respondida com sucesso!`, type: 'success', insert: 'top', container: 'top-right', animationIn: ['animate__animated', 'animate__fadeIn'], animationOut: ['animate__animated', 'animate__fadeOut'], dismiss: { duration: 5000, onScreen: true, }, }); }); } catch (error) { console.log(error); } } return ( <> <div className="col-12 title" style={{ marginBottom: 10 }}> <h1>Responder Solicitação</h1> </div> <div className="col-12 px-0"> <div style={{ display: 'flex', justifyContent: "space-between", marginTop: 20, }} > <Button onClick={() => setSolicitacao(false)} className="primary" > <BiArrowBack /> Voltar </Button> </div> </div> <div className="col-12 px-0"> <Card style={{ padding: 20, display: "flex", alignItems: 'flex-start' }} className="red"> <div className="modal-body" ref={reference}> <div style={{ marginBottom: 20 }}> <label style={{ fontWeight: 'bold', marginBottom: 10 }}> Assunto: </label> <td style={{ overflowWrap: 'break-word', marginTop: 10, textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: item?.assunto }} /> </div> <div style={{ marginBottom: 20 }}> <label style={{ fontWeight: 'bold', marginBottom: 10 }}> Solicitação: </label> <td style={{ overflowWrap: 'break-word', marginTop: 10, textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: item?.solicitacao }} /> </div> {/* <div style={{ marginBottom: 20 }}> <label style={{ fontWeight: 'bold', marginBottom: 10 }}> Projeto: </label> <td style={{ overflowWrap: 'break-word', marginTop: 10, textAlign: 'center' }} dangerouslySetInnerHTML={{ __html: item?.projeto?.title }} /> </div> */} <div> <label style={{ fontWeight: 'bold', marginBottom: 10 }}> Projeto: </label> <td style={{ marginTop: 10, textAlign: 'center' }}> <a className="url" href={`/projeto/${item?.projeto?.edital_id}/${item?.projeto?.coordenador_id}`}>{item?.projeto?.title}</a> {/* <button onClick={() => history.push(`/projeto/${item?.project?.edital_id}/${item?.project?.coordenador_id}`)} className="submit"> <FiCheckCircle /> {' '} Visualizar </button> */} </td> </div> </div> {user.profile.name == 'Pesquisador' && ( <StyledModal> <div className="modal-footer"> {/* <button type="button" className="close" onClick={() => setSolicitacao(false)}> Voltar </button> */} <button onClick={() => handleSubmit("ACEITA")} className="submit"> <FiCheckCircle /> {' '} Aceitar </button> <button onClick={() => handleSubmit("RECUSADA")} className="refuse"> <FiCheckCircle /> {' '} Recusar </button> </div> </StyledModal> )} </Card> </div> </> ); }
storagezhang/Object-Oriented-Programming
derivation_3/src/factor/Cos.java
package factor; import java.math.BigInteger; public class Cos extends Factor { public Cos(BigInteger index) { super(index); } @Override public Factor clone() { return new Cos(this.getIndex()); } @Override public String toString() { return "cos("; } @Override public Factor[] diff() { Cos acos = new Cos(this.getIndex().subtract(BigInteger.ONE)); Sin asin = new Sin(BigInteger.ONE); Cons acons = new Cons(this.getIndex().negate()); return new Factor[]{acons, acos, asin}; } }