repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Team-PyRated/PyRated
Final/Dataset/B2016_Z1_Z2/student8428.cpp
<reponame>Team-PyRated/PyRated<filename>Final/Dataset/B2016_Z1_Z2/student8428.cpp #include <iostream> #include <vector> #include <stdexcept> #include <iomanip> #include <stdexcept> typedef std::vector<std::vector<double>> Matrica; Matrica StvoriMatricu(int n, int m) { Matrica mat; mat.resize(n); for(int j(0); j < n; j++) mat[j].resize(m); return mat; } void Ispisimatricu(Matrica m) { for(int i(0); i < m.size(); i++) { for(int j(0); j < m[0].size(); j++) std::cout << std::setw(4) << m[i][j] ; std::cout << "\n"; } } Matrica Horizontalna(Matrica m) { Matrica temp = StvoriMatricu(m.size(), m[0].size()); for(int i(0); i < m.size(); i++) { for(int j(0); j < m[0].size(); j++) { temp[i][j] = m[i][m[0].size() - j - 1]; } } return temp; } Matrica Vertikalna(Matrica m) { Matrica temp = StvoriMatricu(m.size(), m[0].size()); for(int i(0); i < m.size(); i++) { for(int j(0); j < m[0].size(); j++) { temp[i][j] = m[m.size() - 1 - i][j]; } } return temp; } Matrica Kombinovana(Matrica m) { Matrica temp = StvoriMatricu(m.size(), m[0].size()); for(int i(0); i < m.size(); i++) { for(int j(0); j < m[0].size(); j++) { temp[i][j] = m[m.size() - 1 - i][m[0].size() - j - 1]; } } return temp; } void ProvjeraIspravnostiMatrice(Matrica mat) { auto red = mat[0].size(); for(int i = 1; i < int(mat.size()); ++i) if(red != int(mat[i].size())) throw std::domain_error("Matrica nije korektna"); } Matrica OgledaloMatrica(Matrica mat) { if(mat.size() == 0) return mat; ProvjeraIspravnostiMatrice(mat); int m = mat.size(); int n = mat[0].size(); Matrica temp = StvoriMatricu(m * 3, n * 3); Matrica hor = Horizontalna(mat); Matrica ver = Vertikalna(mat); Matrica komb = Kombinovana(mat); for(int i(0); i < temp.size(); i++) { for(int j(0); j < temp[0].size(); j++) { if(i < m && j < n) temp[i][j] = komb[i][j]; else if(i < m && j >= n && j < n * 2) temp[i][j] = ver[i][j - n]; else if(i < m && j >= n * 2) temp[i][j] = komb[i][j - 2 * n]; else if(i >= m && i < m * 2 && j < n) temp[i][j] = hor[i - m][j]; else if(i >= m && i < m * 2 && j >= n && j < n * 2 ) temp[i][j] = mat[i - m][j - n]; else if(i >= m && i < m * 2 && j >= n * 2) temp[i][j] = hor[i - m][j - 2 * n]; else if(i >= 2 * m && j < n) temp[i][j] = komb[i - 2 * m][j]; else if(i >= 2 * m && j >= n && j < n * 2) temp[i][j] = ver[i - 2 * m][j - n]; else if(i >= 2 * m && j >= n * 2) temp[i][j] = komb[i - 2 * m][j - 2 * n]; } } return temp; } int main () { std::cout << "Unesite dimenzije matrice (m n): "; int m, n; std::cin >> m >> n; if( m < 0 ||n < 0) { std::cout << "Dimenzije matrice moraju biti nenegativne!"; return 0; } Matrica mat = StvoriMatricu(m, n); std::cout << "Unesite elemente matrice:\n"; for(int i(0); i < m; i++) { for(int j(0); j < n; j++) { std::cin >> mat[i][j]; } } std::cout << "Rezultantna matrica:\n"; Ispisimatricu(OgledaloMatrica(mat)); return 0; }
nitehawk42/jadira
usertype.core/src/main/java/org/jadira/usertype/dateandtime/joda/columnmapper/StringColumnLocalDateMapper.java
/* * Copyright 2010, 2011 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jadira.usertype.dateandtime.joda.columnmapper; import org.jadira.usertype.spi.shared.AbstractStringColumnMapper; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class StringColumnLocalDateMapper extends AbstractStringColumnMapper<LocalDate> { private static final long serialVersionUID = -6885561256539185520L; public static final DateTimeFormatter LOCAL_DATE_FORMATTER = ISODateTimeFormat.date(); @Override public LocalDate fromNonNullValue(String s) { return LOCAL_DATE_FORMATTER.parseDateTime(s).toLocalDate(); } @Override public String toNonNullValue(LocalDate value) { String formatted = LOCAL_DATE_FORMATTER.print(value); return formatted; } }
lancetipton/keg-cli
src/utils/docker/tags/tagHelpers.js
<filename>src/utils/docker/tags/tagHelpers.js const path = require('path') const { Logger } = require('KegLog') const { git } = require('KegGitCli') const { get, isArr } = require('@keg-hub/jsutils') /** * Loops through the tags array, cleans them up, then returns them * @type function * @param {Array} tags - Custom tags passed from the command line * * @returns {Array} - Tags to be added to the built image */ const tagsFromParams = tags => { // Loop the tags and ensure they are not empty strings return isArr(tags) && tags.length ? tags.reduce((customTags, tag) => { const addTag = tag && tag.trim() addTag && customTags.push(addTag) return customTags }, []) : [] } /** * Gets the location on the repo having it's image built * @type function * @param {Object} containerContext - Metadata about the image to be built ( from buildContainerContext helper ) * @param {Array} loc - Custom location defined from the param object * * @returns {string} - Found local location of the repo being built */ const getLocation = (containerContext, loc) => { const contextPath = containerContext && get(containerContext, 'contextEnvs.KEG_CONTEXT_PATH') const location = contextPath || loc return location || Logger.warn(`Could not build image tag.\nRepo location could not be found!\n`) } /** * Gets a value from the args data based on the key * @type function * @param {Object} args - Data that can be used in tags through dynamic keys * @param {Array} key - Name of the key on the args object * * @returns {*} - Values found for the key on the args object */ const getPassedOptionTag = (args={}, key) => { return args.params[key] } /** * Gets the package.json version if it exists at the passed in location from containerContext or params.location * @type function * @param {Object} containerContext - Metadata about the image to be built ( from buildContainerContext helper ) * @param {Array} params - Options passed from the command line * * @returns {Promise[string]} - Current version in the package.json */ const getPackageVersionTag = async ({ containerContext, params }) => { const location = getLocation(containerContext, params.location) if(!location) return false try { const packageJson = require(path.join(location, 'package.json')) if(!packageJson) throw new Error('No package.json') return packageJson.version } catch(err){ Logger.warn(`Could not build tag from Package.json version.\nFile could not be found at ${location}!\n`) } } /** * Gets a git repos current commit hash or branch name based on the containerContext and location * @type function * @param {Object} args.containerContext - Metadata about the image to be built from buildContainerContext * @param {Array} args.params - Options passed from the command line * @param {string} method - Type string data to get from the git repo ( 'commit' === 'commit hash' ) * * @returns {Promise[string]} - Current commit hash or branch name */ const getRepoGitTag = ({ containerContext, params }, method) => { const location = getLocation(containerContext, params.location) return !location ? Logger.warn(`Could not build tag from git repo. Location argument not found!\n`) : method === 'commit' ? git.repo.commitHash({ location }) : git.branch.name({ location }) } module.exports = { getPassedOptionTag, getPackageVersionTag, getRepoGitTag, tagsFromParams, }
onmyway133/Runtime-Headers
macOS/10.13/Foundation.framework/NSCFType.h
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation */ @interface NSCFType : NSObject + (BOOL)automaticallyNotifiesObserversForKey:(id)arg1; - (BOOL)allowsWeakReference; - (unsigned long long)hash; - (BOOL)isEqual:(id)arg1; - (oneway void)release; - (id)retain; - (unsigned long long)retainCount; - (BOOL)retainWeakReference; @end
wrburgess/access-cal-server
spec/controllers/api/v1/organizations_controller_spec.rb
<reponame>wrburgess/access-cal-server require "rails_helper" describe Api::V1::OrganizationsController, type: :controller do describe "accepting requests" do context "with incorrect token" do before do request.env["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials("<PASSWORD>") end it "returns an forbidden status code" do get :show, id: 1 expect_status :forbidden end end context "with correct token" do let(:organization) { FactoryGirl.create :organization, name: Faker::Company.name } let(:user) { FactoryGirl.create :user } before do authenticate_for_specs(user) end describe "#create" do it "creates and returns a organization instance" do new_name = Faker::Company.name post :create, name: new_name expect_json("data", attributes: { name: new_name }) end it "validates json attribute types" do post :create, name: Faker::Company.name expect_json_types("data", id: :string) expect_json_types("data", attributes: { name: :string }) expect_json_types("data", attributes: { archived: :boolean }) expect_json_types("data", attributes: { test: :boolean }) expect_json_types("data", attributes: { dummy: :boolean }) end it "returns a status of 201" do post :create, name: Faker::Company.name expect_status :created end it "creates a new instance" do expect do post :create, name: Faker::Company.name end.to change(Organization, :count).by(1) end end describe "#show" do it "returns a organization instance" do get :show, id: organization.id expect_json("data", attributes: { name: organization.name }) end it "validates json attribute types" do get :show, id: organization.id expect_json_types("data", id: :string) expect_json_types("data", attributes: { name: :string }) expect_json_types("data", attributes: { archived: :boolean }) expect_json_types("data", attributes: { test: :boolean }) expect_json_types("data", attributes: { dummy: :boolean }) end it "returns a status of 200" do get :show, id: organization.id expect_status :ok end end describe "#index" do it "returns a collection of organizations" do organization.touch FactoryGirl.create :organization FactoryGirl.create :organization get :index expect_json_sizes("data", 3) end it "includes at least one of the instances" do organization_2 = FactoryGirl.create :organization get :index expect_json("data.?", attributes: { name: organization_2.name }) end it "returns a status of 200" do FactoryGirl.create :organization FactoryGirl.create :organization get :index expect_status :ok end end describe "#update" do it "updates the organization" do organization.touch new_name = Faker::Company.name put :update, id: organization.id, name: new_name expect_json("data", attributes: { name: new_name }) end it "validates the json attribute types" do put :update, id: organization.id, name: Faker::Company.name expect_json_types("data", id: :string) expect_json_types("data", attributes: { name: :string }) expect_json_types("data", attributes: { archived: :boolean }) expect_json_types("data", attributes: { test: :boolean }) expect_json_types("data", attributes: { dummy: :boolean }) end it "returns a status of accepted (202)" do put :update, id: organization.id, name: "<NAME>" expect_status :accepted end end describe "#delete" do it "returns empty json" do organization.touch delete :destroy, id: organization.id expect_json_sizes 0 end it "returns a status of accepted (202)" do organization.touch delete :destroy, id: organization.id expect_status :accepted end it "deletes the specified instance" do organization.touch expect { delete :destroy, id: organization.id }.to change(Organization, :count).by(-1) end end end end end
simokhov/schemas44
src/main/java/ru/gov/zakupki/oos/eptypes/_1/ProtocolEZP1ExtractType.java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.07.02 at 03:35:23 PM MSK // package ru.gov.zakupki.oos.eptypes._1; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; import ru.gov.zakupki.oos.base._1.AbandonedReasonRef; import ru.gov.zakupki.oos.base._1.ResponsibleRoleEPType; import ru.gov.zakupki.oos.common._1.AppRejectedReasonType; import ru.gov.zakupki.oos.common._1.AttachmentListType; import ru.gov.zakupki.oos.common._1.ExtPrintFormType; import ru.gov.zakupki.oos.common._1.ParticipantType; import ru.gov.zakupki.oos.common._1.PrintFormType; /** * Тип: Выписка из протокола проведения ЭЗП (Запрос предложений в электронной форме); внесение изменений * * <p>Java class for protocolEZP1ExtractType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="protocolEZP1ExtractType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="externalId" type="{http://zakupki.gov.ru/oos/base/1}externalIdType" minOccurs="0"/> * &lt;element name="versionNumber" type="{http://zakupki.gov.ru/oos/base/1}versionNumberType" minOccurs="0"/> * &lt;element name="foundationDocInfo" type="{http://zakupki.gov.ru/oos/EPtypes/1}foundationDocInfoType" minOccurs="0"/> * &lt;element name="commonInfo" type="{http://zakupki.gov.ru/oos/EPtypes/1}protocolCommonInfoType"/> * &lt;element name="protocolPublisherInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="publisherOrg" type="{http://zakupki.gov.ru/oos/EPtypes/1}organizationType"/> * &lt;element name="publisherRole" type="{http://zakupki.gov.ru/oos/base/1}responsibleRoleEPType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="commissionName" type="{http://zakupki.gov.ru/oos/base/1}text2000Type"/> * &lt;element name="printFormInfo" type="{http://zakupki.gov.ru/oos/common/1}printFormType" minOccurs="0"/> * &lt;element name="extPrintFormInfo" type="{http://zakupki.gov.ru/oos/common/1}extPrintFormType"/> * &lt;element name="attachmentsInfo" type="{http://zakupki.gov.ru/oos/common/1}attachmentListType" minOccurs="0"/> * &lt;element name="modificationInfo" type="{http://zakupki.gov.ru/oos/EPtypes/1}modificationType" minOccurs="0"/> * &lt;element name="protocolInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="applicationsInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="applicationInfo" maxOccurs="unbounded"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="commonInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNumber" type="{http://zakupki.gov.ru/oos/base/1}journalNumberType"/> * &lt;element name="appDT" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="appParticipant" type="{http://zakupki.gov.ru/oos/common/1}participantType"/> * &lt;element name="admittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNotAdmittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="bestPrice" type="{http://zakupki.gov.ru/oos/base/1}moneyType"/> * &lt;element name="abandonedReason" type="{http://zakupki.gov.ru/oos/base/1}abandonedReasonRef" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="schemeVersion" use="required" type="{http://zakupki.gov.ru/oos/base/1}schemeVersionType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "protocolEZP1ExtractType", propOrder = { "id", "externalId", "versionNumber", "foundationDocInfo", "commonInfo", "protocolPublisherInfo", "commissionName", "printFormInfo", "extPrintFormInfo", "attachmentsInfo", "modificationInfo", "protocolInfo" }) public class ProtocolEZP1ExtractType { protected Long id; protected String externalId; protected Integer versionNumber; protected FoundationDocInfoType foundationDocInfo; @XmlElement(required = true) protected ProtocolCommonInfoType commonInfo; @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolPublisherInfo protocolPublisherInfo; @XmlElement(required = true) protected String commissionName; protected PrintFormType printFormInfo; @XmlElement(required = true) protected ExtPrintFormType extPrintFormInfo; protected AttachmentListType attachmentsInfo; protected ModificationType modificationInfo; @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolInfo protocolInfo; @XmlAttribute(name = "schemeVersion", required = true) protected String schemeVersion; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the externalId property. * * @return * possible object is * {@link String } * */ public String getExternalId() { return externalId; } /** * Sets the value of the externalId property. * * @param value * allowed object is * {@link String } * */ public void setExternalId(String value) { this.externalId = value; } /** * Gets the value of the versionNumber property. * * @return * possible object is * {@link Integer } * */ public Integer getVersionNumber() { return versionNumber; } /** * Sets the value of the versionNumber property. * * @param value * allowed object is * {@link Integer } * */ public void setVersionNumber(Integer value) { this.versionNumber = value; } /** * Gets the value of the foundationDocInfo property. * * @return * possible object is * {@link FoundationDocInfoType } * */ public FoundationDocInfoType getFoundationDocInfo() { return foundationDocInfo; } /** * Sets the value of the foundationDocInfo property. * * @param value * allowed object is * {@link FoundationDocInfoType } * */ public void setFoundationDocInfo(FoundationDocInfoType value) { this.foundationDocInfo = value; } /** * Gets the value of the commonInfo property. * * @return * possible object is * {@link ProtocolCommonInfoType } * */ public ProtocolCommonInfoType getCommonInfo() { return commonInfo; } /** * Sets the value of the commonInfo property. * * @param value * allowed object is * {@link ProtocolCommonInfoType } * */ public void setCommonInfo(ProtocolCommonInfoType value) { this.commonInfo = value; } /** * Gets the value of the protocolPublisherInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolPublisherInfo } * */ public ProtocolEZP1ExtractType.ProtocolPublisherInfo getProtocolPublisherInfo() { return protocolPublisherInfo; } /** * Sets the value of the protocolPublisherInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolPublisherInfo } * */ public void setProtocolPublisherInfo(ProtocolEZP1ExtractType.ProtocolPublisherInfo value) { this.protocolPublisherInfo = value; } /** * Gets the value of the commissionName property. * * @return * possible object is * {@link String } * */ public String getCommissionName() { return commissionName; } /** * Sets the value of the commissionName property. * * @param value * allowed object is * {@link String } * */ public void setCommissionName(String value) { this.commissionName = value; } /** * Gets the value of the printFormInfo property. * * @return * possible object is * {@link PrintFormType } * */ public PrintFormType getPrintFormInfo() { return printFormInfo; } /** * Sets the value of the printFormInfo property. * * @param value * allowed object is * {@link PrintFormType } * */ public void setPrintFormInfo(PrintFormType value) { this.printFormInfo = value; } /** * Gets the value of the extPrintFormInfo property. * * @return * possible object is * {@link ExtPrintFormType } * */ public ExtPrintFormType getExtPrintFormInfo() { return extPrintFormInfo; } /** * Sets the value of the extPrintFormInfo property. * * @param value * allowed object is * {@link ExtPrintFormType } * */ public void setExtPrintFormInfo(ExtPrintFormType value) { this.extPrintFormInfo = value; } /** * Gets the value of the attachmentsInfo property. * * @return * possible object is * {@link AttachmentListType } * */ public AttachmentListType getAttachmentsInfo() { return attachmentsInfo; } /** * Sets the value of the attachmentsInfo property. * * @param value * allowed object is * {@link AttachmentListType } * */ public void setAttachmentsInfo(AttachmentListType value) { this.attachmentsInfo = value; } /** * Gets the value of the modificationInfo property. * * @return * possible object is * {@link ModificationType } * */ public ModificationType getModificationInfo() { return modificationInfo; } /** * Sets the value of the modificationInfo property. * * @param value * allowed object is * {@link ModificationType } * */ public void setModificationInfo(ModificationType value) { this.modificationInfo = value; } /** * Gets the value of the protocolInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo getProtocolInfo() { return protocolInfo; } /** * Sets the value of the protocolInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo } * */ public void setProtocolInfo(ProtocolEZP1ExtractType.ProtocolInfo value) { this.protocolInfo = value; } /** * Gets the value of the schemeVersion property. * * @return * possible object is * {@link String } * */ public String getSchemeVersion() { return schemeVersion; } /** * Sets the value of the schemeVersion property. * * @param value * allowed object is * {@link String } * */ public void setSchemeVersion(String value) { this.schemeVersion = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="applicationsInfo" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="applicationInfo" maxOccurs="unbounded"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="commonInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNumber" type="{http://zakupki.gov.ru/oos/base/1}journalNumberType"/> * &lt;element name="appDT" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="appParticipant" type="{http://zakupki.gov.ru/oos/common/1}participantType"/> * &lt;element name="admittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNotAdmittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="bestPrice" type="{http://zakupki.gov.ru/oos/base/1}moneyType"/> * &lt;element name="abandonedReason" type="{http://zakupki.gov.ru/oos/base/1}abandonedReasonRef" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "applicationsInfo", "bestPrice", "abandonedReason" }) public static class ProtocolInfo { protected ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo applicationsInfo; @XmlElement(required = true) protected String bestPrice; protected AbandonedReasonRef abandonedReason; /** * Gets the value of the applicationsInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo getApplicationsInfo() { return applicationsInfo; } /** * Sets the value of the applicationsInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo } * */ public void setApplicationsInfo(ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo value) { this.applicationsInfo = value; } /** * Gets the value of the bestPrice property. * * @return * possible object is * {@link String } * */ public String getBestPrice() { return bestPrice; } /** * Sets the value of the bestPrice property. * * @param value * allowed object is * {@link String } * */ public void setBestPrice(String value) { this.bestPrice = value; } /** * Gets the value of the abandonedReason property. * * @return * possible object is * {@link AbandonedReasonRef } * */ public AbandonedReasonRef getAbandonedReason() { return abandonedReason; } /** * Sets the value of the abandonedReason property. * * @param value * allowed object is * {@link AbandonedReasonRef } * */ public void setAbandonedReason(AbandonedReasonRef value) { this.abandonedReason = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="applicationInfo" maxOccurs="unbounded"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="commonInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNumber" type="{http://zakupki.gov.ru/oos/base/1}journalNumberType"/> * &lt;element name="appDT" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="appParticipant" type="{http://zakupki.gov.ru/oos/common/1}participantType"/> * &lt;element name="admittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNotAdmittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "applicationInfo" }) public static class ApplicationsInfo { @XmlElement(required = true) protected List<ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo> applicationInfo; /** * Gets the value of the applicationInfo property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the applicationInfo property. * * <p> * For example, to add a new item, do as follows: * <pre> * getApplicationInfo().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo } * * */ public List<ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo> getApplicationInfo() { if (applicationInfo == null) { applicationInfo = new ArrayList<ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo>(); } return this.applicationInfo; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="commonInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNumber" type="{http://zakupki.gov.ru/oos/base/1}journalNumberType"/> * &lt;element name="appDT" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="appParticipant" type="{http://zakupki.gov.ru/oos/common/1}participantType"/> * &lt;element name="admittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNotAdmittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "commonInfo", "appParticipant", "admittedInfo" }) public static class ApplicationInfo { @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.CommonInfo commonInfo; @XmlElement(required = true) protected ParticipantType appParticipant; @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo admittedInfo; /** * Gets the value of the commonInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.CommonInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.CommonInfo getCommonInfo() { return commonInfo; } /** * Sets the value of the commonInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.CommonInfo } * */ public void setCommonInfo(ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.CommonInfo value) { this.commonInfo = value; } /** * Gets the value of the appParticipant property. * * @return * possible object is * {@link ParticipantType } * */ public ParticipantType getAppParticipant() { return appParticipant; } /** * Sets the value of the appParticipant property. * * @param value * allowed object is * {@link ParticipantType } * */ public void setAppParticipant(ParticipantType value) { this.appParticipant = value; } /** * Gets the value of the admittedInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo getAdmittedInfo() { return admittedInfo; } /** * Sets the value of the admittedInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo } * */ public void setAdmittedInfo(ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo value) { this.admittedInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNotAdmittedInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "appNotAdmittedInfo" }) public static class AdmittedInfo { @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo appNotAdmittedInfo; /** * Gets the value of the appNotAdmittedInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo getAppNotAdmittedInfo() { return appNotAdmittedInfo; } /** * Sets the value of the appNotAdmittedInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo } * */ public void setAppNotAdmittedInfo(ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo value) { this.appNotAdmittedInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonsInfo"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "appRejectedReasonsInfo" }) public static class AppNotAdmittedInfo { @XmlElement(required = true) protected ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo.AppRejectedReasonsInfo appRejectedReasonsInfo; /** * Gets the value of the appRejectedReasonsInfo property. * * @return * possible object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo.AppRejectedReasonsInfo } * */ public ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo.AppRejectedReasonsInfo getAppRejectedReasonsInfo() { return appRejectedReasonsInfo; } /** * Sets the value of the appRejectedReasonsInfo property. * * @param value * allowed object is * {@link ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo.AppRejectedReasonsInfo } * */ public void setAppRejectedReasonsInfo(ProtocolEZP1ExtractType.ProtocolInfo.ApplicationsInfo.ApplicationInfo.AdmittedInfo.AppNotAdmittedInfo.AppRejectedReasonsInfo value) { this.appRejectedReasonsInfo = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appRejectedReasonInfo" type="{http://zakupki.gov.ru/oos/common/1}appRejectedReasonType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "appRejectedReasonInfo" }) public static class AppRejectedReasonsInfo { @XmlElement(required = true) protected List<AppRejectedReasonType> appRejectedReasonInfo; /** * Gets the value of the appRejectedReasonInfo property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the appRejectedReasonInfo property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAppRejectedReasonInfo().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AppRejectedReasonType } * * */ public List<AppRejectedReasonType> getAppRejectedReasonInfo() { if (appRejectedReasonInfo == null) { appRejectedReasonInfo = new ArrayList<AppRejectedReasonType>(); } return this.appRejectedReasonInfo; } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="appNumber" type="{http://zakupki.gov.ru/oos/base/1}journalNumberType"/> * &lt;element name="appDT" type="{http://www.w3.org/2001/XMLSchema}dateTime"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "appNumber", "appDT" }) public static class CommonInfo { @XmlElement(required = true) protected String appNumber; @XmlElement(required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar appDT; /** * Gets the value of the appNumber property. * * @return * possible object is * {@link String } * */ public String getAppNumber() { return appNumber; } /** * Sets the value of the appNumber property. * * @param value * allowed object is * {@link String } * */ public void setAppNumber(String value) { this.appNumber = value; } /** * Gets the value of the appDT property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getAppDT() { return appDT; } /** * Sets the value of the appDT property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setAppDT(XMLGregorianCalendar value) { this.appDT = value; } } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="publisherOrg" type="{http://zakupki.gov.ru/oos/EPtypes/1}organizationType"/> * &lt;element name="publisherRole" type="{http://zakupki.gov.ru/oos/base/1}responsibleRoleEPType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "publisherOrg", "publisherRole" }) public static class ProtocolPublisherInfo { @XmlElement(required = true) protected OrganizationType publisherOrg; @XmlElement(required = true) @XmlSchemaType(name = "string") protected ResponsibleRoleEPType publisherRole; /** * Gets the value of the publisherOrg property. * * @return * possible object is * {@link OrganizationType } * */ public OrganizationType getPublisherOrg() { return publisherOrg; } /** * Sets the value of the publisherOrg property. * * @param value * allowed object is * {@link OrganizationType } * */ public void setPublisherOrg(OrganizationType value) { this.publisherOrg = value; } /** * Gets the value of the publisherRole property. * * @return * possible object is * {@link ResponsibleRoleEPType } * */ public ResponsibleRoleEPType getPublisherRole() { return publisherRole; } /** * Sets the value of the publisherRole property. * * @param value * allowed object is * {@link ResponsibleRoleEPType } * */ public void setPublisherRole(ResponsibleRoleEPType value) { this.publisherRole = value; } } }
drcsturm/project-euler
p018.py
<reponame>drcsturm/project-euler<filename>p018.py # By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom of the triangle below: # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 82 47 65 # 19 01 23 75 03 34 # 88 02 77 73 07 63 67 # 99 65 04 28 06 16 70 92 # 41 41 26 56 83 40 80 70 33 # 41 48 72 33 47 32 37 16 94 29 # 53 71 44 65 25 43 91 52 97 51 14 # 70 11 33 28 77 73 17 78 39 68 17 57 # 91 71 52 38 17 14 91 43 58 50 27 29 48 # 63 66 04 68 89 53 67 30 73 16 69 87 40 31 # 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 # NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) grid = """ 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 """ import re import numpy as np np.set_printoptions(linewidth=240) rows = grid.count('\n') - 1 # 15 rows of data data = [int(i) for i in re.findall("[0-9]+", grid)] # make a list of integers # create a pyramid matrix filled with zeros z = np.zeros((rows,rows*2), dtype=np.int64) for i in range(1, rows+1): for j in range(i): z[i-1, rows - (i-1) + j*2] = data[0] data.pop(0) z_orig = np.copy(z) z = np.rot90(np.rot90(z)) for i in range(1,rows): for j in range(rows-i): # get the max of the sum of the current number with either of the previous numbers z[i, i + j*2] = z[i, i + j*2] + max(z[i-1, i-1 + j*2], z[i-1, i-1 + j*2 + 2]) # print(z_orig) print(np.rot90(np.rot90(z))) print(np.amax(z))
hulu7/deepnews
admin/src/pages/Setting/Controller.js
export default function Controller($scope,$state,SettingSer,CommonJs,FileUploader){ // 获取登录token const Token = window.localStorage.getItem('Token'); if(!Token){ $state.go('login'); return; } // 表单字段 $scope.formData = { rootDir : '', webTitle : '', webLogo : '', WordLogo : '', description : '', keywords : '', copyright : '', recordNumber : '', language:'ch' } // 表单提交 $scope.submitForm = submitForm; // 获取配置 GetConfig(); // 文件上传 uploadfile(); // 表单提交 function submitForm(){ CommonJs.getCurrentLang(Token,function(language){ // 当前选中语言 $scope.formData.language = language.lang_field; SettingSer.setInfos($scope.formData,Token).then(response=>{ var response = response.data; // 检查令牌是否失效 if(CommonJs.checkRequestCode(response.code)) return; if(!response.code){ swal("配置写入成功","","success"); // 获取最新配置 GetConfig(); }else{ swal("配置写入失败","","error"); } }); }); } // 获取配置 function GetConfig(){ CommonJs.getCurrentLang(Token,function(language){ SettingSer.getInfo(Token,language.lang_field).then(response=>{ var response = response.data; // 检查令牌是否失效 if(CommonJs.checkRequestCode(response.code)) return; if(!response.code){ $scope.formData = response.result; }else{ swal("配置获取失败","","error"); } }); }); } // 文件上传 function uploadfile(){ var uploader = $scope.uploader = new FileUploader({ url: `${CommonJs.SERVER_PATH}fileUpload` }); uploader.onSuccessItem = fileItem => { var path = JSON.parse(fileItem._xhr.responseText).file.path.split('server')[1].substr(1); $scope.formData.webLogo = path; }; uploader.onErrorItem = fileItem => { swal("文件上传失败","","error"); }; } } Controller.$inject = ['$scope','$state','SettingSer','CommonJs','FileUploader'];
maoa3/scalpel
psx/_dump_/1/_dump_c_src_/diabpsx/source/stores.cpp
// C:\diabpsx\SOURCE\STORES.CPP #include "types.h" // address: 0x8006402C // line start: 150 // line end: 151 void FreeStoreMem__Fv() { } // address: 0x80064034 // line start: 159 // line end: 162 void DrawSTextBack__Fv() { } // address: 0x800640A4 // line start: 167 // line end: 234 void PrintSString__FiiUcPcci(int x, int y, unsigned char cjustflag, char *str, int col, int val) { // register: 21 register int xx; // register: 19 register int yy; // address: 0xFFFFFFB0 // size: 0x20 auto char valstr[32]; // address: 0xFFFFFFD0 auto int SpinnerY; // register: 20 register unsigned char R; // register: 18 register unsigned char G; // register: 17 register unsigned char B; // address: 0x8011713C static unsigned char DaveFix; } // address: 0x80064434 // line start: 241 // line end: 248 void DrawSLine__Fi(int y) { // register: 16 register int yy; } // address: 0x800644C8 // line start: 255 // line end: 268 void ClearSText__Fii(int s, int e) { // register: 4 register int i; } // address: 0x80064560 // line start: 274 // line end: 278 void AddSLine__Fi(int y) { } // address: 0x800645B0 // line start: 284 // line end: 285 void AddSTextVal__Fii(int y, int val) { } // address: 0x800645D8 // line start: 294 // line end: 303 void AddSText__FiiUcPccUc(int x, int y, unsigned char j, char *str, int clr, int sel) { } // address: 0x8006468C // line start: 308 // line end: 383 void PrintStoreItem__FPC10ItemStructic(struct ItemStruct *x, int l, char iclr) { // address: 0xFFFFFF60 // size: 0x80 auto char sstr[128]; } // address: 0x80064AD0 // line start: 391 // line end: 449 void StoreAutoPlace__Fv() { // register: 16 register int i; // register: 18 register int w; // register: 19 register int h; // register: 3 register int idx; // register: 4 register unsigned char done; } // address: 0x800650EC // line start: 456 // line end: 470 void S_StartSmith__Fv() { } // address: 0x80065274 // line start: 476 // line end: 503 void S_ScrollSBuy__Fi(int idx) { // register: 17 register int l; // register: 20 register int ls; // register: 18 register char iclr; } // address: 0x80065420 // line start: 509 // line end: 527 void S_StartSBuy__Fv() { } // address: 0x80065550 // line start: 533 // line end: 592 void S_ScrollSPBuy__Fi(int idx) { // register: 19 register int l; // register: 17 register char iclr; // register: 3 register int boughtitems; } // address: 0x80065718 // line start: 598 // line end: 628 unsigned char S_StartSPBuy__Fv() { // register: 4 register int i; } // address: 0x80065868 // line start: 634 // line end: 645 unsigned char SmithSellOk__Fi(int i) { } // address: 0x80065950 // line start: 651 // line end: 687 void S_ScrollSSell__Fi(int idx) { // register: 17 register int l; // register: 21 register int ls; // register: 5 register int v; // register: 18 register char iclr; } // address: 0x80065B3C // line start: 693 // line end: 739 void S_StartSSell__Fv() { // register: 16 register int i; // register: 18 register unsigned char sellok; } // address: 0x80065F64 // line start: 747 // line end: 755 unsigned char SmithRepairOk__Fi(int i) { } // address: 0x8006600C // line start: 760 // line end: 781 void AddStoreHoldRepair__FP10ItemStructi(struct ItemStruct *itm, int i) { // register: 4 register int v; } // address: 0x800661E8 // line start: 786 // line end: 844 void S_StartSRepair__Fv() { // register: 16 register int i; // register: 18 register unsigned char repairok; } // address: 0x800666B4 // line start: 853 // line end: 865 void S_StartWitch__Fv() { } // address: 0x800667F4 // line start: 871 // line end: 900 void S_ScrollWBuy__Fi(int idx) { // register: 17 register int l; // register: 20 register int ls; // register: 18 register char iclr; } // address: 0x800669A0 // line start: 906 // line end: 926 void S_StartWBuy__Fv() { } // address: 0x80066AC8 // line start: 932 // line end: 952 unsigned char WitchSellOk__Fi(int i) { // register: 5 register unsigned char rv; // register: 3 // size: 0x94 register struct ItemStruct *pI; } // address: 0x80066BEC // line start: 958 // line end: 1018 void S_StartWSell__Fv() { // register: 16 register int i; // register: 19 register unsigned char sellok; } // address: 0x80067238 // line start: 1027 // line end: 1033 unsigned char WitchRechargeOk__Fi(int i) { // register: 5 register unsigned char rv; } // address: 0x800672C4 // line start: 1039 // line end: 1048 void AddStoreHoldRecharge__FG10ItemStructi(struct ItemStruct itm, int i) { } // address: 0x80067440 // line start: 1054 // line end: 1095 void S_StartWRecharge__Fv() { // register: 16 register int i; // register: 18 register unsigned char rechargeok; } // address: 0x80067854 // line start: 1104 // line end: 1110 void S_StartNoMoney__Fv() { } // address: 0x800678BC // line start: 1116 // line end: 1121 void S_StartNoRoom__Fv() { } // address: 0x8006791C // line start: 1127 // line end: 1184 void S_StartConfirm__Fv() { // register: 16 register char iclr; // register: 3 register unsigned char idprint; } // address: 0x80067C50 // line start: 1190 // line end: 1208 void S_StartBoy__Fv() { } // address: 0x80067DE0 // line start: 1215 // line end: 1239 void S_StartBBoy__Fv() { // register: 17 register int iclr; } // address: 0x80067F2C // line start: 1247 // line end: 1267 void S_StartHealer__Fv() { } // address: 0x80068100 // line start: 1273 // line end: 1295 void S_ScrollHBuy__Fi(int idx) { // register: 19 register int l; } // address: 0x80068260 // line start: 1301 // line end: 1318 void S_StartHBuy__Fv() { } // address: 0x80068380 // line start: 1324 // line end: 1333 void S_StartStory__Fv() { } // address: 0x80068470 // line start: 1339 // line end: 1343 unsigned char IdItemOk__FP10ItemStruct(struct ItemStruct *i) { } // address: 0x800684A4 // line start: 1351 // line end: 1356 void AddStoreHoldId__FG10ItemStructi(struct ItemStruct itm, int i) { } // address: 0x80068574 // line start: 1362 // line end: 1433 void S_StartSIdentify__Fv() { // register: 16 register int i; // register: 19 register unsigned char idok; } // address: 0x80068FB0 // line start: 1442 // line end: 1459 void S_StartIdShow__Fv() { // register: 16 register char iclr; } // address: 0x80069140 // line start: 1465 // line end: 1499 void S_StartTalk__Fv() { // register: 18 register int i; // register: 5 register int tq; // register: 17 register int sn; // register: 22 register int la; // register: 20 register int gl; } // address: 0x80069370 // line start: 1506 // line end: 1516 void S_StartTavern__Fv() { } // address: 0x80069468 // line start: 1522 // line end: 1531 void S_StartBarMaid__Fv() { } // address: 0x8006953C // line start: 1537 // line end: 1546 void S_StartDrunk__Fv() { } // address: 0x80069610 // line start: 1552 // line end: 1624 void StartStore__Fc(char s) { // register: 3 register int i; } // address: 0x800698F8 // line start: 1631 // line end: 1635 void DrawSText__Fv() { } // address: 0x80069938 // line start: 1640 // line end: 1654 void DrawSTextTSK__FP4TASK(struct TASK *T) { } // address: 0x80069A00 // line start: 1658 // line end: 1711 void DoThatDrawSText__Fv() { // register: 17 register int i; } // address: 0x80069BAC // line start: 1719 // line end: 1783 void STextESC__Fv() { } // address: 0x80069D5C // line start: 1788 // line end: 1822 void STextUp__Fv() { } // address: 0x80069EE4 // line start: 1832 // line end: 1864 void STextDown__Fv() { } // address: 0x8006A07C // line start: 1876 // line end: 1898 void S_SmithEnter__Fv() { } // address: 0x8006A150 // line start: 1905 // line end: 1916 void SetGoldCurs__Fii(int pnum, int i) { } // address: 0x8006A1D0 // line start: 1924 // line end: 1934 void SetSpdbarGoldCurs__Fii(int pnum, int i) { } // address: 0x8006A250 // line start: 1942 // line end: 2033 void TakePlrsMoney__Fl(long cost) { // register: 16 register int i; } // address: 0x8006A69C // line start: 2042 // line end: 2065 void SmithBuyItem__Fv() { // register: 10 register int idx; } // address: 0x8006A880 // line start: 2071 // line end: 2100 void S_SBuyEnter__Fv() { // register: 3 register int idx; // register: 16 register int i; // register: 3 register unsigned char done; } // address: 0x8006AA7C // line start: 2108 // line end: 2133 void SmithBuyPItem__Fv() { // register: 6 register int idx; // register: 5 register int i; // register: 3 register int xx; } // address: 0x8006ABFC // line start: 2140 // line end: 2177 void S_SPBuyEnter__Fv() { // register: 6 register int idx; // register: 16 register int i; // register: 3 register unsigned char done; { // register: 5 register int xx; } } // address: 0x8006AE40 // line start: 2184 // line end: 2213 unsigned char StoreGoldFit__Fi(int idx) { // register: 18 register int sz; // register: 16 register int numsqrs; // register: 4 register int i; // register: 17 register long cost; } // address: 0x8006B110 // line start: 2222 // line end: 2246 void PlaceStoreGold__Fl(long v) { // register: 16 register int i; // register: 18 register int ii; // register: 19 register int xx; // register: 17 register int yy; // register: 5 register unsigned char done; { { { { } } } } } // address: 0x8006B374 // line start: 2252 // line end: 2307 void StoreSellItem__Fv() { // register: 16 register int idx; // register: 16 register int i; // register: 17 register long cost; } // address: 0x8006B65C // line start: 2314 // line end: 2330 void S_SSellEnter__Fv() { // register: 7 register int idx; } // address: 0x8006B750 // line start: 2337 // line end: 2354 void SmithRepairItem__Fv() { // register: 4 register int i; // register: 3 register int idx; } // address: 0x8006B9B8 // line start: 2360 // line end: 2378 void S_SRepairEnter__Fv() { // register: 8 register int idx; } // address: 0x8006BB04 // line start: 2385 // line end: 2402 void S_WitchEnter__Fv() { } // address: 0x8006BBB4 // line start: 2409 // line end: 2441 void WitchBuyItem__Fv() { // register: 16 register int idx; } // address: 0x8006BDA8 // line start: 2446 // line end: 2475 void S_WBuyEnter__Fv() { // register: 3 register int idx; // register: 16 register int i; // register: 3 register unsigned char done; } // address: 0x8006BFA4 // line start: 2483 // line end: 2499 void S_WSellEnter__Fv() { // register: 7 register int idx; } // address: 0x8006C098 // line start: 2506 // line end: 2520 void WitchRechargeItem__Fv() { // register: 2 register int i; // register: 3 register int idx; } // address: 0x8006C208 // line start: 2526 // line end: 2544 void S_WRechargeEnter__Fv() { // register: 8 register int idx; } // address: 0x8006C354 // line start: 2551 // line end: 2579 void S_BoyEnter__Fv() { } // address: 0x8006C48C // line start: 2586 // line end: 2597 void BoyBuyItem__Fv() { } // address: 0x8006C510 // line start: 2603 // line end: 2648 void HealerBuyItem__Fv() { // register: 16 register int idx; } // address: 0x8006C79C // line start: 2653 // line end: 2687 void S_BBuyEnter__Fv() { // register: 16 register int i; // register: 3 register unsigned char done; } // address: 0x8006C998 // line start: 2693 // line end: 2715 void StoryIdItem__Fv() { // register: 4 register int i; // register: 2 register int idx; } // address: 0x8006CCE0 // line start: 2722 // line end: 2757 void S_ConfirmEnter__Fv() { } // address: 0x8006CDFC // line start: 2762 // line end: 2780 void S_HealerEnter__Fv() { } // address: 0x8006CE94 // line start: 2787 // line end: 2816 void S_HBuyEnter__Fv() { // register: 3 register int idx; // register: 16 register int i; // register: 3 register unsigned char done; } // address: 0x8006D0B0 // line start: 2824 // line end: 2837 void S_StoryEnter__Fv() { } // address: 0x8006D148 // line start: 2844 // line end: 2862 void S_SIDEnter__Fv() { // register: 8 register int idx; } // address: 0x8006D2B4 // line start: 2869 // line end: 2911 void S_TalkEnter__Fv() { // register: 16 register int i; // register: 5 register int tq; // register: 18 register int sn; // register: 21 register int la; { { { { } } } } } // address: 0x8006D4AC // line start: 2920 // line end: 2931 void S_TavernEnter__Fv() { } // address: 0x8006D51C // line start: 2938 // line end: 2950 void S_BarmaidEnter__Fv() { } // address: 0x8006D58C // line start: 2957 // line end: 2968 void S_DrunkEnter__Fv() { } // address: 0x8006D5FC // line start: 2975 // line end: 3037 void STextEnter__Fv() { } // address: 0x8006D80C // line start: 3042 // line end: 3124 void CheckStoreBtn__Fv() { // register: 16 // size: 0x6C register struct CPad *Pad; } // address: 0x8006D924 // line start: 3129 // line end: 3131 void ReleaseStoreBtn__Fv() { } // address: 0x8006D938 // line start: 3210 // line end: 3210 void _GLOBAL__D_pSTextBoxCels() { } // address: 0x8006D960 // line start: 3210 // line end: 3210 void _GLOBAL__I_pSTextBoxCels() { }
ajpmaclean/vtk-examples
src/Cxx/PolyData/ResampleAppendedPolyData.cxx
#include <vtkActor.h> #include <vtkAppendPolyData.h> #include <vtkCamera.h> #include <vtkCellArray.h> #include <vtkCellLocator.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkMinimalStandardRandomSequence.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkPlaneSource.h> #include <vtkPlatonicSolidSource.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> //#include <random> int main(int, char*[]) { // Define adjustable paramaters constexpr double xMin = -10.0; constexpr double xMax = 10.0; constexpr double yMin = -10.0; constexpr double yMax = 10.0; constexpr int xResolution = 100; constexpr int yResolution = 100; constexpr double scaleMin = 0.2; constexpr double scaleMax = 1.5; constexpr int numberOfObjects = 200; constexpr int probeResolution = 200.0; // Generate terrain vtkNew<vtkPlaneSource> terrain; terrain->SetOrigin(xMin, yMin, 0.0); terrain->SetPoint2(xMin, yMax, 0.0); terrain->SetPoint1(xMax, yMin, 0.0); terrain->SetXResolution(xResolution); terrain->SetYResolution(yResolution); terrain->Update(); // Generate objects and append them to terrain vtkNew<vtkAppendPolyData> append; append->AddInputConnection(terrain->GetOutputPort()); // Commented out since it gives different results for VS and gcc. // std::mt19937_64 mt(4355412); // Standard mersenne twister engine // std::uniform_int_distribution<> solid(0, 4); // std::uniform_real_distribution<> scale(scaleMin, scaleMax); // std::uniform_real_distribution<> position(xMin + 1.0, xMax - 1.0); vtkNew<vtkMinimalStandardRandomSequence> randomSequence; randomSequence->SetSeed(4355412); for (auto i = 0; i < numberOfObjects; ++i) { int solid = static_cast<int>(randomSequence->GetRangeValue(0, 4)); randomSequence->Next(); double s = randomSequence->GetRangeValue(scaleMin, scaleMax); randomSequence->Next(); double x, y; x = randomSequence->GetRangeValue(xMin + 1.0, xMax - 1.0); randomSequence->Next(); y = randomSequence->GetRangeValue(yMin + 1.0, yMax - 1.0); randomSequence->Next(); // Generate an object vtkNew<vtkPlatonicSolidSource> platonic; // platonic->SetSolidType(solid(mt)); platonic->SetSolidType(solid); // Translate and scale vtkNew<vtkTransform> transform; // double s = scale(mt); // transform->Translate(position(mt), position(mt), 0.0); transform->Translate(x, y, 0.0); transform->Scale(s, s, s); vtkNew<vtkTransformPolyDataFilter> transformPD; transformPD->SetTransform(transform); transformPD->SetInputConnection(platonic->GetOutputPort()); transformPD->Update(); vtkNew<vtkPolyData> pd; pd->DeepCopy(transformPD->GetOutput()); append->AddInputData(pd); } append->Update(); // Resample terrian vtkNew<vtkCellLocator> cellLocator; cellLocator->SetDataSet(append->GetOutput()); cellLocator->BuildLocator(); // Generate a probe plane vtkNew<vtkPlaneSource> probeTerrain; probeTerrain->SetOrigin(terrain->GetOrigin()); probeTerrain->SetPoint2(terrain->GetPoint2()); probeTerrain->SetPoint1(terrain->GetPoint1()); probeTerrain->SetXResolution(probeResolution); probeTerrain->SetYResolution(probeResolution); probeTerrain->Update(); vtkPoints* probePoints = probeTerrain->GetOutput()->GetPoints(); for (auto i = 0; i < probeTerrain->GetOutput()->GetNumberOfPoints(); ++i) { int subId; double t, xyz[3], pcoords[3]; double rayStart[3], rayEnd[3]; probePoints->GetPoint(i, rayStart); rayStart[2] += 100000.0; probePoints->GetPoint(i, rayEnd); rayEnd[2] -= 100000.0; if (cellLocator->IntersectWithLine(rayStart, rayEnd, 0.0001, t, xyz, pcoords, subId)) { // The new elevation is in xyz[2] double pt[3]; probePoints->GetPoint(i, pt); probePoints->SetPoint(i, pt[0], pt[1], xyz[2]); } } probeTerrain->GetOutput()->GetPointData()->SetNormals(nullptr); // Visualize vtkNew<vtkNamedColors> colors; // Two viewports, left for original and right for resampled vtkNew<vtkPolyDataMapper> originalMapper; originalMapper->SetInputConnection(append->GetOutputPort()); originalMapper->SetInputData(append->GetOutput()); originalMapper->ScalarVisibilityOff(); vtkNew<vtkActor> originalActor; originalActor->SetMapper(originalMapper); originalActor->GetProperty()->SetRepresentationToWireframe(); originalActor->GetProperty()->SetColor( colors->GetColor3d("Seashell").GetData()); vtkNew<vtkPolyDataMapper> resampledMapper; resampledMapper->SetInputConnection(append->GetOutputPort()); resampledMapper->SetInputData(probeTerrain->GetOutput()); resampledMapper->ScalarVisibilityOff(); vtkNew<vtkActor> resampledActor; resampledActor->SetMapper(resampledMapper); resampledActor->GetProperty()->SetRepresentationToWireframe(); resampledActor->GetProperty()->SetColor( colors->GetColor3d("Seashell").GetData()); double rightViewport[4] = {0.5, 0.0, 1.0, 1.0}; vtkNew<vtkRenderer> rightRenderer; rightRenderer->SetViewport(rightViewport); rightRenderer->UseHiddenLineRemovalOn(); rightRenderer->AddActor(resampledActor); rightRenderer->SetBackground(colors->GetColor3d("DarkSlateGray").GetData()); double leftViewport[4] = {0.0, 0.0, 0.5, 1.0}; vtkNew<vtkRenderer> leftRenderer; leftRenderer->SetViewport(leftViewport); leftRenderer->UseHiddenLineRemovalOn(); leftRenderer->AddActor(originalActor); leftRenderer->SetBackground(colors->GetColor3d("DarkSlateGray").GetData()); vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(rightRenderer); renderWindow->AddRenderer(leftRenderer); renderWindow->SetSize(1024, 512); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderWindow->SetWindowName("ResampleAppendedPolyData"); vtkNew<vtkInteractorStyleTrackballCamera> style; renderWindowInteractor->SetInteractorStyle(style); renderWindow->Render(); vtkCamera* camera; camera = leftRenderer->GetActiveCamera(); camera->SetFocalPoint(0.0, 0.0, 0.0); camera->SetPosition(1.0, 0.0, 0.0); camera->SetViewUp(0.0, 0.0, 1.0); camera->Azimuth(30.0); camera->Elevation(45.0); leftRenderer->ResetCamera(); rightRenderer->SetActiveCamera(camera); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
dthree/wat
src/vorpal/indexer.js
'use strict'; const chalk = require('chalk'); module.exports = function (vorpal, options) { const app = options.app; vorpal .command('index', 'Updates the index based on local docs.') .alias('update') .option('-s, --static', 'Overrides static files, for building and submitting new docs.') .action(function (args, cb) { const self = this; let isStatic = args.options.static || false; isStatic = (app.updateRemotely === false) ? true : isStatic; app.clerk.indexer.update({force: true, static: isStatic}, function (err, data) { if (!err) { self.log(chalk.cyan('\n Successfully updated index.')); const amt = app.clerk.updater.queue.length; if (amt > 1) { self.log(`\n ${amt} documents are queued for updating.`); } if (app.updateRemotely === false) { app.clerk.indexer.build(function(index){ app.clerk.indexer.write(index, undefined, {static: true}); vorpal.log(chalk.cyan('\n Sucessfully rebuilt index.\n')); cb(); }); } else { self.log(' '); cb(); } } else { self.log('Error'); self.log(err, data); cb(); } }); }); };
clairegriffin/lockss-core
src/test/java/org/lockss/config/TestTdbAu.java
<gh_stars>1-10 /* * $Id$ */ /* Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.config; import org.lockss.util.*; import org.lockss.config.Tdb.TdbException; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.test.*; import java.util.*; /** * Test class for <code>org.lockss.config.TdbAu</code> * * @author <NAME> * @version $Id$ */ public class TestTdbAu extends LockssTestCase { public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } static Logger log = Logger.getLogger(); /** * Test creating valid TdbAu. */ public void testValidAu() { TdbAu au = null; try { au = new TdbAu("Test Au", "Test Plugin"); } catch (IllegalArgumentException ex) { fail("Unexpected xception creating TdbAu", ex); } assertNotNull(au); assertEquals("Test Au", au.getName()); } /** * Test isDown() method * @throws TdbException for invalid Tdb operations */ public void testIsDown() throws TdbException{ TdbAu au1 = new TdbAu("Test AU", "pluginA"); assertFalse(au1.isDown()); // same as title1 TdbAu au2 = new TdbAu("Test AU", "pluginA"); au2.setParam("pub_down", "true"); assertTrue(au2.isDown()); } /** * Test getProprietaryId() and getProprietarySeriesId() methods. * @throws TdbException for invalid Tdb operations */ public void testProprietaryId() throws TdbException { TdbAu au1 = new TdbAu("Test AU", "pluginA"); // use param if specified with au type "journal" au1.setParam("journal_id", "foo"); assertEquals("foo", au1.getProprietaryIds()[0]); // use attr instead if also specified au1.setAttr("journal_id", "bar"); assertEquals("bar", au1.getProprietaryIds()[0]); // verify no series series id for journal if (au1.getProprietarySeriesIds() != null && au1.getProprietarySeriesIds().length > 0) { assertNull(au1.getProprietarySeriesIds()[0]); } // change au type to "book series" and verify no proprietary id au1.setPropertyByName("type", "bookSeries"); if (au1.getProprietaryIds() != null && au1.getProprietaryIds().length > 0) { assertNull(au1.getProprietaryIds()[0]); } // verify "journal_id" is is now interpreted as series id assertEquals("bar", au1.getProprietarySeriesIds()[0]); // verify that book id is now intrpreted as proprietary id au1.setAttr("book_id", "baz"); assertEquals("baz", au1.getProprietaryIds()[0]); } /** * Test equals() method * @throws TdbException for invalid Tdb operations */ public void testEquals() throws TdbException{ TdbAu au1 = new TdbAu("Test AU", "pluginA"); au1.setParam("name1", "val1"); au1.setParam("name2", "val2"); assertEquals(au1, au1); // same as title1 TdbAu au2 = new TdbAu("Test AU", "pluginA"); au2.setParam("name1", "val1"); au2.setParam("name2", "val2"); assertEquals(au1, au2); // differs from title1 only by au param TdbAu au3 = new TdbAu("Test AU", "pluginA"); au3.setParam("name1", "val1"); au3.setParam("name2", "val3"); assertNotEquals(au1, au3); // differs from title3 only by plugin id TdbAu au4 = new TdbAu("Test AU", "pluginB"); au4.setParam("name1", "val1"); au4.setParam("name2", "val3"); assertNotEquals(au3, au4); // differs from title1 only by name TdbAu au5 = new TdbAu("Test AU different name", "pluginA"); log.critical("au1: " + au1); log.critical("au5: " + au5); au5.setParam("name1", "val1"); au5.setParam("name2", "val2"); assertNotEquals(au1, au5); // au1 and au2 differ only by a property au1.setPropertyByName("issn", "1234-5678"); assertNotEquals(au1, au2); au2.setPropertyByName("issn", "1234-5678"); assertEquals(au1, au2); // au1 and au2 differ only by an attribute au1.setAttr("year", "1953"); assertNotEquals(au1, au2); au2.setAttr("year", "1954"); assertNotEquals(au1, au2); } /** * Test addAu() method. * @throws TdbException for invalid Tdb operations */ public void testGetTitle() throws TdbException { TdbTitle title = new TdbTitle("Test Title", "0000-0000"); TdbAu au = new TdbAu("Test AU", "pluginA"); title.addTdbAu(au); Collection<TdbAu> aus = title.getTdbAus(); assertEquals(1, aus.size()); assertTrue(aus.contains(au)); assertSameElements(ListUtil.list(au), ListUtil.fromIterator(title.tdbAuIterator())); // get title TdbTitle getTitle = au.getTdbTitle(); assertSame(title, getTitle); } /** * Test year operations * @throws TdbException for invalid Tdb operations */ public void testYear() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getYear()); assertNull(au.getStartYear()); assertNull(au.getEndYear()); au.setParam("year", "1971"); assertEquals("1971", au.getYear()); assertEquals("1971", au.getStartYear()); assertEquals("1971", au.getEndYear()); assertTrue(au.includesYear("1971")); assertFalse(au.includesYear("1970")); au = new TdbAu("TestAU", "pluginA"); au.setAttr("year", "1971-1977"); assertEquals("1971-1977", au.getYear()); assertEquals("1971", au.getStartYear()); assertEquals("1977", au.getEndYear()); assertTrue(au.includesYear("1971")); assertTrue(au.includesYear("1975")); assertFalse(au.includesYear("1970")); assertFalse(au.includesYear("1979")); au = new TdbAu("TestAU", "pluginA"); au.setAttr("year", "MCMLXXI-1977"); assertEquals("MCMLXXI-1977", au.getYear()); assertEquals("MCMLXXI", au.getStartYear()); assertEquals("1977", au.getEndYear()); assertTrue(au.includesYear("MCMLXXVII")); assertTrue(au.includesYear("MCMLXXV")); assertFalse(au.includesYear("MCMLXX")); assertFalse(au.includesYear("1979")); // test year range as range list au = new TdbAu("TestAU", "pluginA"); String issStr = "1960-1969, 1970, MCMLXXI-1977"; au.setAttr("year", issStr); assertEquals(issStr, au.getYear()); assertTrue(NumberUtil.isContiguousRange(au.getYear())); assertEquals("1960", au.getStartYear()); assertEquals("1977", au.getEndYear()); assertTrue(au.includesYear("MCMLXXVII")); assertTrue(au.includesYear("1972")); assertTrue(au.includesYear("1968")); assertTrue(au.includesYear("1970")); au = new TdbAu("TestAU", "pluginA"); au.setAttr("year", "1971,1973,1975-1977"); assertEquals("1971,1973,1975-1977", au.getYear()); assertEquals("1971", au.getStartYear()); assertEquals("1977", au.getEndYear()); assertTrue(au.includesYear("1971")); assertTrue(au.includesYear("1975")); assertFalse(au.includesYear("1970")); assertFalse(au.includesYear("1974")); assertFalse(au.includesYear("1979")); } /** * Test volumes operations * @throws TdbException for invalid Tdb operations */ public void testVolumes() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getVolume()); assertNull(au.getStartVolume()); assertNull(au.getEndVolume()); // test single arabic number au.setParam("volume", "1971"); assertEquals("1971", au.getVolume()); assertEquals("1971", au.getStartVolume()); assertEquals("1971", au.getEndVolume()); assertTrue(au.includesVolume("1971")); assertFalse(au.includesVolume("1970")); assertFalse(au.includesVolume("1979")); // test arabic number range au = new TdbAu("TestAU", "pluginA"); au.setAttr("volume", "1971-1977"); assertEquals("1971-1977", au.getVolume()); assertEquals("1971", au.getStartVolume()); assertEquals("1977", au.getEndVolume()); assertTrue(au.includesVolume("1971")); assertTrue(au.includesVolume("1975")); assertFalse(au.includesVolume("1970")); assertFalse(au.includesVolume("1979")); // test interchangeability of arabic and roman numbers au = new TdbAu("TestAU", "pluginA"); au.setAttr("volume", "MCMLXXI-1977"); assertEquals("MCMLXXI-1977", au.getVolume()); assertEquals("MCMLXXI", au.getStartVolume()); assertEquals("1977", au.getEndVolume()); assertTrue(au.includesVolume("MCMLXXVII")); assertTrue(au.includesVolume("MCMLXXV")); assertFalse(au.includesVolume("MCMLXX")); assertFalse(au.includesVolume("1979")); // test volume ranges as "topic ranges" au = new TdbAu("TestAU", "pluginA"); au.setAttr("volume", "Ge-Ma"); assertEquals("Ge-Ma", au.getVolume()); assertEquals("Ge", au.getStartVolume()); assertEquals("Ma", au.getEndVolume()); assertTrue(au.includesVolume("Ge")); assertTrue(au.includesVolume("Georgia")); assertTrue(au.includesVolume("M")); assertTrue(au.includesVolume("Ma")); assertTrue(au.includesVolume("Mathematics")); assertFalse(au.includesVolume("G")); assertFalse(au.includesVolume("Mbone")); // test volume range as range list au = new TdbAu("TestAU", "pluginA"); String volStr = "Ge-Ma;MCMLXXI-1977;1960-1969"; au.setAttr("volume", volStr); assertEquals(volStr, au.getVolume()); assertFalse(NumberUtil.isContiguousRange(au.getVolume())); assertEquals("Ge", au.getStartVolume()); assertEquals("1969", au.getEndVolume()); assertTrue(au.includesVolume("Ge")); assertTrue(au.includesVolume("MCMLXXVII")); assertTrue(au.includesVolume("1972")); assertTrue(au.includesVolume("1968")); assertFalse(au.includesVolume("1970")); // Test that Roman tokens get interpreted as Roman tokens au = new TdbAu("TestAU", "pluginA"); volStr = "s1v-s1x; s1i, s1ii"; au.setAttr("volume", volStr); assertEquals(volStr, au.getVolume()); // Include values from an alphabetic interpretation (topic ranges) // s1v-s1x to include s1ix and also s1w and assertTrue(au.includesVolume("s1vi")); assertTrue(au.includesVolume("s1ix")); assertTrue(au.includesVolume("s1w")); assertTrue(au.includesVolume("s1word")); // s1ii to not include s1iii assertFalse(au.includesVolume("s1iii")); au = new TdbAu("TestAU", "pluginA"); volStr = "1971,1973,1975-1977"; au.setAttr("volume", volStr); assertEquals(volStr, au.getVolume()); assertEquals("1971", au.getStartVolume()); assertEquals("1977", au.getEndVolume()); assertTrue(au.includesVolume("1971")); assertTrue(au.includesVolume("1975")); assertFalse(au.includesVolume("1970")); assertFalse(au.includesVolume("1974")); assertFalse(au.includesVolume("1979")); } /** * Test issue operations * @throws TdbException for invalid Tdb operations */ public void testIssues() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getIssue()); assertNull(au.getStartIssue()); assertNull(au.getEndIssue()); // test single arabic number au.setParam("issue", "1971"); assertEquals("1971", au.getIssue()); assertEquals("1971", au.getStartIssue()); assertEquals("1971", au.getEndIssue()); assertTrue(au.includesIssue("1971")); assertFalse(au.includesIssue("1970")); assertFalse(au.includesIssue("1979")); // test arabic number range au = new TdbAu("TestAU", "pluginA"); au.setAttr("issue", "1971-1977"); assertEquals("1971-1977", au.getIssue()); assertEquals("1971", au.getStartIssue()); assertEquals("1977", au.getEndIssue()); assertTrue(au.includesIssue("1971")); assertTrue(au.includesIssue("1975")); assertFalse(au.includesIssue("1970")); assertFalse(au.includesIssue("1979")); // test interchangeability of arabic and roman numbers au = new TdbAu("TestAU", "pluginA"); au.setAttr("issue", "MCMLXXI-1977"); assertEquals("MCMLXXI-1977", au.getIssue()); assertEquals("MCMLXXI", au.getStartIssue()); assertEquals("1977", au.getEndIssue()); assertTrue(au.includesIssue("MCMLXXVII")); assertTrue(au.includesIssue("MCMLXXV")); assertFalse(au.includesIssue("MCMLXX")); assertFalse(au.includesIssue("1979")); // test issue ranges as "topic ranges" au = new TdbAu("TestAU", "pluginA"); au.setAttr("issue", "Ge-Ma"); assertEquals("Ge-Ma", au.getIssue()); assertEquals("Ge", au.getStartIssue()); assertEquals("Ma", au.getEndIssue()); assertTrue(au.includesIssue("Ge")); assertTrue(au.includesIssue("Georgia")); assertTrue(au.includesIssue("M")); assertTrue(au.includesIssue("Ma")); assertTrue(au.includesIssue("Mathematics")); assertFalse(au.includesIssue("G")); assertFalse(au.includesIssue("Mbone")); // test issue range as range list au = new TdbAu("TestAU", "pluginA"); String issStr = "Ge-Ma;MCMLXXI-1977;1960-1969"; au.setAttr("issue", issStr); assertEquals(issStr, au.getIssue()); assertFalse(NumberUtil.isContiguousRange(au.getIssue())); assertEquals("Ge", au.getStartIssue()); assertEquals("1969", au.getEndIssue()); assertTrue(au.includesIssue("Ge")); assertTrue(au.includesIssue("MCMLXXVII")); assertTrue(au.includesIssue("1972")); assertTrue(au.includesIssue("1968")); assertFalse(au.includesIssue("1970")); au = new TdbAu("TestAU", "pluginA"); issStr = "1971,1973,1975-1977"; au.setAttr("issue", issStr); assertEquals(issStr, au.getIssue()); assertEquals("1971", au.getStartIssue()); assertEquals("1977", au.getEndIssue()); assertTrue(au.includesIssue("1971")); assertTrue(au.includesIssue("1975")); assertFalse(au.includesIssue("1970")); assertFalse(au.includesIssue("1974")); assertFalse(au.includesIssue("1979")); } /** * Test ISBNs and ISBNs * @throws TdbException for invalid Tdb operations */ public void testIssns() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); au.setPropertyByName("issn", "1234-5678"); au.setPropertyByName("eissn", "2468-1357"); au.setPropertyByName("issnl", "8765-4321"); au.setAttr("isbn", "1234567890"); assertEquals("1234-5678", au.getPrintIssn()); assertEquals("2468-1357", au.getEissn()); assertEquals("8765-4321", au.getIssnL()); assertNotNull(au.getIssn()); assertEquals("1234567890", au.getIsbn()); assertEquals("1234567890", au.getPrintIsbn()); assertNull(au.getEisbn()); // Test behaviour with ill-formed ISSNs au.setPropertyByName("issn", "1234-5"); au.setPropertyByName("eissn", "-2468"); au.setPropertyByName("issnl", "string"); // Individual getters should return the invalid string, // but getIssn() should return null assertEquals("1234-5", au.getPrintIssn()); assertEquals("-2468", au.getEissn()); assertEquals("string", au.getIssnL()); assertNull(au.getIssn()); } /** * Test publication title * @throws TdbException for invalid Tdb operations */ public void testJournalTitle() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getPublicationTitle()); // because au has no TdbTitle au.setPropertyByName("issn", "1234-5678"); assertNull(au.getPublicationTitle()); // because au has no TdbTitle au.setAttr("isbn", "978-3-540-33894-9"); assertEquals("Test AU", au.getPublicationTitle()); au.setPropertyByName("type", "book"); assertEquals("Test AU", au.getPublicationTitle()); } /** * Test publication type * @throws TdbException for invalid Tdb operations */ public void testPublicationType() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertEquals("journal", au.getPublicationType()); au.setPropertyByName("issn", "1234-5678"); assertEquals("journal", au.getPublicationType()); au.setAttr("isbn", "978-3-540-33894-9"); assertEquals("bookSeries", au.getPublicationType()); au.setPropertyByName("type", "book"); assertEquals("book", au.getPublicationType()); } /** * Test coverage depth * @throws TdbException for invalid Tdb operations */ public void testCoverageDepth() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); // test default when no attributes present assertEquals("fulltext", au.getCoverageDepth()); // test default when attributes present au.setAttr("attr_name", "attr_value"); assertEquals("fulltext", au.getCoverageDepth()); // test when au_coverage_depth attribute set au.setAttr("au_coverage_depth","abstracts"); assertEquals("abstracts", au.getCoverageDepth()); } /** * Test getPublisher() method. * @throws TdbException for invalid Tdb operations */ public void testGetPublisher() throws TdbException { TdbPublisher publisher = new TdbPublisher("Test Publisher"); Collection<TdbTitle> titles = publisher.getTdbTitles(); assertEmpty(titles); // add title TdbTitle title = new TdbTitle("Test Title", "0000-0000"); publisher.addTdbTitle(title); // add au TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getPublicationTitle()); title.addTdbAu(au); // ensure same as publisher for AU's title TdbPublisher getPublisher = au.getTdbPublisher(); assertEquals(publisher, getPublisher); assertEquals("Test Publisher", au.getPublisherName()); } /** * Test getProvider() method. * @throws TdbException for invalid Tdb operations */ public void testGetProvider() throws TdbException { TdbProvider provider = new TdbProvider("Test Provider"); Collection<TdbTitle> titles = provider.getTdbTitles(); assertEmpty(titles); // add au TdbAu au = new TdbAu("Test AU", "pluginA"); assertNull(au.getProviderName()); provider.addTdbAu(au); // ensure same as publisher for AU's title TdbProvider getProvider = au.getTdbProvider(); assertEquals(provider, getProvider); assertEquals("Test Provider", au.getProviderName()); } /** * Test convenience methods. * @throws TdbException for invalid Tdb operations */ public void testConvenienceMethods() throws TdbException { TdbPublisher publisher = new TdbPublisher("Test Publisher"); Collection<TdbTitle> titles = publisher.getTdbTitles(); assertEmpty(titles); // add title TdbTitle title = new TdbTitle("Test Title", "1234-5678"); publisher.addTdbTitle(title); // add au TdbAu au = new TdbAu("Test AU", "org.lockss.TestPlugin"); au.setPluginVersion("7"); au.setPropertyByName("estSize", "32.5MB"); au.setParam("p1", "v1"); au.setParam("p2", "v2"); title.addTdbAu(au); assertEquals("7", au.getPropertyByName("pluginVersion")); assertEquals("Test Title", au.getPublicationTitle()); assertEquals(32500000, au.getEstimatedSize()); Properties props = au.toProperties(); assertTrue(props.containsKey("param.1.value")); assertTrue(props.containsValue("v1")); assertTrue(props.containsKey("param.2.value")); assertTrue(props.containsValue("v2")); /* assertEquals("32.5MB", props.getProperty("estSize")); */ } /** * Test param methods * @throws TdbException for invalid Tdb operations */ public void testParams() throws TdbException { // set two params TdbAu au = new TdbAu("Test AU", "pluginA"); au.setParam("name1", "val1"); au.setParam("name2", "val2"); au.setParam("name3", "val3"); // set invalid params try { au.setParam("name4", null); fail("TdbAu did not throw IllegalArgumentException for null param argument."); } catch (IllegalArgumentException ex) { } // ensure params contain expected names and values Map<String,String> getParams = au.getParams(); assertNotNull(getParams); assertEquals(3, getParams.size()); assertEquals("val1", getParams.get("name1")); assertEquals("val2", getParams.get("name2")); assertEquals("val3", getParams.get("name3")); // ensure param cannot be reset try { au.setParam("name2", "newval2"); fail("TdbAu did not throw TdbException resetting param."); } catch (TdbException ex) { } assertNotNull(getParams); assertEquals(3, getParams.size()); getParams = au.getParams(); assertEquals("val2", getParams.get("name2")); TdbTitle title = new TdbTitle("Test Title", "0000-0000"); title.addTdbAu(au); try { au.setParam("name4", "newval4"); fail("TdbAu did not throw TdbException setting param once added to title."); } catch (TdbException ex) { } assertNotNull(getParams); assertEquals(3, getParams.size()); getParams = au.getParams(); assertNull(getParams.get("name4")); } /** * Test attr methods */ public void testAttrs() throws TdbException { // set two attrs TdbAu au = new TdbAu("Test AU", "Test ID"); au.setAttr("name1", "val1"); au.setAttr("name2", "val2"); // set invalid params try { au.setAttr("name3", null); fail("TdbAu did not throw IllegalArgumentException for null attr argument."); } catch (IllegalArgumentException ex) { } // ensure params contain expected names and values Map<String,String> getAttrs = au.getAttrs(); assertNotNull(getAttrs); assertEquals(2, getAttrs.size()); assertEquals("val1", getAttrs.get("name1")); assertEquals("val2", getAttrs.get("name2")); // ensure attr cannot be reset try { au.setAttr("name2", "newval2"); fail("TdbAu did not throw TdbException resetting attr."); } catch (TdbException ex) { } assertNotNull(getAttrs); assertEquals(2, getAttrs.size()); getAttrs = au.getAttrs(); assertEquals("val2", getAttrs.get("name2")); } /** * Test TdbAu.Id * @throws TdbException for invalid Tdb operations */ public void testTdbAuId() throws TdbException { TdbAu au1 = new TdbAu("Test AU1", "pluginA"); au1.setAttr("a", "A"); au1.setAttr("b", "A"); au1.setParam("x", "X"); au1.setPluginVersion("3"); TdbAu au2 = new TdbAu("Test AU1", "pluginA"); au2.setAttr("a", "A"); au2.setAttr("b", "A"); au2.setParam("x", "X"); au2.setPluginVersion("3"); TdbAu au3 = new TdbAu("Test AU1", "pluginB"); au3.setAttr("a", "A"); au3.setAttr("b", "A"); au3.setParam("x", "X"); au3.setPluginVersion("3"); assertEquals(au1.getId(), au2.getId()); assertNotEquals(au1.getId(), au3.getId()); } /** * Test AuId * @throws TdbException for invalid Tdb operations */ public void testGetAuId() throws TdbException { PluginManager pmgr = getMockLockssDaemon().getPluginManager(); TdbAu au1 = new TdbAu("Test AU1", "pluginA"); au1.setAttr("a", "A"); au1.setParam("x", "X"); try { au1.getAuId(pmgr); fail("getAuId() with no plugin should throw"); } catch (IllegalStateException e) { } MockPlugin plug = (MockPlugin)PluginTestUtil.findPlugin(MockPlugin.class); plug.setAuConfigDescrs(ListUtil.list(ConfigParamDescr.BASE_URL, ConfigParamDescr.VOLUME_NUMBER, ConfigParamDescr.CRAWL_PROXY)); TdbAu au2 = new TdbAu("Test AU1", plug.getPluginId()); au2.setAttr("a", "A"); au2.setParam("base_url", "http://example.com/bbb/"); au2.setParam("volume", "12"); au2.setParam("crawl_proxy", "foo.bar:8080"); assertEquals("org|lockss|test|MockPlugin&base_url~http%3A%2F%2Fexample%2Ecom%2Fbbb%2F&volume~12", au2.getAuId(pmgr)); TdbAu au3 = new TdbAu("Test AU1", plug.getPluginId()); au3.setAttr("a", "A"); au3.setParam("base_url", "http://example.com/bbb/"); au3.setParam("crawl_proxy", "foo.bar:8080"); try { au3.getAuId(pmgr); fail("getAuId() with missing config param should throw"); } catch (NullPointerException e) { } } /** * Test copyForTdbTitle method. * @throws TdbException for invalid Tdb operations */ public void testCopyForTdbTitle() throws TdbException { TdbAu au1 = new TdbAu("Test AU1", "pluginA"); au1.setAttr("a", "A"); au1.setAttr("b", "A"); au1.setParam("x", "X"); au1.setPluginVersion("3"); TdbTitle title1 = new TdbTitle("Test Title1", "0000-0000"); title1.addTdbAu(au1); TdbTitle title2 = new TdbTitle("Test Title2", "0000-0000"); TdbAu au2 = au1.copyForTdbTitle(title2); assertSame(title2, au2.getTdbTitle()); assertNotSame(title1, title2); assertEquals(au1.getName(), au2.getName()); assertEquals(au1.getAttr("a"), au2.getAttr("a")); assertEquals(au1.getParam("x"), au2.getParam("x")); assertEquals(au1.getPluginId(), au2.getPluginId()); assertEquals(au1.getPluginVersion(), au2.getPluginVersion()); } /** * Test isSerial() * @throws TdbException for invalid Tdb operations */ public void testIsSerial() throws TdbException { TdbAu au = new TdbAu("Test AU", "pluginA"); assertTrue(au.isSerial()); au.setPropertyByName("issn", "1234-5678"); assertTrue(au.isSerial()); au.setAttr("isbn", "978-3-540-33894-9"); assertTrue(au.isSerial()); au.setPropertyByName("type", "book"); assertFalse(au.isSerial()); au.setPropertyByName("type", "blog"); assertFalse(au.isSerial()); } }
aimuch/AiTools
darknet/clipPointsROI.py
<gh_stars>10-100 # -*- coding: utf-8 -*- # Author : <NAME> # Last modified: 2019-07-23 # This tool is used to clip images by reading txt labels # input: python3 clipImg.py ./img ./txt ./dst # output: # ./dst/obj1 # ./dst/obj2 # The Label txt format: # classNO center_x center_y width height import argparse import os import sys import random import shutil from glob import glob import cv2 def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('imgDir', help='img directory', type=str) parser.add_argument('txtDir', help='label directory', type=str) parser.add_argument('dstDir', help='dst directory', type=str) args = parser.parse_args() return args def saveROI(imgDir, txtDir, dstDir): imgDir = os.path.abspath(imgDir) txtDir = os.path.abspath(txtDir) dstDir = os.path.abspath(dstDir) if imgDir[-1] == "/": imgDir = imgDir[:-1] if txtDir[-1] == "/": txtDir = txtDir[:-1] if os.path.exists(dstDir): shutil.rmtree(dstDir) # recursive os.makedirs(dstDir) print(dstDir, " has been created!") imgList = os.listdir(imgDir) txtList = os.listdir(txtDir) # filelist = glob(os.path.join(imgDir, "*.jpg")) for img in imgList: if os.path.isdir(img): continue file_name, file_extend = os.path.splitext(img) imgPath = os.path.join(imgDir, img) txtPath = os.path.join(txtDir, file_name+".txt") if not os.path.exists(txtPath): print("Warning %s is not exits!!!!"%txtPath) print(imgPath) print(txtPath) imgArray = cv2.imread(imgPath) imgShape = imgArray.shape imgWidth = imgShape[1] imgHeight = imgShape[0] with open(txtPath, "r") as txt: lines = txt.read().split('\n') for i, line in enumerate(lines): if line is '' or line is ' ' or line is None: continue lineInfo = line.split(" ") # print(lineInfo) obj = lineInfo[0] x = int(float(lineInfo[1])*imgWidth) y = int(float(lineInfo[2])*imgHeight) # w = int(float(lineInfo[3])*imgWidth) # h = int(float(lineInfo[4])*imgHeight) # left = x-int(w/2) if x-int(w/2)>0 else 0 # right = x+int(w/2) if x+int(w/2)<imgHeight else imgHeight # top = y-int(h/2) if y-int(h/2)>0 else 0 # bottom = y+int(h/2) if y+int(h/2)<imgHeight else imgHeight w = 46 h = 46 left = x-23 if x-23>0 else 0 right = x+23 if x+23<imgWidth else imgWidth top = y-23 if y-23>0 else 0 bottom = y+23 if y+23<imgHeight else imgHeight objDir = os.path.join(dstDir, obj) if not os.path.exists(objDir): os.mkdir(objDir) roiPath = os.path.join(objDir, file_name+"_"+str(i)+".jpg") roiArray = imgArray[top:bottom, left:right, :] cv2.imwrite(roiPath, roiArray) if __name__ == '__main__': args = parse_args() imgDir = args.imgDir txtDir = args.txtDir dstDir = args.dstDir if not os.path.exists(imgDir): print("Error !!! %s is not exists, please check the parameter"%imgDir) sys.exit(0) if not os.path.exists(txtDir): print("Error !!! %s is not exists, please check the parameter"%txtDir) sys.exit(0) if not os.path.exists(dstDir): print("Warning !!! %s is not exists, please check the parameter"%dstDir) saveROI(imgDir, txtDir, dstDir) print("Done!")
matallana/Angular6-base-NOT-clean
routes/ocupations/ocupation.js
<gh_stars>0 /* *Autor: <NAME> *Fecha: 01-2018-2019 *Modulo: routes profesion se crea api POST, PUT, GET se agrega el middlerwares *Información: */ 'use strict' var express = require('express'); var api = express.Router(); var md_auth = require('../../middlerwares/authenticated'); var OcupationController = require('../../controller/ocupation/ocupation'); //Enviar api.post('/registrar_ocupation', md_auth.ensureAuth, OcupationController.saveOcupation); //actualizar api.put('/update_ocupation/:id', md_auth.ensureAuth, OcupationController.updateOcupation); //traer api.get('/get_ocupation', md_auth.ensureAuth, OcupationController.getOcupation); module.exports = api;
streamline-eu/dynamic-flink
flink-runtime/src/main/java/org/apache/flink/runtime/leaderretrieval/ZooKeeperLeaderRetrievalService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.leaderretrieval; import org.apache.flink.util.Preconditions; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.util.Objects; import java.util.UUID; /** * The counterpart to the {@link org.apache.flink.runtime.leaderelection.ZooKeeperLeaderElectionService}. * This implementation of the {@link LeaderRetrievalService} retrieves the current leader which has * been elected by the {@link org.apache.flink.runtime.leaderelection.ZooKeeperLeaderElectionService}. * The leader address as well as the current leader session ID is retrieved from ZooKeeper. */ public class ZooKeeperLeaderRetrievalService implements LeaderRetrievalService, NodeCacheListener { private static final Logger LOG = LoggerFactory.getLogger( ZooKeeperLeaderRetrievalService.class); /** Connection to the used ZooKeeper quorum */ private final CuratorFramework client; /** Curator recipe to watch changes of a specific ZooKeeper node */ private final NodeCache cache; /** Listener which will be notified about leader changes */ private volatile LeaderRetrievalListener leaderListener; private String lastLeaderAddress; private UUID lastLeaderSessionID; private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; /** * Creates a leader retrieval service which uses ZooKeeper to retrieve the leader information. * * @param client Client which constitutes the connection to the ZooKeeper quorum * @param retrievalPath Path of the ZooKeeper node which contains the leader information */ public ZooKeeperLeaderRetrievalService(CuratorFramework client, String retrievalPath) { this.client = client; this.cache = new NodeCache(client, retrievalPath); } @Override public void start(LeaderRetrievalListener listener) throws Exception { Preconditions.checkNotNull(listener, "Listener must not be null."); Preconditions.checkState(leaderListener == null, "ZooKeeperLeaderRetrievalService can " + "only be started once."); LOG.info("Starting ZooKeeperLeaderRetrievalService."); leaderListener = listener; cache.getListenable().addListener(this); cache.start(); client.getConnectionStateListenable().addListener(connectionStateListener); } @Override public void stop() throws Exception { LOG.info("Stopping ZooKeeperLeaderRetrievalService."); client.getConnectionStateListenable().removeListener(connectionStateListener); cache.close(); } @Override public void nodeChanged() throws Exception { try { LOG.debug("Leader node has changed."); ChildData childData = cache.getCurrentData(); String leaderAddress; UUID leaderSessionID; if (childData == null) { leaderAddress = null; leaderSessionID = null; } else { byte[] data = childData.getData(); if (data == null || data.length == 0) { leaderAddress = null; leaderSessionID = null; } else { ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bais); leaderAddress = ois.readUTF(); leaderSessionID = (UUID) ois.readObject(); } } if(!(Objects.equals(leaderAddress, lastLeaderAddress) && Objects.equals(leaderSessionID, lastLeaderSessionID))) { LOG.debug( "New leader information: Leader={}, session ID={}.", leaderAddress, leaderSessionID); lastLeaderAddress = leaderAddress; lastLeaderSessionID = leaderSessionID; leaderListener.notifyLeaderAddress(leaderAddress, leaderSessionID); } } catch (Exception e) { leaderListener.handleError(new Exception("Could not handle node changed event.", e)); throw e; } } protected void handleStateChange(ConnectionState newState) { switch (newState) { case CONNECTED: LOG.debug("Connected to ZooKeeper quorum. Leader retrieval can start."); break; case SUSPENDED: LOG.warn("Connection to ZooKeeper suspended. Can no longer retrieve the leader from " + "ZooKeeper."); break; case RECONNECTED: LOG.info("Connection to ZooKeeper was reconnected. Leader retrieval can be restarted."); break; case LOST: LOG.warn("Connection to ZooKeeper lost. Can no longer retrieve the leader from " + "ZooKeeper."); break; } } }
fernando-romulo-silva/myStudies
java/miscellaneous/dockerAndKubernetsForJavaDevelopers/src/main/java/br/com/fernando/chapter06_running_container_java_applications/part06_runningWithMaven/Part01.java
<reponame>fernando-romulo-silva/myStudies<filename>java/miscellaneous/dockerAndKubernetsForJavaDevelopers/src/main/java/br/com/fernando/chapter06_running_container_java_applications/part06_runningWithMaven/Part01.java<gh_stars>1-10 package br.com.fernando.chapter06_running_container_java_applications.part06_runningWithMaven; public class Part01 { // Starting and stopping containers // // To start-up the container, execute the following: // // $ mvn clean package docker:start // // The container is now running in the background. // // $ mvn docker:stop }
JeffreyRiggle/text-adventure-lib
src/persistence/player/characteristicPersistenceObject.js
import {NamedPersistenceObject} from './namedPersistenceObject'; import {Characteristic} from '@jeffriggle/player-lib'; export class CharacteristicPersistenceObject extends NamedPersistenceObject { constructor(characteristic) { super('Characteristic'); if (characteristic) { this.convertToPersistence(characteristic); } } convertToCharacteristic() { return new Characteristic(this.name, this.description, this.value); } }
dyna-mis/Hilabeling
src/gui/raster/qgspalettedrendererwidget.cpp
/*************************************************************************** qgspalettedrendererwidget.cpp ----------------------------- begin : February 2012 copyright : (C) 2012 by <NAME> email : <EMAIL> ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "qgspalettedrendererwidget.h" #include "qgspalettedrasterrenderer.h" #include "qgsrasterdataprovider.h" #include "qgsrasterlayer.h" #include "qgscolordialog.h" #include "qgssettings.h" #include "qgsproject.h" #include <QColorDialog> #include <QInputDialog> #include <QFileDialog> #include <QMessageBox> #include <QMenu> #ifdef ENABLE_MODELTEST #include "modeltest.h" #endif QgsPalettedRendererWidget::QgsPalettedRendererWidget( QgsRasterLayer *layer, const QgsRectangle &extent ): QgsRasterRendererWidget( layer, extent ) { setupUi( this ); mCalculatingProgressBar->hide(); mCancelButton->hide(); mContextMenu = new QMenu( tr( "Options" ), this ); mContextMenu->addAction( tr( "Change Color…" ), this, SLOT( changeColor() ) ); mContextMenu->addAction( tr( "Change Opacity…" ), this, SLOT( changeOpacity() ) ); mContextMenu->addAction( tr( "Change Label…" ), this, SLOT( changeLabel() ) ); mAdvancedMenu = new QMenu( tr( "Advanced Options" ), this ); QAction *mLoadFromLayerAction = mAdvancedMenu->addAction( tr( "Load Classes from Layer" ) ); connect( mLoadFromLayerAction, &QAction::triggered, this, &QgsPalettedRendererWidget::loadFromLayer ); QAction *loadFromFile = mAdvancedMenu->addAction( tr( "Load Color Map from File…" ) ); connect( loadFromFile, &QAction::triggered, this, &QgsPalettedRendererWidget::loadColorTable ); QAction *exportToFile = mAdvancedMenu->addAction( tr( "Export Color Map to File…" ) ); connect( exportToFile, &QAction::triggered, this, &QgsPalettedRendererWidget::saveColorTable ); mButtonAdvanced->setMenu( mAdvancedMenu ); mModel = new QgsPalettedRendererModel( this ); mTreeView->setSortingEnabled( false ); mTreeView->setModel( mModel ); #ifdef ENABLE_MODELTEST new ModelTest( mModel, this ); #endif mSwatchDelegate = new QgsColorSwatchDelegate( this ); mTreeView->setItemDelegateForColumn( QgsPalettedRendererModel::ColorColumn, mSwatchDelegate ); mTreeView->setColumnWidth( QgsPalettedRendererModel::ColorColumn, Qgis::UI_SCALE_FACTOR * fontMetrics().width( 'X' ) * 6.6 ); mTreeView->setContextMenuPolicy( Qt::CustomContextMenu ); mTreeView->setSelectionMode( QAbstractItemView::ExtendedSelection ); mTreeView->setDragEnabled( true ); mTreeView->setAcceptDrops( true ); mTreeView->setDropIndicatorShown( true ); mTreeView->setDragDropMode( QAbstractItemView::InternalMove ); mTreeView->setSelectionBehavior( QAbstractItemView::SelectRows ); mTreeView->setDefaultDropAction( Qt::MoveAction ); connect( mTreeView, &QTreeView::customContextMenuRequested, this, [ = ]( QPoint ) { mContextMenu->exec( QCursor::pos() ); } ); btnColorRamp->setShowRandomColorRamp( true ); connect( btnColorRamp, &QgsColorRampButton::colorRampChanged, this, &QgsPalettedRendererWidget::applyColorRamp ); mBandComboBox->setLayer( mRasterLayer ); if ( mRasterLayer ) { QgsRasterDataProvider *provider = mRasterLayer->dataProvider(); if ( !provider ) { return; } setFromRenderer( mRasterLayer->renderer() ); } connect( mBandComboBox, &QgsRasterBandComboBox::bandChanged, this, &QgsRasterRendererWidget::widgetChanged ); connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); connect( mDeleteEntryButton, &QPushButton::clicked, this, &QgsPalettedRendererWidget::deleteEntry ); connect( mButtonDeleteAll, &QPushButton::clicked, mModel, &QgsPalettedRendererModel::deleteAll ); connect( mAddEntryButton, &QPushButton::clicked, this, &QgsPalettedRendererWidget::addEntry ); connect( mClassifyButton, &QPushButton::clicked, this, &QgsPalettedRendererWidget::classify ); QgsRasterDataProvider *provider = mRasterLayer->dataProvider(); if ( provider ) { mLoadFromLayerAction->setEnabled( !provider->colorTable( mBandComboBox->currentBand() ).isEmpty() ); } else { mLoadFromLayerAction->setEnabled( false ); } connect( QgsProject::instance(), static_cast < void ( QgsProject::* )( QgsMapLayer * ) >( &QgsProject::layerWillBeRemoved ), this, &QgsPalettedRendererWidget::layerWillBeRemoved ); connect( mBandComboBox, &QgsRasterBandComboBox::bandChanged, this, &QgsPalettedRendererWidget::bandChanged ); } QgsPalettedRendererWidget::~QgsPalettedRendererWidget() { if ( mGatherer ) { mGatherer->stop(); mGatherer->wait(); // mGatherer is deleted when wait completes } } QgsRasterRenderer *QgsPalettedRendererWidget::renderer() { QgsPalettedRasterRenderer::ClassData classes = mModel->classData(); int bandNumber = mBandComboBox->currentBand(); QgsPalettedRasterRenderer *r = new QgsPalettedRasterRenderer( mRasterLayer->dataProvider(), bandNumber, classes ); if ( !btnColorRamp->isNull() ) { r->setSourceColorRamp( btnColorRamp->colorRamp() ); } return r; } void QgsPalettedRendererWidget::setFromRenderer( const QgsRasterRenderer *r ) { const QgsPalettedRasterRenderer *pr = dynamic_cast<const QgsPalettedRasterRenderer *>( r ); if ( pr ) { mBand = pr->band(); whileBlocking( mBandComboBox )->setBand( mBand ); //read values and colors and fill into tree widget mModel->setClassData( pr->classes() ); if ( pr->sourceColorRamp() ) { whileBlocking( btnColorRamp )->setColorRamp( pr->sourceColorRamp() ); } else { std::unique_ptr< QgsColorRamp > ramp( new QgsRandomColorRamp() ); whileBlocking( btnColorRamp )->setColorRamp( ramp.get() ); } } else { loadFromLayer(); std::unique_ptr< QgsColorRamp > ramp( new QgsRandomColorRamp() ); whileBlocking( btnColorRamp )->setColorRamp( ramp.get() ); } } void QgsPalettedRendererWidget::setSelectionColor( const QItemSelection &selection, const QColor &color ) { // don't want to emit widgetChanged multiple times disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); QModelIndex colorIndex; const auto constSelection = selection; for ( const QItemSelectionRange &range : constSelection ) { const auto constIndexes = range.indexes(); for ( const QModelIndex &index : constIndexes ) { colorIndex = mModel->index( index.row(), QgsPalettedRendererModel::ColorColumn ); mModel->setData( colorIndex, color, Qt::EditRole ); } } connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } void QgsPalettedRendererWidget::deleteEntry() { // don't want to emit widgetChanged multiple times disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); QItemSelection sel = mTreeView->selectionModel()->selection(); const auto constSel = sel; for ( const QItemSelectionRange &range : constSel ) { if ( range.isValid() ) mModel->removeRows( range.top(), range.bottom() - range.top() + 1, range.parent() ); } connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } void QgsPalettedRendererWidget::addEntry() { disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); QColor color( 150, 150, 150 ); std::unique_ptr< QgsColorRamp > ramp( btnColorRamp->colorRamp() ); if ( ramp ) { color = ramp->color( 1.0 ); } QModelIndex newEntry = mModel->addEntry( color ); mTreeView->scrollTo( newEntry ); mTreeView->selectionModel()->select( newEntry, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows ); connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } void QgsPalettedRendererWidget::changeColor() { QItemSelection sel = mTreeView->selectionModel()->selection(); QModelIndex colorIndex = mModel->index( sel.first().top(), QgsPalettedRendererModel::ColorColumn ); QColor currentColor = mModel->data( colorIndex, Qt::DisplayRole ).value<QColor>(); QgsPanelWidget *panel = QgsPanelWidget::findParentPanel( qobject_cast< QWidget * >( parent() ) ); if ( panel && panel->dockMode() ) { QgsCompoundColorWidget *colorWidget = new QgsCompoundColorWidget( panel, currentColor, QgsCompoundColorWidget::LayoutVertical ); colorWidget->setPanelTitle( tr( "Select Color" ) ); colorWidget->setAllowOpacity( true ); connect( colorWidget, &QgsCompoundColorWidget::currentColorChanged, this, [ = ]( const QColor & color ) { setSelectionColor( sel, color ); } ); panel->openPanel( colorWidget ); } else { // modal dialog version... yuck QColor newColor = QgsColorDialog::getColor( currentColor, this, QStringLiteral( "Change color" ), true ); if ( newColor.isValid() ) { setSelectionColor( sel, newColor ); } } } void QgsPalettedRendererWidget::changeOpacity() { QItemSelection sel = mTreeView->selectionModel()->selection(); QModelIndex colorIndex = mModel->index( sel.first().top(), QgsPalettedRendererModel::ColorColumn ); QColor currentColor = mModel->data( colorIndex, Qt::DisplayRole ).value<QColor>(); bool ok; double oldOpacity = ( currentColor.alpha() / 255.0 ) * 100.0; double opacity = QInputDialog::getDouble( this, tr( "Opacity" ), tr( "Change color opacity [%]" ), oldOpacity, 0.0, 100.0, 0, &ok ); if ( ok ) { int newOpacity = opacity / 100 * 255; // don't want to emit widgetChanged multiple times disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); const auto constSel = sel; for ( const QItemSelectionRange &range : constSel ) { const auto constIndexes = range.indexes(); for ( const QModelIndex &index : constIndexes ) { colorIndex = mModel->index( index.row(), QgsPalettedRendererModel::ColorColumn ); QColor newColor = mModel->data( colorIndex, Qt::DisplayRole ).value<QColor>(); newColor.setAlpha( newOpacity ); mModel->setData( colorIndex, newColor, Qt::EditRole ); } } connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } } void QgsPalettedRendererWidget::changeLabel() { QItemSelection sel = mTreeView->selectionModel()->selection(); QModelIndex labelIndex = mModel->index( sel.first().top(), QgsPalettedRendererModel::LabelColumn ); QString currentLabel = mModel->data( labelIndex, Qt::DisplayRole ).toString(); bool ok; QString newLabel = QInputDialog::getText( this, tr( "Label" ), tr( "Change label" ), QLineEdit::Normal, currentLabel, &ok ); if ( ok ) { // don't want to emit widgetChanged multiple times disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); const auto constSel = sel; for ( const QItemSelectionRange &range : constSel ) { const auto constIndexes = range.indexes(); for ( const QModelIndex &index : constIndexes ) { labelIndex = mModel->index( index.row(), QgsPalettedRendererModel::LabelColumn ); mModel->setData( labelIndex, newLabel, Qt::EditRole ); } } connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } } void QgsPalettedRendererWidget::applyColorRamp() { std::unique_ptr< QgsColorRamp > ramp( btnColorRamp->colorRamp() ); if ( !ramp ) { return; } disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); QgsPalettedRasterRenderer::ClassData data = mModel->classData(); QgsPalettedRasterRenderer::ClassData::iterator cIt = data.begin(); double numberOfEntries = data.count(); int i = 0; if ( QgsRandomColorRamp *randomRamp = dynamic_cast<QgsRandomColorRamp *>( ramp.get() ) ) { //ramp is a random colors ramp, so inform it of the total number of required colors //this allows the ramp to pregenerate a set of visually distinctive colors randomRamp->setTotalColorCount( numberOfEntries ); } if ( numberOfEntries > 1 ) numberOfEntries -= 1; //avoid duplicate first color for ( ; cIt != data.end(); ++cIt ) { cIt->color = ramp->color( i / numberOfEntries ); i++; } mModel->setClassData( data ); connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); emit widgetChanged(); } void QgsPalettedRendererWidget::loadColorTable() { QgsSettings settings; QString lastDir = settings.value( QStringLiteral( "lastColorMapDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, tr( "Load Color Table from File" ), lastDir ); if ( !fileName.isEmpty() ) { QgsPalettedRasterRenderer::ClassData classes = QgsPalettedRasterRenderer::classDataFromFile( fileName ); if ( !classes.isEmpty() ) { disconnect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); mModel->setClassData( classes ); emit widgetChanged(); connect( mModel, &QgsPalettedRendererModel::classesChanged, this, &QgsPalettedRendererWidget::widgetChanged ); } else { QMessageBox::critical( nullptr, tr( "Load Color Table" ), tr( "Could not interpret file as a raster color table." ) ); } } } void QgsPalettedRendererWidget::saveColorTable() { QgsSettings settings; QString lastDir = settings.value( QStringLiteral( "lastColorMapDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( this, tr( "Save Color Table as File" ), lastDir, tr( "Text (*.clr)" ) ); if ( !fileName.isEmpty() ) { if ( !fileName.endsWith( QLatin1String( ".clr" ), Qt::CaseInsensitive ) ) { fileName = fileName + ".clr"; } QFile outputFile( fileName ); if ( outputFile.open( QFile::WriteOnly | QIODevice::Truncate ) ) { QTextStream outputStream( &outputFile ); outputStream << QgsPalettedRasterRenderer::classDataToString( mModel->classData() ); outputStream.flush(); outputFile.close(); QFileInfo fileInfo( fileName ); settings.setValue( QStringLiteral( "lastColorMapDir" ), fileInfo.absoluteDir().absolutePath() ); } else { QMessageBox::warning( this, tr( "Save Color Table as File" ), tr( "Write access denied. Adjust the file permissions and try again.\n\n" ) ); } } } void QgsPalettedRendererWidget::classify() { if ( mRasterLayer ) { QgsRasterDataProvider *provider = mRasterLayer->dataProvider(); if ( !provider ) { return; } if ( mGatherer ) { mGatherer->stop(); return; } mGatherer = new QgsPalettedRendererClassGatherer( mRasterLayer, mBandComboBox->currentBand(), mModel->classData(), btnColorRamp->colorRamp() ); connect( mGatherer, &QgsPalettedRendererClassGatherer::progressChanged, mCalculatingProgressBar, &QProgressBar::setValue ); mCalculatingProgressBar->show(); mCancelButton->show(); connect( mCancelButton, &QPushButton::clicked, mGatherer, &QgsPalettedRendererClassGatherer::stop ); connect( mGatherer, &QgsPalettedRendererClassGatherer::collectedClasses, this, &QgsPalettedRendererWidget::gatheredClasses ); connect( mGatherer, &QgsPalettedRendererClassGatherer::finished, this, &QgsPalettedRendererWidget::gathererThreadFinished ); mClassifyButton->setText( tr( "Calculating…" ) ); mClassifyButton->setEnabled( false ); mGatherer->start(); } } void QgsPalettedRendererWidget::loadFromLayer() { //read default palette settings from layer QgsRasterDataProvider *provider = mRasterLayer->dataProvider(); if ( provider ) { QList<QgsColorRampShader::ColorRampItem> table = provider->colorTable( mBandComboBox->currentBand() ); if ( !table.isEmpty() ) { QgsPalettedRasterRenderer::ClassData classes = QgsPalettedRasterRenderer::colorTableToClassData( provider->colorTable( mBandComboBox->currentBand() ) ); mModel->setClassData( classes ); emit widgetChanged(); } } } void QgsPalettedRendererWidget::bandChanged( int band ) { if ( band == mBand ) return; bool deleteExisting = false; if ( !mModel->classData().isEmpty() ) { int res = QMessageBox::question( this, tr( "Delete Classification" ), tr( "The classification band was changed from %1 to %2.\n" "Should the existing classes be deleted?" ).arg( mBand ).arg( band ), QMessageBox::Yes | QMessageBox::No ); deleteExisting = ( res == QMessageBox::Yes ); } mBand = band; mModel->blockSignals( true ); if ( deleteExisting ) mModel->deleteAll(); mModel->blockSignals( false ); emit widgetChanged(); } void QgsPalettedRendererWidget::gatheredClasses() { if ( !mGatherer || mGatherer->wasCanceled() ) return; mModel->setClassData( mGatherer->classes() ); emit widgetChanged(); } void QgsPalettedRendererWidget::gathererThreadFinished() { mGatherer->deleteLater(); mGatherer = nullptr; mClassifyButton->setText( tr( "Classify" ) ); mClassifyButton->setEnabled( true ); mCalculatingProgressBar->hide(); mCancelButton->hide(); } void QgsPalettedRendererWidget::layerWillBeRemoved( QgsMapLayer *layer ) { if ( mGatherer && mRasterLayer == layer ) { mGatherer->stop(); mGatherer->wait(); } } // // QgsPalettedRendererModel // ///@cond PRIVATE QgsPalettedRendererModel::QgsPalettedRendererModel( QObject *parent ) : QAbstractItemModel( parent ) { } void QgsPalettedRendererModel::setClassData( const QgsPalettedRasterRenderer::ClassData &data ) { beginResetModel(); mData = data; endResetModel(); } QModelIndex QgsPalettedRendererModel::index( int row, int column, const QModelIndex &parent ) const { if ( column < 0 || column >= columnCount() ) { //column out of bounds return QModelIndex(); } if ( !parent.isValid() && row >= 0 && row < mData.size() ) { //return an index for the item at this position return createIndex( row, column ); } //only top level supported return QModelIndex(); } QModelIndex QgsPalettedRendererModel::parent( const QModelIndex &index ) const { Q_UNUSED( index ); //all items are top level return QModelIndex(); } int QgsPalettedRendererModel::columnCount( const QModelIndex &parent ) const { if ( parent.isValid() ) return 0; return 3; } int QgsPalettedRendererModel::rowCount( const QModelIndex &parent ) const { if ( parent.isValid() ) return 0; return mData.count(); } QVariant QgsPalettedRendererModel::data( const QModelIndex &index, int role ) const { if ( !index.isValid() ) return QVariant(); switch ( role ) { case Qt::DisplayRole: case Qt::EditRole: { switch ( index.column() ) { case ValueColumn: return mData.at( index.row() ).value; case ColorColumn: return mData.at( index.row() ).color; case LabelColumn: return mData.at( index.row() ).label; } } default: break; } return QVariant(); } QVariant QgsPalettedRendererModel::headerData( int section, Qt::Orientation orientation, int role ) const { switch ( orientation ) { case Qt::Vertical: return QVariant(); case Qt::Horizontal: { switch ( role ) { case Qt::DisplayRole: { switch ( section ) { case ValueColumn: return tr( "Value" ); case ColorColumn: return tr( "Color" ); case LabelColumn: return tr( "Label" ); } } } break; } default: return QAbstractItemModel::headerData( section, orientation, role ); } return QAbstractItemModel::headerData( section, orientation, role ); } bool QgsPalettedRendererModel::setData( const QModelIndex &index, const QVariant &value, int ) { if ( !index.isValid() ) return false; if ( index.row() >= mData.length() ) return false; switch ( index.column() ) { case ValueColumn: { bool ok = false; int newValue = value.toInt( &ok ); if ( !ok ) return false; mData[ index.row() ].value = newValue; emit dataChanged( index, index ); emit classesChanged(); return true; } case ColorColumn: { mData[ index.row() ].color = value.value<QColor>(); emit dataChanged( index, index ); emit classesChanged(); return true; } case LabelColumn: { mData[ index.row() ].label = value.toString(); emit dataChanged( index, index ); emit classesChanged(); return true; } } return false; } Qt::ItemFlags QgsPalettedRendererModel::flags( const QModelIndex &index ) const { if ( !index.isValid() ) return QAbstractItemModel::flags( index ) | Qt::ItemIsDropEnabled; Qt::ItemFlags f = QAbstractItemModel::flags( index ); switch ( index.column() ) { case ValueColumn: case LabelColumn: case ColorColumn: f = f | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsDragEnabled; break; } return f | Qt::ItemIsEnabled | Qt::ItemIsSelectable;; } bool QgsPalettedRendererModel::removeRows( int row, int count, const QModelIndex &parent ) { if ( row < 0 || row >= mData.count() ) return false; if ( parent.isValid() ) return false; for ( int i = row + count - 1; i >= row; --i ) { beginRemoveRows( parent, i, i ); mData.removeAt( i ); endRemoveRows(); } emit classesChanged(); return true; } bool QgsPalettedRendererModel::insertRows( int row, int count, const QModelIndex & ) { QgsPalettedRasterRenderer::ClassData::const_iterator cIt = mData.constBegin(); int currentMaxValue = -std::numeric_limits<int>::max(); for ( ; cIt != mData.constEnd(); ++cIt ) { int value = cIt->value; currentMaxValue = std::max( value, currentMaxValue ); } int nextValue = std::max( 0, currentMaxValue + 1 ); beginInsertRows( QModelIndex(), row, row + count - 1 ); for ( int i = row; i < row + count; ++i, ++nextValue ) { mData.insert( i, QgsPalettedRasterRenderer::Class( nextValue, QColor( 200, 200, 200 ), QString::number( nextValue ) ) ); } endInsertRows(); emit classesChanged(); return true; } Qt::DropActions QgsPalettedRendererModel::supportedDropActions() const { return Qt::MoveAction; } QStringList QgsPalettedRendererModel::mimeTypes() const { QStringList types; types << QStringLiteral( "application/x-qgspalettedrenderermodel" ); return types; } QMimeData *QgsPalettedRendererModel::mimeData( const QModelIndexList &indexes ) const { QMimeData *mimeData = new QMimeData(); QByteArray encodedData; QDataStream stream( &encodedData, QIODevice::WriteOnly ); // Create list of rows const auto constIndexes = indexes; for ( const QModelIndex &index : constIndexes ) { if ( !index.isValid() || index.column() != 0 ) continue; stream << index.row(); } mimeData->setData( QStringLiteral( "application/x-qgspalettedrenderermodel" ), encodedData ); return mimeData; } bool QgsPalettedRendererModel::dropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex & ) { Q_UNUSED( column ); if ( action != Qt::MoveAction ) return true; if ( !data->hasFormat( QStringLiteral( "application/x-qgspalettedrenderermodel" ) ) ) return false; QByteArray encodedData = data->data( QStringLiteral( "application/x-qgspalettedrenderermodel" ) ); QDataStream stream( &encodedData, QIODevice::ReadOnly ); QVector<int> rows; while ( !stream.atEnd() ) { int r; stream >> r; rows.append( r ); } QgsPalettedRasterRenderer::ClassData newData; for ( int i = 0; i < rows.count(); ++i ) newData << mData.at( rows.at( i ) ); if ( row < 0 ) row = mData.count(); beginInsertRows( QModelIndex(), row, row + rows.count() - 1 ); for ( int i = 0; i < rows.count(); ++i ) mData.insert( row + i, newData.at( i ) ); endInsertRows(); emit classesChanged(); return true; } QModelIndex QgsPalettedRendererModel::addEntry( const QColor &color ) { insertRow( rowCount() ); QModelIndex newRow = index( mData.count() - 1, 1 ); setData( newRow, color ); return newRow; } void QgsPalettedRendererModel::deleteAll() { beginResetModel(); mData.clear(); endResetModel(); emit classesChanged(); } void QgsPalettedRendererClassGatherer::run() { mWasCanceled = false; // allow responsive cancellation mFeedback = new QgsRasterBlockFeedback(); connect( mFeedback, &QgsRasterBlockFeedback::progressChanged, this, &QgsPalettedRendererClassGatherer::progressChanged ); QgsPalettedRasterRenderer::ClassData newClasses = QgsPalettedRasterRenderer::classDataFromRaster( mLayer->dataProvider(), mBandNumber, mRamp.get(), mFeedback ); // combine existing classes with new classes QgsPalettedRasterRenderer::ClassData::iterator classIt = newClasses.begin(); for ( ; classIt != newClasses.end(); ++classIt ) { // check if existing classes contains this same class for ( const QgsPalettedRasterRenderer::Class &existingClass : qgis::as_const( mClasses ) ) { if ( existingClass.value == classIt->value ) { classIt->color = existingClass.color; classIt->label = existingClass.label; break; } } } mClasses = newClasses; // be overly cautious - it's *possible* stop() might be called between deleting mFeedback and nulling it mFeedbackMutex.lock(); delete mFeedback; mFeedback = nullptr; mFeedbackMutex.unlock(); emit collectedClasses(); } ///@endcond PRIVATE
KonstantinosKr/vega
delta/core/io/write.h
/* * write.h * * Created on: 2 Apr 2017 * Author: konstantinos */ #ifndef DELTA_IO_WRITE_H_ #define DELTA_IO_WRITE_H_ #include <vector> #include <string> #include "stdio.h" #include "string.h" #include "../../core/data/ParticleRecord.h" #include "../../geometry/structure/Mesh.h" #include "../../world/structure/Object.h" #include <vtkSmartPointer.h> #include <vtkTetra.h> #include <vtkLine.h> #include <vtkDataArray.h> #include <vtkDoubleArray.h> #include <vtkIntArray.h> #include <vtkMath.h> #include <vtkCellArray.h> #include <vtkXMLUnstructuredGridReader.h> #include <vtkDataSetMapper.h> #include <vtkXMLUnstructuredGridWriter.h> #include <vtkUnstructuredGrid.h> #include <vtkPointData.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkXMLPolyDataReader.h> #include <vtkPolyDataNormals.h> #include <vtkFloatArray.h> #include <vtkMath.h> #include <string> namespace delta { namespace core { namespace io { void writeGeometryToVTKVTK( std::string path, int step, std::vector<delta::core::data::ParticleRecord>& geometries); void writeGridGeometryToVTKVTK( std::string path, int step, std::vector<std::array<iREAL, 6>> boundary); void writeGeometryToVTK( std::string path, int step, std::vector<delta::core::data::ParticleRecord>& geometries); void writeGridGeometryToVTK( std::string path, int step, std::vector<std::array<iREAL, 6>> boundary); void writeScenarioSpecification(std::string fileName); } } } #endif /* DELTA_CORE_WRITE_H_ */
mincloud1501/Python
Pydeck/node_modules/@deck.gl/json/dist/esm/helpers/convert-functions.js
<filename>Pydeck/node_modules/@deck.gl/json/dist/esm/helpers/convert-functions.js import parseExpressionString from './parse-expression-string'; import { getPropTypes, isFunctionProp } from './deck-prop-types'; export default function convertFunctions(Class, props, configuration) { var propTypes = getPropTypes(Class); return convertFunctionsUsingPropTypes(props, propTypes, configuration); } function convertFunctionsUsingPropTypes(props, propTypes, configuration) { var replacedProps = {}; for (var propName in props) { var propValue = props[propName]; var isFunction = isFunctionProp(propTypes, propName); if (isFunction && typeof propValue === 'string') { var isAccessor = true; propValue = parseExpressionString(propValue, configuration, isAccessor); } if (propValue) { replacedProps[propName] = propValue; } } return replacedProps; } //# sourceMappingURL=convert-functions.js.map
rht/ripple-client
compat/ie/ws/ws-config.js
WEB_SOCKET_SWF_LOCATION = "compat/ie/ws/WebSocketMain.swf";
zthang/code2vec_treelstm
raw_dataset/59908674@setSize@OK.java
<filename>raw_dataset/59908674@setSize@OK.java public int setSize(int i) { return setSize[findSet(i)]; }
christophfranke/continuous-integration-tools
py/cleanup.py
from modules import engine from modules import out @engine.prepare_and_clean def execute(): out.log("cleaning up the local tmp directory") engine.clean_local_tmp_dir() out.log("cleaning up the remote tmp directory") engine.clean_remote_tmp_dir() if engine.ENABLE_BUILD_SYSTEM: out.log("cleaning up local build directory") engine.clean_build_dir() def help(): out.log("deletes all files in the local and remote tmp directories.", 'help')
HarryZhang1224/BSBolt
bsbolt/Matrix/SiteAggregator.py
import multiprocessing as mp from typing import Dict, List from bsbolt.Utils.CGmapIterator import OpenCGmap from bsbolt.Utils.UtilityFunctions import propagate_error import numpy as np from tqdm import tqdm class CGmapSiteAggregator: """Pull consensus methylation sites into a methylation matrix Keyword Arguments: cgmap_files (list): file paths min_site_coverage (int): minimum site coverage for a valid methylation call verbose (bool): tqdm output threads (int): threads available for aggregation """ def __init__(self, cgmap_files: List[str] = None, min_site_coverage: int = 1, verbose: bool = False, threads: int = 8, count_matrix: bool = False): self.cgmap_files = cgmap_files self.min_site_coverage = min_site_coverage self.verbose = verbose self.threads = threads self.count_matrix = count_matrix def assemble_matrix(self, matrix_sites: List[str] = None): # initialize collection_pool and manager queue matrix_pool = mp.Pool(processes=self.threads) manager = mp.Manager() matrix_queue = manager.Queue(maxsize=10) completed_samples = manager.list() # initialize empty array of zeros, fill with null values for safety for count, cgmap in enumerate(self.cgmap_files): matrix_pool.apply_async(self.collect_methylation_sites, kwds=dict(sample_pos=count, cgmap_path=cgmap, return_queue=matrix_queue, completed_samples=completed_samples, matrix_sites=matrix_sites), error_callback=propagate_error) matrix_pool.close() # if verbose initialize tqdm progress bar update_count = 0 pbar = tqdm(total=len(self.cgmap_files), desc='Setting Methylation Sites') if self.verbose else None meth_matrix, matrix_order = [], [] while True: if len(completed_samples) == len(self.cgmap_files) and matrix_queue.empty(): break sample_pos, sample_values = matrix_queue.get(block=True) matrix_order.append(sample_pos) if len(sample_values.shape) > 1: meth_matrix.append(sample_values[:, 0]) meth_matrix.append(sample_values[:, 1]) else: meth_matrix.append(sample_values) if pbar: update_number = len(completed_samples) - update_count pbar.update(update_number) update_count = len(completed_samples) if pbar: update_number = len(completed_samples) - update_count pbar.update(update_number) pbar.close() return np.array(meth_matrix).T, matrix_order def collect_methylation_sites(self, sample_pos: int = None, cgmap_path: str = None, return_queue: mp.Queue = None, completed_samples: List = None, matrix_sites: Dict = None): # initialize an array for all sites and fill with null values matrix_key = {site: count for count, site in enumerate(matrix_sites)} if self.count_matrix: sample_array = np.zeros((len(matrix_sites), 2)) else: sample_array = np.zeros((len(matrix_sites))) sample_array.fill(np.nan) for line_info in OpenCGmap(cgmap_path): try: line_info[7] except IndexError: break else: if int(line_info[7]) >= self.min_site_coverage: site_label = f'{line_info[0]}:{line_info[2]}' if site_label in matrix_key: if self.count_matrix: sample_array[matrix_key[site_label], :] = np.array((int(line_info[6]), int(line_info[7]))) else: sample_array[matrix_key[site_label]] = float(line_info[5]) return_queue.put((sample_pos, sample_array), block=True) completed_samples.append('done')
jbakosi/seacas
docs/ioss_html/Ioex__DatabaseIO_8C.js
var Ioex__DatabaseIO_8C = [ [ "check_attribute_index_order", "Ioex__DatabaseIO_8C.html#a9a39a5e9379a4a90041c1e408f4f95cd", null ], [ "check_variable_consistency", "Ioex__DatabaseIO_8C.html#a5f1d0ce0f60ab0c62e367d59dc8d9ab4", null ], [ "generate_block_truth_table", "Ioex__DatabaseIO_8C.html#a0feccf323106457fbeb37d155ee24dc7", null ], [ "generate_block_truth_table", "Ioex__DatabaseIO_8C.html#a4fb1d81d83857a5b936fedbdb6ad7f82", null ], [ "write_attribute_names", "Ioex__DatabaseIO_8C.html#a49a8fb19587d51f9b0b5d713d17f5ea8", null ], [ "complex_suffix", "Ioex__DatabaseIO_8C.html#a756b4cdcd8565306fc1a6c20bd5ffef2", null ], [ "max_line_length", "Ioex__DatabaseIO_8C.html#aa46c0ef881bbcda9aa7b23ad9441e812", null ] ];
jblowe/services
services/common/src/main/java/org/collectionspace/services/common/storage/PreparedStatementBuilder.java
<filename>services/common/src/main/java/org/collectionspace/services/common/storage/PreparedStatementBuilder.java /** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * http://www.collectionspace.org * http://wiki.collectionspace.org * Copyright © 2009-2013 The Regents of the University of California * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * 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. */ /** * PreparedStatementBuilder * * Simple workaround for the inability to create a JDBC * PreparedStatement without having a current Connection * * See http://stackoverflow.com/a/7127189 * and http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/ */ package org.collectionspace.services.common.storage; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class PreparedStatementBuilder { private String sql; public PreparedStatementBuilder(final String sql) { this.sql = sql; } /** * A 'virtual' method to be overridden, in which to declare setup directives * to be applied to a PreparedStatement; for instance, to add values to * replaceable parameters or otherwise modify the statement's behavior. * * (The PreparedStatement will not yet exist at the time this method is overridden.) * * @param preparedStatement a JDBC PreparedStatement. * @throws SQLException */ protected void preparePrepared(final PreparedStatement preparedStatement) throws SQLException { } /** * Build a PreparedStatement by obtaining it from a JDBC Connection, * then applying setup directives before returning it. * * @param conn a JDBC connection * @return a JDBC PreparedStatement, with setup directives, if any, applied. * @throws SQLException */ public PreparedStatement build(final Connection conn) throws SQLException { final PreparedStatement returnable = conn.prepareStatement(sql); preparePrepared(returnable); return returnable; } }
AccelByte/accelbyte-python-sdk
accelbyte_py_sdk/api/achievement/wrappers/__init__.py
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template file: justice_py_sdk_codegen/__main__.py """Auto-generated package that contains models used by the justice-achievement-service.""" __version__ = "" __author__ = "AccelByte" __email__ = "<EMAIL>" # pylint: disable=line-too-long from ._achievements import admin_create_new_achievement from ._achievements import admin_create_new_achievement_async from ._achievements import admin_delete_achievement from ._achievements import admin_delete_achievement_async from ._achievements import admin_get_achievement from ._achievements import admin_get_achievement_async from ._achievements import admin_list_achievements from ._achievements import admin_list_achievements_async from ._achievements import admin_list_user_achievements from ._achievements import admin_list_user_achievements_async from ._achievements import admin_unlock_achievement from ._achievements import admin_unlock_achievement_async from ._achievements import admin_update_achievement from ._achievements import admin_update_achievement_async from ._achievements import admin_update_achievement_list_order from ._achievements import admin_update_achievement_list_order_async from ._achievements import export_achievements from ._achievements import export_achievements_async from ._achievements import import_achievements from ._achievements import import_achievements_async from ._achievements import public_get_achievement from ._achievements import public_get_achievement_async from ._achievements import public_list_achievements from ._achievements import public_list_achievements_async from ._achievements import public_list_user_achievements from ._achievements import public_list_user_achievements_async from ._achievements import public_unlock_achievement from ._achievements import public_unlock_achievement_async
ishtiaqahmad/dotwebstack-framework
backend/rdf4j/src/main/java/org/dotwebstack/framework/backend/rdf4j/query/helper/VerticeHelper.java
<reponame>ishtiaqahmad/dotwebstack-framework package org.dotwebstack.framework.backend.rdf4j.query.helper; import org.dotwebstack.framework.backend.rdf4j.query.model.Vertice; import org.dotwebstack.framework.backend.rdf4j.shacl.NodeShape; import org.eclipse.rdf4j.sparqlbuilder.core.Variable; public class VerticeHelper { private VerticeHelper() {} public static Vertice buildVertice(Variable subject, NodeShape nodeShape) { return Vertice.builder() .nodeShape(nodeShape) .subject(subject) .build(); } }
daimaren/TikTok
sharedcpp/audio_effect/libaudio_effect/audio_effect/audio_info.cpp
<gh_stars>1-10 #include "./audio_info.h" #define LOG_TAG "AudioInfo" AudioInfo::AudioInfo(){ } AudioInfo::AudioInfo(int channels, int audioSampleRate, int recordedTimeMills, int totalTimeMills, float accompanyAGCVolume, float audioAGCVolume, float accompanyPitch, int pitchShiftLevel) { this->channels = channels; this->audioSampleRate = audioSampleRate; this->recordedTimeMills = recordedTimeMills; this->totalTimeMills = totalTimeMills; this->accompanyAGCVolume = accompanyAGCVolume; this->audioAGCVolume = audioAGCVolume; this->accompanyPitch = accompanyPitch; this->pitchShiftLevel = pitchShiftLevel; } AudioInfo::~AudioInfo(){ }
wuweiweiwu/babel
packages/babel-parser/test/fixtures/experimental/class-private-properties/failure-numeric-literal/input.js
class Foo { #2 = y }
ahmedsamir9/medico
app/src/main/java/com/example/medicalapp/API/NewsModel/ArticlesItem.java
<reponame>ahmedsamir9/medico package com.example.medicalapp.API.NewsModel; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import com.google.gson.annotations.SerializedName; @Entity public class ArticlesItem{ @PrimaryKey(autoGenerate = true) int id_db; @ColumnInfo @SerializedName("publishedAt") private String publishedAt; @ColumnInfo @SerializedName("author") private String author; @ColumnInfo @SerializedName("urlToImage") private String urlToImage; @ColumnInfo @SerializedName("description") private String description; @Ignore @SerializedName("source") private Source source; @ColumnInfo @SerializedName("title") private String title; @ColumnInfo @SerializedName("url") private String url; @ColumnInfo @SerializedName("content") private String content; public void setPublishedAt(String publishedAt){ this.publishedAt = publishedAt; } public String getPublishedAt(){ return publishedAt; } public void setAuthor(String author){ this.author = author; } public String getAuthor(){ return author; } public void setUrlToImage(String urlToImage){ this.urlToImage = urlToImage; } public String getUrlToImage(){ return urlToImage; } public void setDescription(String description){ this.description = description; } public String getDescription(){ return description; } public void setSource(Source source){ this.source = source; } public Source getSource(){ return source; } public void setTitle(String title){ this.title = title; } public String getTitle(){ return title; } public void setUrl(String url){ this.url = url; } public String getUrl(){ return url; } public void setContent(String content){ this.content = content; } public String getContent(){ return content; } @Ignore @Override public String toString(){ return "ArticlesItem{" + "publishedAt = '" + publishedAt + '\'' + ",author = '" + author + '\'' + ",urlToImage = '" + urlToImage + '\'' + ",description = '" + description + '\'' + ",source = '" + source + '\'' + ",title = '" + title + '\'' + ",url = '" + url + '\'' + ",content = '" + content + '\'' + "}"; } public ArticlesItem() { } }
failled/Orekit
src/test/java/org/orekit/estimation/leastsquares/DSSTOrbitDeterminationTest.java
<reponame>failled/Orekit /* Copyright 2002-2021 CS GROUP * Licensed to CS GROUP (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.estimation.leastsquares; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.hipparchus.exception.LocalizedCoreFormats; import org.hipparchus.geometry.euclidean.threed.Vector3D; import org.hipparchus.util.FastMath; import org.junit.Assert; import org.junit.Test; import org.orekit.KeyValueFileParser; import org.orekit.Utils; import org.orekit.attitudes.AttitudeProvider; import org.orekit.bodies.CelestialBody; import org.orekit.bodies.OneAxisEllipsoid; import org.orekit.errors.OrekitException; import org.orekit.estimation.common.AbstractOrbitDetermination; import org.orekit.estimation.common.ParameterKey; import org.orekit.estimation.common.ResultBatchLeastSquares; import org.orekit.forces.drag.DragSensitive; import org.orekit.forces.gravity.potential.GravityFieldFactory; import org.orekit.forces.gravity.potential.ICGEMFormatReader; import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider; import org.orekit.forces.radiation.RadiationSensitive; import org.orekit.models.earth.atmosphere.Atmosphere; import org.orekit.orbits.EquinoctialOrbit; import org.orekit.orbits.Orbit; import org.orekit.orbits.OrbitType; import org.orekit.propagation.PropagationType; import org.orekit.propagation.conversion.DSSTPropagatorBuilder; import org.orekit.propagation.conversion.ODEIntegratorBuilder; import org.orekit.propagation.semianalytical.dsst.forces.DSSTAtmosphericDrag; import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel; import org.orekit.propagation.semianalytical.dsst.forces.DSSTSolarRadiationPressure; import org.orekit.propagation.semianalytical.dsst.forces.DSSTTesseral; import org.orekit.propagation.semianalytical.dsst.forces.DSSTThirdBody; import org.orekit.propagation.semianalytical.dsst.forces.DSSTZonal; import org.orekit.utils.Constants; import org.orekit.utils.IERSConventions; import org.orekit.utils.ParameterDriver; public class DSSTOrbitDeterminationTest extends AbstractOrbitDetermination<DSSTPropagatorBuilder> { /** Gravity field. */ private UnnormalizedSphericalHarmonicsProvider gravityField; /** Propagation type (mean or mean + osculating). */ private PropagationType propagationType; /** Initial state type (defined using mean or osculating elements). */ private PropagationType stateType; /** {@inheritDoc} */ @Override protected void createGravityField(final KeyValueFileParser<ParameterKey> parser) throws NoSuchElementException { final int degree = parser.getInt(ParameterKey.CENTRAL_BODY_DEGREE); final int order = FastMath.min(degree, parser.getInt(ParameterKey.CENTRAL_BODY_ORDER)); gravityField = GravityFieldFactory.getUnnormalizedProvider(degree, order); } /** {@inheritDoc} */ @Override protected double getMu() { return gravityField.getMu(); } /** {@inheritDoc} */ @Override protected DSSTPropagatorBuilder createPropagatorBuilder(final Orbit referenceOrbit, final ODEIntegratorBuilder builder, final double positionScale) { final EquinoctialOrbit equiOrbit = (EquinoctialOrbit) OrbitType.EQUINOCTIAL.convertType(referenceOrbit); return new DSSTPropagatorBuilder(equiOrbit, builder, positionScale, propagationType, stateType); } /** {@inheritDoc} */ @Override protected void setMass(final DSSTPropagatorBuilder propagatorBuilder, final double mass) { propagatorBuilder.setMass(mass); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setGravity(final DSSTPropagatorBuilder propagatorBuilder, final OneAxisEllipsoid body) { // tesseral terms final DSSTForceModel tesseral = new DSSTTesseral(body.getBodyFrame(), Constants.WGS84_EARTH_ANGULAR_VELOCITY, gravityField, gravityField.getMaxDegree(), gravityField.getMaxOrder(), 4, 12, gravityField.getMaxDegree(), gravityField.getMaxOrder(), 4); propagatorBuilder.addForceModel(tesseral); // zonal terms final DSSTForceModel zonal = new DSSTZonal(gravityField, gravityField.getMaxDegree(), 4, 2 * gravityField.getMaxDegree() + 1); propagatorBuilder.addForceModel(zonal); // gather all drivers final List<ParameterDriver> drivers = new ArrayList<>(); drivers.addAll(tesseral.getParametersDrivers()); drivers.addAll(zonal.getParametersDrivers()); return drivers; } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setOceanTides(final DSSTPropagatorBuilder propagatorBuilder, final IERSConventions conventions, final OneAxisEllipsoid body, final int degree, final int order) { throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE, "Ocean tides not implemented in DSST"); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setSolidTides(final DSSTPropagatorBuilder propagatorBuilder, final IERSConventions conventions, final OneAxisEllipsoid body, final CelestialBody[] solidTidesBodies) { throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE, "Solid tides not implemented in DSST"); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setThirdBody(final DSSTPropagatorBuilder propagatorBuilder, final CelestialBody thirdBody) { final DSSTForceModel thirdBodyModel = new DSSTThirdBody(thirdBody, gravityField.getMu()); propagatorBuilder.addForceModel(thirdBodyModel); return thirdBodyModel.getParametersDrivers(); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setDrag(final DSSTPropagatorBuilder propagatorBuilder, final Atmosphere atmosphere, final DragSensitive spacecraft) { final DSSTForceModel dragModel = new DSSTAtmosphericDrag(atmosphere, spacecraft, gravityField.getMu()); propagatorBuilder.addForceModel(dragModel); return dragModel.getParametersDrivers(); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setSolarRadiationPressure(final DSSTPropagatorBuilder propagatorBuilder, final CelestialBody sun, final double equatorialRadius, final RadiationSensitive spacecraft) { final DSSTForceModel srpModel = new DSSTSolarRadiationPressure(sun, equatorialRadius, spacecraft, gravityField.getMu()); propagatorBuilder.addForceModel(srpModel); return srpModel.getParametersDrivers(); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setAlbedoInfrared(final DSSTPropagatorBuilder propagatorBuilder, final CelestialBody sun, final double equatorialRadius, final double angularResolution, final RadiationSensitive spacecraft) { throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE, "Albedo and infrared not implemented in DSST"); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setRelativity(final DSSTPropagatorBuilder propagatorBuilder) { throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE, "Albedo and infrared not implemented in DSST"); } /** {@inheritDoc} */ @Override protected List<ParameterDriver> setPolynomialAcceleration(final DSSTPropagatorBuilder propagatorBuilder, final String name, final Vector3D direction, final int degree) { throw new OrekitException(LocalizedCoreFormats.SIMPLE_MESSAGE, "Polynomial acceleration not implemented in DSST"); } /** {@inheritDoc} */ @Override protected void setAttitudeProvider(final DSSTPropagatorBuilder propagatorBuilder, final AttitudeProvider attitudeProvider) { propagatorBuilder.setAttitudeProvider(attitudeProvider); } /** * Lageos 2 orbit determination test using laser data. * * This test uses both mean and osculating elements to perform the orbit determination. * It is possible to consider only mean elements by changing propagationType and * stateType keys. */ @Test public void testLageos2() throws URISyntaxException, IllegalArgumentException, IOException, OrekitException, ParseException { // input in resources directory final String inputPath = DSSTOrbitDeterminationTest.class.getClassLoader().getResource("orbit-determination/Lageos2/dsst_od_test_Lageos2.in").toURI().getPath(); final File input = new File(inputPath); // configure Orekit data access Utils.setDataRoot("orbit-determination/february-2016:potential/icgem-format"); GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("eigen-6s-truncated", true)); // configure propagation and initial state types propagationType = PropagationType.OSCULATING; stateType = PropagationType.OSCULATING; //orbit determination run. ResultBatchLeastSquares odLageos2 = runBLS(input, false); //test //definition of the accuracy for the test final double distanceAccuracy = 76.46; final double velocityAccuracy = 1.58e-1; //test on the convergence final int numberOfIte = 6; final int numberOfEval = 6; Assert.assertEquals(numberOfIte, odLageos2.getNumberOfIteration()); Assert.assertEquals(numberOfEval, odLageos2.getNumberOfEvaluation()); //test on the estimated position and velocity final Vector3D estimatedPos = odLageos2.getEstimatedPV().getPosition(); final Vector3D estimatedVel = odLageos2.getEstimatedPV().getVelocity(); // Ref position from "lageos2_cpf_160212_5441.jax" final Vector3D refPos = new Vector3D(-2551060.861, 9748629.197, -6528045.767); final Vector3D refVel = new Vector3D(-4595.833, 1029.893, 3382.441); Assert.assertEquals(0.0, Vector3D.distance(refPos, estimatedPos), distanceAccuracy); Assert.assertEquals(0.0, Vector3D.distance(refVel, estimatedVel), velocityAccuracy); //test on statistic for the range residuals final long nbRange = 95; final double[] RefStatRange = { -29.016, 59.104, 0.0, 14.968 }; Assert.assertEquals(nbRange, odLageos2.getRangeStat().getN()); Assert.assertEquals(RefStatRange[0], odLageos2.getRangeStat().getMin(), 1.0e-3); Assert.assertEquals(RefStatRange[1], odLageos2.getRangeStat().getMax(), 1.0e-3); Assert.assertEquals(RefStatRange[2], odLageos2.getRangeStat().getMean(), 1.0e-3); Assert.assertEquals(RefStatRange[3], odLageos2.getRangeStat().getStandardDeviation(), 1.0e-3); } /** * GNSS orbit determination test. * * This test uses both mean and osculating elements to perform the orbit determination. * It is possible to consider only mean elements by changing propagationType and * stateType keys. * * Using only mean elements, results are: * ΔP = 59 meters * ΔV = 0.23 meters per second * * nb iterations = 2 * nb evaluations = 3 * * min residual = -83.945 meters * max residual = 59.365 meters * mean residual = 0.23 meters * RMS = 20.857 meters */ @Test public void testGNSS() throws URISyntaxException, IllegalArgumentException, IOException, OrekitException, ParseException { // input in resources directory final String inputPath = DSSTOrbitDeterminationTest.class.getClassLoader().getResource("orbit-determination/GNSS/dsst_od_test_GPS07.in").toURI().getPath(); final File input = new File(inputPath); // configure Orekit data access Utils.setDataRoot("orbit-determination/february-2016:potential/icgem-format"); GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("eigen-6s-truncated", true)); // configure propagation and initial state types propagationType = PropagationType.OSCULATING; stateType = PropagationType.OSCULATING; //orbit determination run. ResultBatchLeastSquares odGNSS = runBLS(input, false); //test //definition of the accuracy for the test final double distanceAccuracy = 6.95; final double velocityAccuracy = 2.46e-3; //test on the convergence final int numberOfIte = 3; final int numberOfEval = 4; Assert.assertEquals(numberOfIte, odGNSS.getNumberOfIteration()); Assert.assertEquals(numberOfEval, odGNSS.getNumberOfEvaluation()); //test on the estimated position and velocity (reference from IGS-MGEX file com18836.sp3) final Vector3D estimatedPos = odGNSS.getEstimatedPV().getPosition(); final Vector3D estimatedVel = odGNSS.getEstimatedPV().getVelocity(); final Vector3D refPos = new Vector3D(-2747606.680868164, 22572091.30648564, 13522761.402325712); final Vector3D refVel = new Vector3D(-2729.5151218788005, 1142.6629459030657, -2523.9055974487947); Assert.assertEquals(0.0, Vector3D.distance(refPos, estimatedPos), distanceAccuracy); Assert.assertEquals(0.0, Vector3D.distance(refVel, estimatedVel), velocityAccuracy); //test on statistic for the range residuals final long nbRange = 4009; final double[] RefStatRange = { -3.497, 2.594, 0.0, 0.837 }; Assert.assertEquals(nbRange, odGNSS.getRangeStat().getN()); Assert.assertEquals(RefStatRange[0], odGNSS.getRangeStat().getMin(), 1.0e-3); Assert.assertEquals(RefStatRange[1], odGNSS.getRangeStat().getMax(), 1.0e-3); Assert.assertEquals(RefStatRange[2], odGNSS.getRangeStat().getMean(), 1.0e-3); Assert.assertEquals(RefStatRange[3], odGNSS.getRangeStat().getStandardDeviation(), 1.0e-3); } }
rahlk/MOOSE
src/Models/Models/pom3/pom3.py
<filename>src/Models/Models/pom3/pom3.py from pom3_teams import * from pom3_requirements import * import random """############################################################################## ### -@author: <NAME> ### -@note: POM3 Simulation Module ### -@note: This work done in affiliation with the West Virginia University ### -@contact: <EMAIL> ### -@copyright: This work is made for academic research. Do not edit without ### -@copyright: citing POM3 as a reference. ##############################################################################""" class pom3_decisions: def __init__(p3d, X): p3d.culture = X[0] p3d.criticality = X[1] p3d.criticality_modifier = X[2] p3d.initial_known = X[3] p3d.interdependency = X[4] p3d.dynamism = X[5] p3d.size = int(X[6]) p3d.plan = int(X[7]) p3d.team_size = X[8] class pom3: def __init__(p3): pass def simulate(p3, inputs): # # # # # # # # # # # # 0) Initialization # # # # # # # # # # # # POM3_DECISIONS = pom3_decisions(inputs) numberOfShuffles = 6 # # # # # # # # # # # # # # # # 1) Generate Requirements # # # # # # # # # # # # # # # # POM3_REQUIREMENTS = pom3_requirements(POM3_DECISIONS) # # # # # # # # # # # # 2) Generate Teams # # # # # # # # # # # # POM3_TEAMS = pom3_teams(POM3_REQUIREMENTS, POM3_DECISIONS) # # # # # # # # # 3) Shuffle # # # # # # # # # for shufflingIteration in range(numberOfShuffles): for team in POM3_TEAMS.teams: team.updateBudget(numberOfShuffles) team.collectAvailableTasks(POM3_REQUIREMENTS) team.applySortingStrategy() team.executeAvailableTasks() team.discoverNewTasks() team.updateTasks() # # # # # # # # # # # # # # 4) Objective Scoring # # # # # # # # # # # # # # cost_sum, value_sum, god_cost_sum, god_value_sum, completion_sum, available_sum, total_tasks = 0.0, 0.0, 0.0, 0.0, 0, 0, 0 for team in POM3_TEAMS.teams: cost_sum += team.cost_total value_sum += team.value_total available_sum += team.numAvailableTasks completion_sum += team.numCompletedTasks for task in team.tasks: if task.val.visible: total_tasks += 1 for task in team.tasks: if task.val.done: god_cost_sum += task.val.cost god_value_sum += task.val.value if cost_sum == 0: our_frontier = 0.0 else: our_frontier = value_sum / cost_sum if god_cost_sum == 0: god_frontier = 0.0 else: god_frontier = god_value_sum / god_cost_sum if god_frontier == 0.0: score = 0.0 else: score = our_frontier / god_frontier # print # "cost",cost_sum,"value",value_sum,"completion",completion_sum,"avaiable",available_sum,"tot # tasks",total_tasks if completion_sum == 0: cost = 0 else: cost = cost_sum / completion_sum if available_sum == 0: idle = 0 else: idle = 1 - completion_sum / float(available_sum) if total_tasks == 0: completion = 0 else: completion = completion_sum / float(total_tasks) # return [cost, score, completion, idle] return [cost, completion, idle] if __name__ == '__main__': # Test Code p3 = pom3() print p3.simulate([0.20, 1.26, 8, 0.95, 100, 10, 2, 5, 20])
Zhang-Qing-Yun/mini-im
im-client/src/main/java/com/qingyun/im/client/task/MsgTimeoutTask.java
package com.qingyun.im.client.task; import com.qingyun.im.client.imClient.ClientSession; import com.qingyun.im.client.sender.MsgTimeoutTimerManager; import com.qingyun.im.client.sender.CommonSender; import com.qingyun.im.common.constants.ClientConstants; import com.qingyun.im.common.entity.ProtoMsg; import lombok.extern.slf4j.Slf4j; import java.util.TimerTask; /** * @description: 定时任务 * @author: 張青云 * @create: 2021-11-13 16:14 **/ @Slf4j public class MsgTimeoutTask extends TimerTask { // 当前重试次数 private int retryCount; // 需要进行超时重传的消息 private final ProtoMsg.Message msg; private final ClientSession session; private final CommonSender sender; private final MsgTimeoutTimerManager manager; public MsgTimeoutTask(MsgTimeoutTimerManager manager, CommonSender sender, ClientSession session, ProtoMsg.Message msg) { retryCount = 0; this.manager = manager; this.sender = sender; this.session = session; this.msg = msg; } @Override public void run() { retryCount++; // 超出重传次数限制 if (retryCount > ClientConstants.REPEAT_SEND_COUNT) { sendFail(); return; } // 如果当前正在重连中,则本次不进行消息的重传,等下一次重传时如果重连成功再重传 if (!session.isConnected()){ // 当前正在重连中,本次不占用重传次数 retryCount--; return; } // 重传消息 sender.sendMsg(msg); log.info("重传消息【{}:{}】", msg.getSequence(), msg.getMsg().getContext()); } /** * 消息多次重传仍未成功 */ private void sendFail() { // 从超时重传管理器中移除 manager.remove(msg.getSequence()); log.error("消息【{}:{}】发送失败", msg.getSequence(), msg.getMsg().getContext()); } }
gabrypulzio/wise-stack
templates/secure_headers.rb
<filename>templates/secure_headers.rb # frozen_string_literal: true # Please review this configuration for your needs. This configuration is not meant to # be the safest but just to have a minimal configuration to have secure_headers working # See https://github.com/twitter/secureheaders#configuration for more options SecureHeaders::Configuration.default do |config| config.csp = { default_src: %w('self' localhost:* ws://localhost:*), font_src: %w('self'), img_src: %w('self' data:), object_src: %w('none'), script_src: %w('self' 'unsafe-inline' localhost:*), style_src: %w('self' 'unsafe-inline') } end
eschiebel/common-cartridge-viewer
src/AssignmentListItem.js
import React, { Component } from "react"; import AssignmentListItemBody from "./AssignmentListItemBody"; export default class AssignmentListItem extends Component { constructor(props) { super(props); this.state = { isLoading: true, title: null, workflowState: null }; } async componentDidMount() { const path = this.props.href.substr(1); const xml = await this.props.getTextByPath(path); if (xml === null) { this.setState({ isLoading: false, title: "Error: Resource Not Found", points: "N/A", workflowState: "unpublished", resourceNotFound: true }); return; } const parser = new DOMParser(); const doc = parser.parseFromString(xml, "text/xml"); const title = doc.querySelector("title") && doc.querySelector("title").textContent; const gradableNode = doc.querySelector("gradable"); const points = gradableNode && gradableNode.textContent === "true" && gradableNode.getAttribute("points_possible") ? parseFloat(gradableNode.getAttribute("points_possible")) : 0; const workflowStateNode = doc.querySelector( "extensions > assignment > workflow_state" ); const workflowState = workflowStateNode && workflowStateNode.textContent; this.setState({ isLoading: false, title, points, workflowState }); } render() { if (this.state.isLoading) { return null; } const iconColor = ["published", "active"].includes(this.state.workflowState) ? "success" : "secondary"; return ( <AssignmentListItemBody iconColor={iconColor} identifier={this.props.identifier} title={this.state.title} points={this.state.points} workflowState={this.state.workflowState} resourceNotFound={this.state.resourceNotFound} isModuleItem={this.props.isModuleItem} /> ); } }
MaksimSobolev/redux-dashboard
src/components/uielements/card.js
import { Card } from 'antd'; import '../../style/UI-Component/card/card.css'; export default Card;
paullewallencom/java-978-1-8471-9440-4
_src/Chapter_08/ch08/BindEjb/03_AxisClient/src/com/binildas/esb/bindejb/JsrEjbEPPortType.java
/** * JsrEjbEPPortType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.binildas.esb.bindejb; public interface JsrEjbEPPortType extends java.rmi.Remote { public java.lang.String hello(java.lang.String in0) throws java.rmi.RemoteException, java.io.IOException; }
Webiny/PlatformSetup
Public/Core/Registry.js
<gh_stars>0 import Http from '/Core/Http' function initializeStore(store){ store.instance.init(); store.initialized = true; return store.instance.getInitialData().then((data) => { store.instance.setInitialData(data); }); } class Registry { constructor() { this.stores = {}; } addStore(store, meta) { if (!this.stores.hasOwnProperty(store)) { meta.instance = store; this.stores[store.getFqn()] = meta; } } getStore(name) { var store = this.stores[name]; if (!store.initialized) { initializeStore(store); } return store.instance; } } export default new Registry;
hixuym/monkey
monkey-resteasy/src/main/java/io/monkey/resteasy/setup/ResteasyHandlerProvider.java
/* * Copyright 2018-2023 Monkey, Inc * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.monkey.resteasy.setup; import io.monkey.MonkeyException; import io.undertow.server.HttpHandler; import io.undertow.servlet.api.DeploymentManager; import javax.inject.Provider; import javax.servlet.ServletException; /** * @author Michael * Created at: 2019/1/15 17:26 */ class ResteasyHandlerProvider implements Provider<HttpHandler> { private DeploymentManager manager; ResteasyHandlerProvider(DeploymentManager manager) { this.manager = manager; } @Override public HttpHandler get() { try { manager.deploy(); return manager.start(); } catch (ServletException e) { throw new MonkeyException(e); } } }
research-note/Many-as-One
nn/websocket-server/main/Controller.hpp
<reponame>research-note/Many-as-One<filename>nn/websocket-server/main/Controller.hpp /* Copyright 2021 The Many as One Authors. 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. ==============================================================================*/ #ifndef _NN_CONTROLLER_HPP_ #define _NN_CONTROLLER_HPP_ #include <iostream> #include <string> #include <array> #include <map> #include <vector> #include <functional> #include <execution> #include <algorithm> #include <sstream> #include <cstdlib> #include <fstream> namespace controller { std::map<std::string, std::function<int(std::string t)>> m { { "mnist", [](std::string message) -> int { std::system("cd ../parser && ./bazel-bin/main/example mnist > mnist.txt"); std::cout << std::ifstream("../parser/mnist.txt").rdbuf(); return 0; } }, { "grey", [](std::string message) -> int { std::system("cd ../parser && ./bazel-bin/main/example grey > grey.txt"); std::cout << std::ifstream("../parser/grey.txt").rdbuf(); return 0; } }, { "cluster", [](std::string message) -> int { std::array <std::string, 3> x = {"1", "2", "3"}; std::for_each(std::execution::par_unseq, x.begin(), x.end(), [](auto v) { std::string command("cd ../parser && ./bazel-bin/main/example > "); std::string fileName("cluster"); auto files = command.append(fileName).append(v).append(".txt").c_str(); std::system(files); std::string path("../parser/"); std::cout << std::ifstream(path.append(files)).rdbuf(); }); return 0; } }, }; int router(std::string message) { std::istringstream iss(message); std::string token; std::cout << "message: " << message << std::endl; std::getline(iss, token, '/'); std::getline(iss, token, '/'); auto result = m[token](message); return result; } } #endif // _NN_CONTROLLER_HPP_
peedekza40/Project-final-sourcecode
js/hr/validate.js
<filename>js/hr/validate.js /* @Author : Jiranun @Date : June 30, 2016 @Detail : Validate element in form @Param : form (ID of tag form) @syntax: validate_form('frm_save') กรณีไว้นอก form or validate_form(this.form.id) กรณีไว้ใน form ใส่ validate ไว้ใน tag ที่ต้องการ */ function validate_form(forms){ //console.log(forms); var elementform = document.getElementById(forms); var chk_valid =0; for (var i = 0; i < elementform.elements.length; i++){ var attr = elementform[i].hasAttribute("validate"); // For some browsers, `attr` is undefined; for others, `attr` is false. Check for both. if (typeof attr !== typeof undefined && attr !== false) { // Element has this attribute //console.log("validate:" + ele); //validate if(elementform[i].tagName != "BUTTON" && elementform[i].tagName != "button"){ var elem = elementform[i]; var elem_id = elementform[i].id;//get id of element var prev_ele = $("#"+elem_id).parent().attr("id");//get id of previous elements //console.log("validate:" + prev_ele+" : "+elementform[i].value); if(elementform[i].value == ""){ if( $(elem).hasClass("select2") ){ var searchEles = document.getElementById(prev_ele).children; $(searchEles).each(function( index ) { if( $( this ).attr("id") == "s2id_"+elem_id ){ var sub_ele = document.getElementById($( this ).attr("id")).children; //console.log(sub_ele); $(sub_ele).each(function( sub_index ) { if( $(sub_ele).hasClass("select2-offscreen")){ var sub_id = $( this ).attr("id"); $( this ).css("background","#fbe8e5"); $( this ).css("border-color","#f69988"); } });//end sub element sub_ele } });//end element searchEles //console.log("#"+elem_id); }else{ $("#"+prev_ele).addClass("has-error"); } chk_valid++; }else{ if( $(elem).hasClass("select2") ){ var searchEles = document.getElementById(prev_ele).children; $(searchEles).each(function( index ) { if( $( this ).attr("id") == "s2id_"+elem_id ){ var sub_ele = document.getElementById($( this ).attr("id")).children; console.log(sub_ele); $(sub_ele).each(function( sub_index ) { if( $(sub_ele).hasClass("select2-offscreen")){ $( this ).css("background","transparent"); $( this ).css("border-color","#e0e0e0"); } });//end sub element sub_ele } });//end element searchEles //console.log("#"+elem_id); }else{ $("#"+prev_ele).removeClass("has-error"); } } }//end check console.log(elementform[i].tagName); } }//end for if(chk_valid > 0){ return false; }else{ //กรณีเอาไว้นอก form $("#"+forms).submit(); return true; } }//end fn validate_form
nhtnhan/CMPUT663-copilot-eval
output/sonar_java/src/main/java/frogJump.java
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** https://leetcode.com/problems/frog-jump/ */ //A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. //Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. //If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. class frogJump { public boolean canCross(int[] stones) { if (stones == null || stones.length == 0) { return false; } if (stones.length == 1) { return true; } Map<Integer, Set<Integer>> jumpMap = new HashMap<>(); for (int i = 0; i < stones.length; i++) { jumpMap.put(stones[i], new HashSet<>()); } jumpMap.get(stones[0]).add(1); for (int i = 1; i < stones.length; i++) { for (int j : jumpMap.get(stones[i - 1])) { int jump = stones[i] - stones[i - 1] + j; if (jump > 0 && jumpMap.get(stones[i]).add(jump)) { if (jump == stones[stones.length - 1] - stones[i]) { return true; } } } } return false; } }
shaojiankui/iOS10-Runtime-Headers
PrivateFrameworks/OfficeImport.framework/OCXContentTypes.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ @interface OCXContentTypes : NSObject { NSMutableDictionary * mContentTypeCountMap; NSMutableDictionary * mContentTypeObjectMap; NSMutableArray * mContentTypes; NSMutableSet * mDefaultTypes; } + (id)relativePathForPath:(id)arg1 currentPath:(id)arg2; - (void)addContentTypeForContentType:(id)arg1 extension:(id)arg2; - (id)addContentTypeForKey:(id)arg1 contentType:(id)arg2 path:(id)arg3; - (bool)containsContentType:(id)arg1; - (bool)containsContentType:(id)arg1 withKey:(id)arg2; - (void)dealloc; - (id)init; - (bool)isLastEntryContentType:(id)arg1; - (id)pathForContentType:(id)arg1; - (id)pathForKey:(id)arg1; - (id)pathForMainDocument; - (void)populateCommonExtensions; - (id)uniquePathForPath:(id)arg1; - (void)writeContentTypesToStream:(id)arg1; @end
ManishParyani/cmc-claim-store
domain-model/src/main/java/uk/gov/hmcts/cmc/domain/models/otherparty/IndividualDetails.java
<gh_stars>10-100 package uk.gov.hmcts.cmc.domain.models.otherparty; import lombok.Builder; import lombok.EqualsAndHashCode; import org.apache.commons.lang3.StringUtils; import uk.gov.hmcts.cmc.domain.constraints.AgeRangeValidator; import uk.gov.hmcts.cmc.domain.constraints.SplitName; import uk.gov.hmcts.cmc.domain.models.Address; import uk.gov.hmcts.cmc.domain.models.legalrep.Representative; import uk.gov.hmcts.cmc.domain.models.party.SplitNamedParty; import uk.gov.hmcts.cmc.domain.models.party.TitledParty; import uk.gov.hmcts.cmc.domain.utils.PartyUtils; import java.time.LocalDate; import java.util.Optional; import javax.validation.constraints.Size; @SplitName @EqualsAndHashCode(callSuper = true) public class IndividualDetails extends TheirDetails implements TitledParty, SplitNamedParty { @AgeRangeValidator private final LocalDate dateOfBirth; @Size(max = 35, message = "must be at most {max} characters") private final String title; // todo ROC-5160 remove @SplitName and put @NotBlank when frontend is merged @Size(max = 255, message = "must be at most {max} characters") private final String firstName; // todo ROC-5160 remove @SplitName and put @NotBlank when frontend is merged @Size(max = 255, message = "must be at most {max} characters") private final String lastName; @Builder public IndividualDetails( String id, String name, String title, String firstName, String lastName, Address address, String email, Representative representative, Address serviceAddress, LocalDate dateOfBirth, Address claimantProvidedAddress, String phoneNumber ) { super(id, name, address, email, representative, serviceAddress, claimantProvidedAddress, phoneNumber); this.dateOfBirth = dateOfBirth; this.title = title; this.firstName = firstName; this.lastName = lastName; } public Optional<LocalDate> getDateOfBirth() { return Optional.ofNullable(dateOfBirth); } @Override public Optional<String> getTitle() { return Optional.ofNullable(title); } @Override public String getName() { if (StringUtils.isNotBlank(firstName) && StringUtils.isNotBlank(lastName)) { return PartyUtils.fullNameFrom(title, firstName, lastName); } return super.getName(); } @Override public String getFirstName() { return firstName; } @Override public String getLastName() { return lastName; } }
AbelNavarro/crowbar-core
crowbar_framework/app/models/batch/build.rb
# # Copyright 2011-2013, Dell # Copyright 2013-2015, SUSE LINUX GmbH # # 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. # module Batch class Build < Base attr_accessor :file validates :file, presence: true def skipped @skipped ||= [] end protected def persist! true end def aliases_to_nodes @aliases_to_nodes ||= begin {}.tap do |aliases| NodeObject.find_all_nodes.each do |node| aliases[node.alias] = node.name end end end end class << self def attribute_names super.tap do |values| unless values.include?("file") values.push("file") end end end end end end
sappenin/java-ilp-connector
connector-service-impl/src/main/java/org/interledger/connector/accounts/IlpOverHttpAccountIdResolver.java
<reponame>sappenin/java-ilp-connector package org.interledger.connector.accounts; import org.springframework.security.core.Authentication; /** * Defines how to resolve AccountId for a given Ilp-over-Http connection. */ public interface IlpOverHttpAccountIdResolver extends AccountIdResolver { /** * Determine the {@link AccountId} for the supplied principal. * * @param authentication The {@link Authentication} to introspect to determine the accountId that it represents. * * @return The {@link AccountId} for the supplied request. */ AccountId resolveAccountId(Authentication authentication); }
zadcha/rethinkdb
src/buffer_cache/stats.hpp
// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef BUFFER_CACHE_STATS_HPP_ #define BUFFER_CACHE_STATS_HPP_ #include "perfmon/perfmon.hpp" #include "buffer_cache/page_cache.hpp" class alt_cache_stats_t : public home_thread_mixin_t { public: explicit alt_cache_stats_t(alt::page_cache_t *_page_cache, perfmon_collection_t *parent); alt::page_cache_t *page_cache; perfmon_collection_t cache_collection; perfmon_membership_t cache_membership; class perfmon_value_t : public perfmon_t { public: explicit perfmon_value_t(alt_cache_stats_t *_parent); void *begin_stats(); void visit_stats(void *); ql::datum_t end_stats(void *); private: alt_cache_stats_t *parent; DISABLE_COPYING(perfmon_value_t); }; perfmon_value_t in_use_bytes; perfmon_membership_t in_use_bytes_membership; perfmon_multi_membership_t cache_collection_membership; }; #endif // BUFFER_CACHE_STATS_HPP_
pasmuss/cmssw
DQM/L1TMonitor/src/L1TStage2BMTF.cc
<reponame>pasmuss/cmssw /* * \L1TStage2BMTF.cc * \author <NAME> * \December 2015 /G.karathanasis */ #include "DQM/L1TMonitor/interface/L1TStage2BMTF.h" L1TStage2BMTF::L1TStage2BMTF(const edm::ParameterSet & ps): monitorDir(ps.getUntrackedParameter<std::string>("monitorDir","")), bmtfSource(ps.getParameter<edm::InputTag>("bmtfSource")), // bmtfSourceTwinMux1(ps.getParameter<edm::InputTag>("bmtfSourceTwinMux1")), // bmtfSourceTwinMux2(ps.getParameter<edm::InputTag>("bmtfSourceTwinMux2")), verbose(ps.getUntrackedParameter<bool>("verbose", false)), global_phi(-1000) { bmtfToken=consumes<l1t::RegionalMuonCandBxCollection>(ps.getParameter<edm::InputTag>("bmtfSource")); // bmtfTokenTwinMux1 = consumes<L1MuDTChambThContainer>(ps.getParameter<edm::InputTag>("bmtfSourceTwinMux1")); // bmtfTokenTwinMux2 = consumes<L1MuDTChambPhContainer>(ps.getParameter<edm::InputTag>("bmtfSourceTwinMux2")); } L1TStage2BMTF::~L1TStage2BMTF() { } void L1TStage2BMTF::dqmBeginRun(const edm::Run& iRrun, const edm::EventSetup& eveSetup) { } void L1TStage2BMTF::beginLuminosityBlock(const edm::LuminosityBlock& iLumi, const edm::EventSetup& eveSetup) { } void L1TStage2BMTF::bookHistograms(DQMStore::IBooker &ibooker, const edm::Run& iRun, const edm::EventSetup& eveSetup) { ibooker.setCurrentFolder(monitorDir); bmtf_hwEta = ibooker.book1D("bmtf_hwEta", "HW #eta", 461, -230.5, 230.5); bmtf_hwLocalPhi = ibooker.book1D("bmtf_hwLocalPhi", "HW Local #phi", 201, -100.5, 100.5); bmtf_hwGlobalPhi = ibooker.book1D("bmtf_hwGlobalPhi", "HW Global #phi", 576, -0.5, 575.5); bmtf_hwPt = ibooker.book1D("bmtf_hwPt", "HW p_{T}", 512, -0.5, 511.5); bmtf_hwQual= ibooker.book1D("bmtf_hwQual" , "HW Quality", 20, -0.5, 19.5); bmtf_proc = ibooker.book1D("bmtf_proc" , "Processor", 12, -0.5, 11.5); bmtf_wedge_bx = ibooker.book2D("bmtf_wedge_bx", "Wedge vs BX", 12, -0.5, 11.5, 5, -2.5, 2.5); bmtf_wedge_bx->setTitle(";Wedge; BX"); for (int bin = 1; bin < 13; ++bin) { bmtf_wedge_bx->setBinLabel(bin, std::to_string(bin), 1); } bmtf_hwEta_hwLocalPhi = ibooker.book2D("bmtf_hwEta_hwLocalPhi", "HW #eta vs HW Local #phi" , 461, -230.5, 230.5, 201, -100.5, 100.5); bmtf_hwEta_hwLocalPhi->setTitle(";HW #eta; HW Local #phi"); bmtf_hwEta_hwGlobalPhi = ibooker.book2D("bmtf_hwEta_hwGlobalPhi", "HW #eta vs HW Global #phi" , 100, -230.5, 230.5, 120, -0.5, 575.5); bmtf_hwEta_hwGlobalPhi->setTitle(";HW #eta; HW Global #phi"); bmtf_hwPt_hwEta = ibooker.book2D("bmtf_hwPt_hwEta" , "HW p_{T} vs HW #eta", 511, -0.5, 510.5, 461, -230.5, 230.5); bmtf_hwPt_hwEta->setTitle(";HW p_{T}; HW #eta"); bmtf_hwPt_hwLocalPhi = ibooker.book2D("bmtf_hwPt_hwLocalPhi" , "HW p_{T} vs HW Local #phi", 511, -0.5, 510.5, 201, -100.5, 100.5); bmtf_hwPt_hwLocalPhi->setTitle(";HW p_{T}; HW Local #phi"); bmtf_hwEta_bx = ibooker.book2D("bmtf_hwEta_bx" , "HW #eta vs BX" , 461, -230.5, 230.5, 5, -2.5, 2.5); bmtf_hwEta_bx->setTitle(";HW #eta; BX"); bmtf_hwLocalPhi_bx = ibooker.book2D("bmtf_hwLocalPhi_bx" , "HW Local #phi vs BX" , 201, -100.5, 100.5, 5, -2.5, 2.5); bmtf_hwLocalPhi_bx->setTitle(";HW Local #phi; BX"); bmtf_hwPt_bx = ibooker.book2D("bmtf_hwPt_bx" , "HW p_{T} vs BX" , 511, -0.5, 510.5, 5, -2.5, 2.5); bmtf_hwPt_bx->setTitle(";HW p_{T}; BX"); bmtf_hwQual_bx = ibooker.book2D("bmtf_hwQual_bx" , "HW Quality vs BX" , 20, -0.5, 19.5, 5, -2.5, 2.5); bmtf_hwQual_bx->setTitle("; HW Quality; BX"); // bmtf_twinmuxInput_PhiBX = ibooker.book1D("bmtf_twinmuxInput_PhiBX" , "TwinMux Input Phi BX" , 5, -2.5, 2.5); // bmtf_twinmuxInput_PhiPhi = ibooker.book1D("bmtf_twinmuxInput_PhiPhi" , "TwinMux Input Phi HW Phi" , 201, -100.5, 100.5); // bmtf_twinmuxInput_PhiPhiB = ibooker.book1D("bmtf_twinmuxInput_PhiPhiB" , "TwinMux Input Phi HW PhiB" , 201, -100.5, 100.5); // bmtf_twinmuxInput_PhiQual = ibooker.book1D("bmtf_twinmuxInput_PhiQual" , "TwinMux Input Phi HW Quality" , 20, -0.5, 19.5); // bmtf_twinmuxInput_PhiStation = ibooker.book1D("bmtf_twinmuxInput_PhiStation" , "TwinMux Input Phi HW Station", 6, -1, 5); // bmtf_twinmuxInput_PhiSector = ibooker.book1D("bmtf_twinmuxInput_PhiSector" , "TwinMux Input Phi HW Sector" , 14, -1, 13 ); // bmtf_twinmuxInput_PhiWheel = ibooker.book1D("bmtf_twinmuxInput_PhiWheel" , "TwinMux Input Phi HW Wheel" , 16 , -4, 4); // bmtf_twinmuxInput_PhiTrSeg = ibooker.book1D("bmtf_twinmuxInput_PhiTrSeg" , "TwinMux Input Phi HW Track Segment" , 6, -1, 5 ); // bmtf_twinmuxInput_PhiWheel_PhiSector = ibooker.book2D("bmtf_twinmuxInput_PhiWheel_PhiSector" , "TwinMux Input Phi HW Wheel vs HW Sector", 16 , -4, 4, 14, -1, 13 ); // bmtf_twinmuxInput_PhiWheel_PhiSector->setTitle("; TwinMux Input Phi HW Wheel; TwinMux Input Phi HW Sector"); // for (int bin = 1; bin < 5; ++bin) { // bmtf_twinmuxInput_PhiWheel_PhiSector->setBinLabel(bin, "station"+std::to_string(bin), 1); // bmtf_twinmuxInput_PhiTrSeg->setBinLabel(bin, "station"+std::to_string(bin), 1); // } // bmtf_twinmuxInput_TheBX = ibooker.book1D("bmtf_twinmuxInput_TheBX" , "TwinMux Input The BX" , 5, -2.5, 2.5); // bmtf_twinmuxInput_ThePhi= ibooker.book1D("bmtf_twinmuxInput_ThePhi" , "TwinMux Input The HW Phi" , 201, -100.5, 100.5); // bmtf_twinmuxInput_ThePhiB = ibooker.book1D("bmtf_twinmuxInput_ThePhiB" , "TwinMux Input The HW PhiB" , 201, -100.5, 100.5); // bmtf_twinmuxInput_TheQual = ibooker.book1D("bmtf_twinmuxInput_TheQual" , "TwinMux Input The HW Quality" , 20, -0.5, 19.5); // bmtf_twinmuxInput_TheStation = ibooker.book1D("bmtf_twinmuxInput_TheStation" , "TwinMux Input The HW Station" , 6, -1, 5); // bmtf_twinmuxInput_TheSector = ibooker.book1D("bmtf_twinmuxInput_TheSector" , "TwinMux Input The HW Sector" , 14, -1, 13 ); // bmtf_twinmuxInput_TheWheel = ibooker.book1D("bmtf_twinmuxInput_TheWheel" , "TwinMux Input The HW Wheel" , 16 , -4, 4); // bmtf_twinmuxInput_TheTrSeg = ibooker.book1D("bmtf_twinmuxInput_TheTrSeg" , "TwinMux Input The HW Track Segment" , 6, -1, 5 ); // bmtf_twinmuxInput_TheWheel_TheSector = ibooker.book2D("bmtf_twinmuxInput_TheWheel_TheSector" , "TwinMux Input The HW Wheel vs HW Sector", 16 , -4, 4, 14, -1, 13); // bmtf_twinmuxInput_TheWheel_TheSector->setTitle("; TwinMux Input The HW Wheel; TwinMux Input The HW Sector"); // for (int bin = 1; bin < 5; ++bin) { // bmtf_twinmuxInput_TheWheel_TheSector->setBinLabel(bin, "station"+std::to_string(bin), 1); // bmtf_twinmuxInput_TheTrSeg->setBinLabel(bin, "station"+std::to_string(bin), 1); // } } void L1TStage2BMTF::analyze(const edm::Event & eve, const edm::EventSetup & eveSetup) { if (verbose) { edm::LogInfo("L1TStage2BMTF") << "L1TStage2BMTF: analyze...." << std::endl; } edm::Handle<l1t::RegionalMuonCandBxCollection> bmtfMuon; eve.getByToken(bmtfToken, bmtfMuon); // edm::Handle<L1MuDTChambThContainer> bmtfMuonTwinMux1; // eve.getByToken(bmtfTokenTwinMux1, bmtfMuonTwinMux1); // edm::Handle<L1MuDTChambPhContainer> bmtfMuonTwinMux2; // eve.getByToken(bmtfTokenTwinMux2, bmtfMuonTwinMux2); for(int itBX=bmtfMuon->getFirstBX(); itBX<=bmtfMuon->getLastBX(); ++itBX) { for(l1t::RegionalMuonCandBxCollection::const_iterator itMuon = bmtfMuon->begin(itBX); itMuon != bmtfMuon->end(itBX); ++itMuon) { bmtf_hwEta->Fill(itMuon->hwEta()); bmtf_hwLocalPhi->Fill(itMuon->hwPhi()); bmtf_hwPt->Fill(itMuon->hwPt()); bmtf_hwQual->Fill(itMuon->hwQual()); bmtf_proc->Fill(itMuon->processor()); if (fabs(bmtfMuon->getLastBX()-bmtfMuon->getFirstBX())>3){ bmtf_wedge_bx->Fill(itMuon->processor(), itBX); bmtf_hwEta_bx->Fill(itMuon->hwEta(), itBX); bmtf_hwLocalPhi_bx->Fill(itMuon->hwPhi(), itBX); bmtf_hwPt_bx->Fill(itMuon->hwPt(), itBX); bmtf_hwQual_bx->Fill(itMuon->hwQual(), itBX);} bmtf_hwEta_hwLocalPhi->Fill(itMuon->hwEta(),itMuon->hwPhi()); bmtf_hwPt_hwEta->Fill(itMuon->hwPt(), itMuon->hwEta()); bmtf_hwPt_hwLocalPhi->Fill(itMuon->hwPt(), itMuon->hwPhi()); /*if(itMuon->hwPhi()*0.010902>=0 && itMuon->hwPhi()*0.010902<=30) global_phi = itMuon->hwPhi() + itMuon->processor()*30.; if(itMuon->hwPhi()*0.010902<0) global_phi = 30-itMuon->hwPhi() + (itMuon->processor()-1)*30.; if(itMuon->hwPhi()*0.010902>30) global_phi = itMuon->hwPhi()-30 + (itMuon->processor()+1)*30.;*/ global_phi= itMuon->hwPhi() + itMuon->processor()*48.-15; if (global_phi<0) global_phi=576+global_phi; bmtf_hwGlobalPhi->Fill(global_phi); bmtf_hwEta_hwGlobalPhi->Fill(itMuon->hwEta(), global_phi); } } // for(L1MuDTChambThContainer::The_Container::const_iterator itMuon = bmtfMuonTwinMux1->getContainer()->begin(); itMuon != bmtfMuonTwinMux1->getContainer()->end(); ++itMuon) // { // bmtf_twinmuxInput_TheBX->Fill(itMuon->bxNum()); // // bmtf_twinmuxInput_ThePhi->Fill(itMuon->phi()); // // bmtf_twinmuxInput_ThePhiB->Fill(itMuon->phiB()); // // bmtf_twinmuxInput_TheQual->Fill(itMuon->code()); // bmtf_twinmuxInput_TheStation->Fill(itMuon->stNum()); // bmtf_twinmuxInput_TheSector->Fill(itMuon->scNum()); // bmtf_twinmuxInput_TheWheel->Fill(itMuon->whNum()); // for(int i = 1; i<=itMuon->stNum(); ++i) // { // // bmtf_twinmuxInput_TheTrSeg->Fill(itMuon->Ts2Tag()); // bmtf_twinmuxInput_TheWheel_TheSector->Fill(itMuon->whNum(), itMuon->scNum()); // } // } // for(L1MuDTChambPhContainer::Phi_Container::const_iterator itMuon = bmtfMuonTwinMux2->getContainer()->begin(); itMuon != bmtfMuonTwinMux2->getContainer()->end(); ++itMuon) // { // bmtf_twinmuxInput_PhiBX->Fill(itMuon->bxNum()); // bmtf_twinmuxInput_PhiPhi->Fill(itMuon->phi()); // bmtf_twinmuxInput_PhiPhiB->Fill(itMuon->phiB()); // bmtf_twinmuxInput_PhiQual->Fill(itMuon->code()); // bmtf_twinmuxInput_PhiStation->Fill(itMuon->stNum()); // bmtf_twinmuxInput_PhiSector->Fill(itMuon->scNum()); // bmtf_twinmuxInput_PhiWheel->Fill(itMuon->whNum()); // for(int i = 1; i<= itMuon->stNum() ; ++i) // { // bmtf_twinmuxInput_PhiTrSeg->Fill(itMuon->Ts2Tag()); // bmtf_twinmuxInput_PhiWheel_PhiSector->Fill(itMuon->whNum(), itMuon->scNum()); // } // } }
PixelShiftAI/createts
dist/es6/style/LineHeight.spec.js
<filename>dist/es6/style/LineHeight.spec.js import { LineHeight, LineHeightType } from './LineHeight'; test('should parse line height', function () { expect(LineHeight.of('normal').type).toEqual(LineHeightType.NORMAL); expect(LineHeight.of('10px')).toEqual({ type: LineHeightType.LENGTH, value: 10 }); expect(LineHeight.of('10')).toEqual({ type: LineHeightType.NUMBER, value: 10 }); expect(LineHeight.of('20%')).toEqual({ type: LineHeightType.PERCENT, value: 20 }); expect(LineHeight.of('aa', true)).toBeUndefined(); });
zlc18/LocalJudge
tests/cpp/reverseNodesInKGroup/reverseNodesInKGroup.cpp
// Source : https://oj.leetcode.com/problems/reverse-nodes-in-k-group/ // Author : <NAME> // Date : 2014-07-05 /********************************************************************************** * * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. * * If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. * * You may not alter the values in the nodes, only nodes itself may be changed. * * Only constant memory is allowed. * * For example, * Given this linked list: 1->2->3->4->5 * * For k = 2, you should return: 2->1->4->3->5 * * For k = 3, you should return: 3->2->1->4->5 * * **********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *reverseList(ListNode *&head, int k); ListNode *reverseKGroup(ListNode *head, int k) { if (k<=0) return head; ListNode fake(0); fake.next = head; ListNode* p = &fake; while(p){ p->next = reverseList(p->next, k); for(int i=0; p && i<k; i++){ p = p->next; } } return fake.next; } ListNode *reverseList(ListNode *&head, int k){ ListNode* pEnd=head; while (pEnd && k>0){ pEnd = pEnd->next; k--; } if (k>0) return head; ListNode *pHead=pEnd, *p=head; while(p != pEnd){ ListNode *q = p->next; p->next = pHead; pHead = p; p = q; } return pHead; } void printList(ListNode* h) { while(h!=NULL){ printf("%d ", h->val); h = h->next; } printf("\n"); } ListNode* createList(int a[], int n) { ListNode *head=NULL, *p=NULL; for(int i=0; i<n; i++){ if (head == NULL){ head = p = new ListNode(a[i]); }else{ p->next = new ListNode(a[i]); p = p->next; } } return head; } int main(int argc, char** argv) { int a[] = {1,2,3,4,5,6,7,8,9,10}; ListNode* pList = createList(a, sizeof(a)/sizeof(int)); int k =2; if (argc>1){ k = atoi(argv[1]); } pList = reverseKGroup(pList, k); printList(pList); return 0; }
davidbrochart/daetk
pdetk/ConstBCECDM.h
#ifndef ConstBCECDM_H #define ConstBCECDM_H #include <vector> #include <map> #include <iostream> #include "Definitions.h" #include "Vec.h" #include "BandColMat.h" #include "BoundaryCondition.h" #include "PetscStencilMM.h" //mwf can I include DivKgradECDM class into this definition #include "DivKgradECDM.h" //#define USE_CONT_INTERFACE_TERMS_ECDM namespace Daetk { using std::cerr; using std::endl; // NEED TO ADD NEUMANN DERIVATIVES--ZERO FLUX DERIVATIVES FOR DIVKGRAD class ConstBCECDM : public BoundaryCondition<Petsc::StencilMM> { public: void applyDirichletConditionsRHS(Petsc::StencilMM&, Daetk::Petsc::Vec&) {std::cerr<<"not yet implemented for ECDM"<<std::endl;} inline void setCurrentDivKgrad(DivKgradECDM<ConstBCECDM,1>* div) { assert(div); currentDiv = div; } ConstBCECDM():currentDiv(0) {} //==================== interface terms==================== template <int nv> inline void applyInteriorConditionToConstRelation(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, Vec& Kr,Vec& Rho, const Vec& pVal); void applyInteriorConditionToConstRelationDeriv(Petsc::StencilMM& node, Vec& DKr,Vec& DRho); //=== 1d === void applyInteriorConditionToInterfaceValues(Petsc::StencilMM& node, const Vec* Kr, const Vec* Rho, Vec& KrX,Vec& RhoX); //=== 2d === void applyInteriorConditionToInterfaceValues(Petsc::StencilMM& node, const Vec* Kr, const Vec* Rho, Vec& KrX,Vec& KrY, Vec& RhoX,Vec& RhoY); template <int nv> inline void applyInteriorConditionToInterfaceValueDerivs(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, const VecVecVec& DKr, const Vec* DRho); //ECDM has explicit dirichlet neumann and dummy conditions //these are for setting the residual and jacobian directly //==================== dirichlet ==================== inline void applyDirichletConditionsToRes(Petsc::StencilMM& node, Vec& res, real scaling=1.0); inline void applyDirichletYprime(Petsc::StencilMM& node); template <class JAC> inline void applyDirichletDerivatives(Petsc::StencilMM& node, JAC& DresDy, real scaling=1.0,int dof=1,int var=0); //==================== robbins ==================== //make global residual be flux-bc template <int nv> inline void applyRobbinsConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling=1.0); inline void applyRobbinsConditionsYprime(Petsc::StencilMM& node, Vec& yPrime); template <class JAC> inline void applyRobbinsDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& Div_D, int DIM, real scaling =1.0); //==================== dummy ==================== inline void applyDummyConditionsToRes(Petsc::StencilMM& node, Vec& res, real scaling=1.0); inline void applyDummyYprime(Petsc::StencilMM& node); template <class JAC> inline void applyDummyDerivatives(Petsc::StencilMM& node, JAC& DresDy, real scaling=1.0,int dof=1,int var=0); //==================== neumann ==================== //make global residual be flux-bc template <int nv> inline void applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling=1.0); inline void applyNeumannConditionsYprime(Petsc::StencilMM& node, Vec& yPrime); template <class JAC> inline void applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& Div_D, int DIM, real scaling =1.0); //====== these use mass balance and neumann bc template <int nv> inline void applyNeumannConditionsYprime(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, Vec& yPrime); //=== pressure head version //mwf now try and put in approx. using mass bal template <int nv> inline void applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, const Vec& Dp, real scaling=1.0); //mwf now try and put in approx. using mass bal template <class JAC, int nv> inline void applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& Div_D, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, const Vec& Dp, real alphaBDF, const Vec& DDrho, const Vec& DDtheta, const Vec& hXcen, const Vec& hYcen, real scaling =1.0); //=== mass conservative version //mwf now try and put in approx. using mass bal template <int nv> inline void applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& mCurrent, const Vec& betaDaeDef, const Vec& detMap, real alphaBDF, real scaling=1.0); //mwf now try and put in approx. using mass bal template <class JAC, int nv> inline void applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& Div_D, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, real alphaBDF, real scaling =1.0); //==================== interior ==================== inline void applyInteriorConditionsYprime(Petsc::StencilMM& node, Vec& yPrime); //make global residual be fluxLeft-fluxRight template <int nv> inline void applyInteriorConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling=1.0); template <class JAC> inline void applyInteriorDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& Div_D, int DIM, real scaling =1.0); //this one updates derivatives straight into jacobian for left and right terms template <class JAC, int nv> inline void updateInteriorDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, const VecVec* K, const Vec* Kr, const Vec* Rho, const Vec* P, const VecVecVec& DKr, const Vec* DRho, VecVec& D_Div, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, real scaling=1.0); //==================== no flow ==================== //make global residual be flux-bc template <int nv> inline void applyNoFlowConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling=1.0); inline void applyNoFlowConditionsYprime(Petsc::StencilMM& node, Vec& yPrime); template <class JAC, int nv> inline void applyNoFlowDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, DivKgradECDM<ConstBCECDM,nv>* div, int DIM, real scaling =1.0); //==================== all ==================== //account for 3 exterior boundary conditions in fluxes and //pressure differences //1d void applyBoundaryConditionsToPressureDifferences(Petsc::StencilMM& node, Vec& pDiff_x); void applyBoundaryConditionsToPressureDifferences(Petsc::StencilMM& node, Vec& pDiff_x, Vec& pDiff_y); //=== 1d === void applyBoundaryConditionsToFluxes(Petsc::StencilMM& node, Vec& flux_x); //=== 2d === void applyBoundaryConditionsToFluxes(Petsc::StencilMM& node, Vec& flux_x, Vec& flux_y); //=== 1d ==== //zero everything except interior pressure difference term void applyBoundaryConditionsToPressureDerivatives(Petsc::StencilMM& node, Vec& DpDiff_x_center, Vec& DpDiff_x_right); //=== 2d ==== //zero everything except interior pressure difference term void applyBoundaryConditionsToPressureDerivatives(Petsc::StencilMM& node, Vec& DpDiff_x_center, Vec& DpDiff_x_right, Vec& DpDiff_y_center, Vec& DpDiff_y_back); //=== 1d ==== //zero everything except derivatives evaluated at interior point void applyBoundaryConditionDerivativesECDM(Petsc::StencilMM& node, Vec& Dflux_x_center, Vec& Dflux_x_right); //=== 2d ==== //zero everything except derivatives evaluated at interior point void applyBoundaryConditionDerivativesECDM(Petsc::StencilMM& node, Vec& Dflux_x_center, Vec& Dflux_x_right, Vec& Dflux_x_back, Vec& Dflux_x_front, Vec& Dflux_x_rightBack, Vec& Dflux_x_rightFront, Vec& Dflux_y_center, Vec& Dflux_y_back, Vec& Dflux_y_right, Vec& Dflux_y_left, Vec& Dflux_y_backRight, Vec& Dflux_y_backLeft); ////////////////////////// //this is for time integration void adjustTimeIntegrationTolerance(Petsc::StencilMM& node, Vec & tol, real newTol); void setBoundaryConditions(face_type ft, condition_type ct, Petsc::StencilMM& node, real bc_value, Vec* var=0, Vec* varprime=0, real *value1 = 0, real *value2 = 0); //mwf try and make sure lists don't share values? void checkForDuplicateBCs(); void print(); void clear() { dirichlet.clear(); neumann.clear(); robbins.clear(); interior.clear(); dummy.clear(); noflow.clear(); } void deleteDirichlet(std::vector<Dirichlet>::iterator& dit_in) { dirichlet.erase(dit_in); } //mwf added to simplify interface, may not really need DivKgradECDM<ConstBCECDM,1>* currentDiv; }; ///////////////////////////////////////// //==================== interface conditions for const relations ========== //try to put in either arithmetic or upwind average //into constitutive relation value at internal interface template <int nv> inline void ConstBCECDM::applyInteriorConditionToConstRelation(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, Vec& Kr,Vec& Rho, const Vec& pVal) { init = interior.begin(); //std::cout<<init<<'\t'<<interior.end()<<std::endl<<std::flush; while(init != interior.end()) { node.globalNode(init->n); //mwf only set if node is local to this processor? if (node.isLocal) { int localNodeNumber = node.globalToLocal(init->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(init->face) { case INTERIOR_X: { Rho[node.center] = div->avgDensityAcrossInteriorBoundaryX(Rho,pVal); Kr[node.center] = div->avgRelPermAcrossInteriorBoundaryX(Kr,Rho,pVal); break; } case INTERIOR_Y: { //arithmetic average Rho[node.center] = div->avgDensityAcrossInteriorBoundaryY(Rho,pVal); Kr[node.center] = div->avgRelPermAcrossInteriorBoundaryY(Kr,Rho,pVal); break; } default: { cerr<<"wrong face = "<<init->face <<" in applyInteriorConditionToConstRelation "<<endl; assert(0); break; } }//end switch }//end if local ++init; }//end while }//end function template <int nv> inline void ConstBCECDM::applyInteriorConditionToInterfaceValueDerivs(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, const VecVecVec& DKr, const Vec* DRho) { init = interior.begin(); //std::cout<<init<<'\t'<<interior.end()<<std::endl<<std::flush; while(init != interior.end()) { node.globalNode(init->n); //mwf only set if node is local to this processor? if (node.isInGhostRegion) { int localNodeNumber = node.globalToLocal(init->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(init->face) { case INTERIOR_X: { div->setDKrXinterface(DKr); div->setDRhoXinterface(DRho); break; } case INTERIOR_Y: { div->setDKrYinterface(DKr); div->setDRhoYinterface(DRho); break; } default: { cerr<<"wrong face = "<<init->face <<" in applyInteriorConditionToConstRelation "<<endl; assert(0); break; } }//end switch }//end if local ++init; }//end while }//end function ////////////////////// //=========================dirichlet==================== inline void ConstBCECDM::applyDirichletConditionsToRes(Petsc::StencilMM& node, Vec& res, real scaling) { dit = dirichlet.begin(); //std::cout<<dit<<'\t'<<dirichlet.end()<<std::endl<<std::flush; while(dit != dirichlet.end()) { node.globalNode(dit->n); if (node.isLocal) res(node.center) = ((*dit->var)(node.center) - dit->value)*scaling; // cout<<"D"<<'t'<<res(node.center)<<'\t'<<(*dit->var)(node.center)<<'\t'<<dit->value<<endl; ++dit; } } inline void ConstBCECDM::applyDirichletYprime(Petsc::StencilMM& node) { //yprime is set to the yprime for neumann dit = dirichlet.begin(); while(dit != dirichlet.end()) { node.globalNode(dit->n); if (node.isLocal) (*dit->varprime)(node.center) = 0.0; ++dit; } } template <class JAC> inline void ConstBCECDM::applyDirichletDerivatives(Petsc::StencilMM& node, JAC& DresDy, real scaling,int dof, int var) { //remember this just sets the scaling of the bc variable, not the solution variable //the actual jacobian entry should be scaling*Dbc_var/Dsol_var //jacobian is set for neumann //DresDy is a row of the matrix with possible non-unit stride //Dres_depDy are the other non-unit stride row vectors dit = dirichlet.begin(); //std::cout<<dit<<'\t'<<dirichlet.end()<<std::endl; while(dit != dirichlet.end()) { node.globalNode(dit->n); //mwf added isLocal here if (node.isLocal) { Petsc::StencilMM::iterator sit = node.begin(); while (sit != node.end()) { //DresDy(node.center,sit->second.globalNodeNumber) = 0.0; for (int vj=0;vj<dof;vj++) DresDy(dof*node.center+var,dof*sit->globalNodeNumber+vj) = 0.0; ++sit; } //DresDy.zeroRow(node.center); DresDy(dof*node.center+var,dof*node.center+var) = scaling; DresDy.finalizeRow(dof*node.center+var); } ++dit; } } //====================dummy=========================== inline void ConstBCECDM::applyDummyConditionsToRes(Petsc::StencilMM& node, Vec& res, real scaling) { duit = dummy.begin(); //std::cout<<dit<<'\t'<<dirichlet.end()<<std::endl<<std::flush; while(duit != dummy.end()) { node.globalNode(duit->n); if (node.isLocal) res(node.center) = ((*duit->var)(node.center) - duit->value)*scaling; // cout<<"D"<<'t'<<res(node.center)<<'\t'<<(*dit->var)(node.center)<<'\t'<<dit->value<<endl; ++duit; } } inline void ConstBCECDM::applyDummyYprime(Petsc::StencilMM& node) { duit = dummy.begin(); while(duit != dummy.end()) { node.globalNode(duit->n); if (node.isLocal) (*duit->varprime)(node.center) = 0.0; ++duit; } } template <class JAC> inline void ConstBCECDM::applyDummyDerivatives(Petsc::StencilMM& node, JAC& DresDy, real scaling,int dof,int var) { //remember this just sets the scaling of the bc variable, not the solution variable //the actual jacobian entry should be scaling*Dbc_var/Dsol_var //jacobian is set for neumann //DresDy is a row of the matrix with possible non-unit stride //Dres_depDy are the other non-unit stride row vectors duit = dummy.begin(); //std::cout<<dit<<'\t'<<dirichlet.end()<<std::endl; while(duit != dummy.end()) { node.globalNode(duit->n); //mwf added isLocal here if (node.isLocal) { Petsc::StencilMM::iterator sit = node.begin(); while (sit != node.end()) { //DresDy(node.center,sit->second.globalNodeNumber) = 0.0; for (int vj=0;vj<dof;vj++) DresDy(dof*node.center+var,dof*sit->globalNodeNumber+vj) = 0.0; ++sit; } //DresDy.zeroRow(node.center); DresDy(dof*node.center+var,dof*node.center+var) = scaling; DresDy.finalizeRow(dof*node.center+var); } ++duit; } } //======================neumann========================= //===== these use qval-bc //mwf I don't know yet what to do about neumann and interior bc's //as far as time integration goes inline void ConstBCECDM::applyNeumannConditionsYprime(Petsc::StencilMM& node, Vec& yPrime) { nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter = node.center; if (node.isLocal) { yPrime(globalCenter) = 0.0; } ++nit; } } //make global residual be fluxInterior-qVal template <int nv> inline void ConstBCECDM::applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling) { assert(nv == 1); assert(div); const Vec & flux_x = div->getFlux_x(0); const Vec & flux_y = div->getFlux_y(0); nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter = node.center; if (node.isLocal) { int localNodeNumber = node.globalToLocal(nit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(nit->face) { case LEFT: { //using interior flux for the Dirichlet face //and zeroing the exterior flux //remember sign of normal for minus side res(globalCenter) = (flux_x[node.interRight] + nit->value)*scaling; if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interRight<<"]= " <<flux_x[node.interRight]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case RIGHT: { res(globalCenter) = (flux_x[node.interLeft] - nit->value)*scaling; if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interLeft<<"]= " <<flux_x[node.interLeft]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case FRONT: { //remeber sign for negative boundary res(globalCenter) = (flux_y[node.interBack] +nit->value)*scaling; // cout<<"FF"<<'\t'<<flux_y[node.interFront]<<'\t'<<nit->value <<'\t'<< flux_y[node.interBack]<<endl; break; } case BACK: { res(globalCenter) = (flux_y[node.interFront] -nit->value)*scaling; std::cout<<"FB"<<'\t'<<flux_y[node.interFront] <<'\t'<<nit->value<<'\t'<< res(globalCenter)<<endl; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end if isLocal ++nit; } } //make global residual be fluxInterior-qVal template <class JAC> inline void ConstBCECDM::applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& D_Div, int DIM, real scaling) { nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int nl=node.center-node.globalLow; real signOfDiv(1.0); if (node.isLocal) { switch(nit->face) { case LEFT: { signOfDiv = -1.0; break; } case RIGHT: { signOfDiv = 1.0; break; } case FRONT: { signOfDiv = -1.0; break; } case BACK: { signOfDiv = 1.0; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch signOfDiv *= scaling; DresDy(node.center,node.center) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::CENTER][nl]; if (node.anchor->k > 0) DresDy(node.center,node.left) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT][nl]; if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.right) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT][nl]; if (DIM > 0) { if (node.anchor->j > 0) { DresDy(node.center,node.front)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]; //(j-1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftFront)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_FRONT][nl]; //(j-1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightFront) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_FRONT][nl]; } if (node.anchor->j < node.nyNodes-1) { DresDy(node.center,node.back) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][nl]; //(j+1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftBack)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_BACK][nl]; //(j+1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightBack) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_BACK][nl]; } }//end DIM==TWO_D if (DIM > 1) //DIM==THREE_D { if (node.anchor->i > 0) DresDy(node.center,node.bottom)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BOTTOM][nl]; if (node.anchor->i < node.nzNodes-1) DresDy(node.center,node.top) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::TOP][nl]; } DresDy.finalizeRow(node.center); }//end isLocal ++nit; }//end while }//end function //=============== these use mass balance template <int nv> inline void ConstBCECDM::applyNeumannConditionsYprime(Petsc::StencilMM& node, DivKgradECDM<ConstBCECDM,nv>* div, Vec& yPrime) { assert(nv == 1); assert(div); nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter = node.center; if (node.isLocal) { switch(nit->face) { case LEFT: { int globalRight = node.right; yPrime(globalCenter) = yPrime(globalRight); break; } case RIGHT: { int globalLeft = node.left; yPrime(globalCenter) = yPrime(globalLeft); break; } case FRONT: { int globalBack = node.back; yPrime(globalCenter) = yPrime(globalBack); break; } case BACK: { int globalFront = node.front; yPrime(globalCenter) = yPrime(globalFront); break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end if isLocal ++nit; } } //========= pressure head form //mwf now try and put in approx. using mass bal. only 2d for now template <int nv> inline void ConstBCECDM::applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, const Vec& Dp, real scaling) { assert(nv == 1); assert(div); const Vec & flux_x = div->getFlux_x(0); const Vec & flux_y = div->getFlux_y(0); const Vec & hXcen = div->getSpatialIncrement(0); const Vec & hYcen = div->getSpatialIncrement(1); nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter= node.center; int globalLeft = node.left; int globalRight = node.right; int globalFront = node.front; int globalBack = node.back; if (node.isLocal) { int localNodeNumber = node.globalToLocal(nit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(nit->face) { case LEFT: { //remember sign of normal for minus side //res(globalCenter) = (flux_x[node.interRight] + nit->value)*scaling; int globalNeighbor=globalRight; int localNeighbor = node.right; real accumulation=(rho(globalNeighbor)*Dtheta(globalNeighbor) + Drho(globalNeighbor)*theta(globalNeighbor)); //use Dp as global variable accumulation *= Dp(globalNeighbor); real volume = detMap(globalNeighbor)*hYcen[localNeighbor] *hXcen[localNeighbor]; real fluxCalc = flux_x[node.interLeft]; //now switch to localNeighbor to get divergence node.localNode(localNeighbor); //normal res calc uses -div from DivKgradECDM res(globalCenter) = volume*accumulation + flux_x[node.interRight] - fluxCalc + flux_y[node.interBack] - flux_y[node.interFront]; if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interRight<<"]= " <<flux_x[node.interRight]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case RIGHT: { // res(globalCenter) = (flux_x[node.interLeft] - nit->value)*scaling; int globalNeighbor=globalLeft; int localNeighbor = node.left; real accumulation=(rho(globalNeighbor)*Dtheta(globalNeighbor) + Drho(globalNeighbor)*theta(globalNeighbor)); //use Dp as global variable accumulation *= Dp(globalNeighbor); real volume = detMap(globalNeighbor)*hYcen[localNeighbor] *hXcen[localNeighbor]; real fluxCalc = flux_x[node.interRight]; //now switch to localNeighbor to get divergence node.localNode(localNeighbor); //normal res calc uses -div from DivKgradECDM res(globalCenter) = volume*accumulation + fluxCalc - flux_x[node.interLeft] + flux_y[node.interBack] - flux_y[node.interFront]; if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interLeft<<"]= " <<flux_x[node.interLeft]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case FRONT: { //remeber sign for negative boundary // res(globalCenter) = (flux_y[node.interBack] +nit->value)*scaling; int globalNeighbor=globalBack; int localNeighbor = node.back; real accumulation=(rho(globalNeighbor)*Dtheta(globalNeighbor) + Drho(globalNeighbor)*theta(globalNeighbor)); //use Dp as global variable accumulation *= Dp(globalNeighbor); real volume = detMap(globalNeighbor)*hYcen[localNeighbor] *hXcen[localNeighbor]; real fluxCalc = flux_y[node.interFront]; //now switch to localNeighbor to get divergence node.localNode(localNeighbor); //normal res calc uses -div from DivKgradECDM res(globalCenter) = volume*accumulation + flux_x[node.interRight] - flux_x[node.interLeft] + flux_y[node.interBack] -fluxCalc; // cout<<"FF"<<'\t'<<flux_y[node.interFront]<<'\t'<<nit->value <<'\t'<< flux_y[node.interBack]<<endl; break; } case BACK: { // res(globalCenter) = (flux_y[node.interFront] -nit->value)*scaling; int globalNeighbor=globalFront; int localNeighbor = node.front; real accumulation=(rho(globalNeighbor)*Dtheta(globalNeighbor) + Drho(globalNeighbor)*theta(globalNeighbor)); //use Dp as global variable accumulation *= Dp(globalNeighbor); real volume = detMap(globalNeighbor)*hYcen[localNeighbor] *hXcen[localNeighbor]; real fluxCalc = flux_y[node.interBack]; std::cout<<" in appNeuRes glbno = "<<globalCenter<<" glbnei= " <<globalNeighbor<<" vol= "<<volume <<" accu = "<<accumulation <<" fluxCalc= "<<fluxCalc <<" res("<<globalNeighbor<<")= " <<res(globalNeighbor)<<std::endl; //now switch to localNeighbor to get divergence node.localNode(localNeighbor); //normal res calc uses -div from DivKgradECDM res(globalCenter) = volume*accumulation + flux_x[node.interRight] - flux_x[node.interLeft] + fluxCalc - flux_y[node.interFront]; std::cout<<" res("<<globalCenter<<")= "<<res(globalCenter) <<std::endl; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch res(globalCenter) *= scaling; }//end if isLocal ++nit; } } template <class JAC, int nv> inline void ConstBCECDM::applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& D_Div, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, const Vec& Dp, real alphaBDF, const Vec& DDrho, const Vec& DDtheta, const Vec& hXcen, const Vec& hYcen, real scaling) { nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter = node.center; int globalLeft = node.left; int globalRight = node.right; int globalFront = node.front; int globalBack = node.back; int globalNeighbor(-1),localNeighbor(-1); if (node.isLocal) { real boundJacTerm(0.0); int offset = node.center-node.globalLow; int localNodeNumber = node.globalToLocal(nit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(nit->face) { case LEFT: { globalNeighbor = globalRight; localNeighbor = node.right; break; } case RIGHT: { globalNeighbor = globalLeft; localNeighbor = node.left; break; } case FRONT: { globalNeighbor = globalBack; localNeighbor = node.back; break; } case BACK: { globalNeighbor = globalFront; localNeighbor = node.front; boundJacTerm = D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][offset]; break; } }//end first switch for local //first get jacobian term for actual boundary cell //mwf now go back and center stencil on interior cell node.globalNode(globalNeighbor); int nl=node.center-node.globalLow; //use same sign convention for divergence as in regular res real signOfDiv(-1.0); real volume = hXcen[nl]*hYcen[nl]*fabs(detMap[nl]); //put in scaling here? signOfDiv *= scaling; volume *= scaling; real ypJac = volume*(rho[nl]*Dtheta[nl] + Drho[nl] * theta[nl]); real Daccum= volume*(rho[nl]*DDtheta[nl] + Drho[nl]*Dtheta[nl] + DDrho[nl]*theta[nl] + Drho[nl]*Dtheta[nl])* Dp[nl]; //go through and evaluate jacobian. The stencil is now centered //at interior neighbor DresDy(globalCenter,node.center) = Daccum + alphaBDF*ypJac + signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::CENTER][nl]; if (node.anchor->k > 0) DresDy(globalCenter,globalLeft) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT][nl]; if (node.anchor->k < node.nxNodes-1) DresDy(globalCenter,node.right) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT][nl]; if (DIM > 0) { if (node.anchor->j > 0) { DresDy(globalCenter,node.front)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]; std::cerr<<" in appNeu DresDy("<<globalCenter<<"," <<node.front<<")= "<<signOfDiv *D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]<<std::endl; //(j-1,k-1) if (node.anchor->k > 0) DresDy(globalCenter,node.leftFront)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_FRONT][nl]; //(j-1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(globalCenter,node.rightFront) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_FRONT][nl]; } if (node.anchor->j < node.nyNodes-1) { DresDy(globalCenter,node.back) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][nl]; std::cerr<<" in appNeu DresDy("<<globalCenter<<"," <<node.back<<")= "<<signOfDiv *D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]<<std::endl; //(j+1,k-1) if (node.anchor->k > 0) DresDy(globalCenter,node.leftBack)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_BACK][nl]; //(j+1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(globalCenter,node.rightBack) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_BACK][nl]; } }//end DIM==TWO_D if (DIM > 1) //DIM==THREE_D { if (node.anchor->i > 0) DresDy(globalCenter,node.bottom)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BOTTOM][nl]; if (node.anchor->i < node.nzNodes-1) DresDy(globalCenter,node.top) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::TOP][nl]; } DresDy(globalCenter,globalCenter) = signOfDiv*boundJacTerm; DresDy.finalizeRow(globalCenter); DresDy(globalNeighbor,globalCenter) = 0.0; //no dependence on actual boundary node? //how about zeroing neighbors instead? DresDy.finalizeRow(globalNeighbor); }//end isLocal ++nit; }//end while }//end function //========= mass conservative form //mwf now try and put in approx. using mass bal. only 2d for now template <int nv> inline void ConstBCECDM::applyNeumannConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& mCurrent, const Vec& betaDaeDef, const Vec& detMap, real alphaBDF, real scaling) { assert(nv == 1); assert(div); const Vec & flux_x = div->getFlux_x(0); const Vec & flux_y = div->getFlux_y(0); const Vec & hXcen = div->getSpatialIncrement(0); const Vec & hYcen = div->getSpatialIncrement(1); nit = neumann.begin(); while(nit != neumann.end()) { node.globalNode(nit->n); int globalCenter = node.center; if (node.isLocal) { int localNodeNumber = node.globalToLocal(nit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); //mwf this looks like it might be a problem real accumulation=alphaBDF*mCurrent(globalCenter) + betaDaeDef(2*globalCenter+1); switch(nit->face) { case LEFT: { //remember sign of normal for minus side //res(globalCenter) = (flux_x[node.interRight] + nit->value)*scaling; //hXcen should be zero I believe real volume = detMap(globalCenter)*hYcen[node.center] *0.5*(hXcen[node.center]+hXcen[node.right]); res(globalCenter) = volume*accumulation + flux_x[node.interRight] + nit->value; //mwf no scaling for now if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interRight<<"]= " <<flux_x[node.interRight]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case RIGHT: { // res(globalCenter) = (flux_x[node.interLeft] - nit->value)*scaling; //hXcen should be zero I believe real volume = detMap(globalCenter)*hYcen[node.center] *0.5*(hXcen[node.center]+hXcen[node.left]); res(globalCenter) = volume*accumulation - flux_x[node.interLeft] + nit->value; //mwf no scaling for now if (fabs(res(globalCenter)) > 1.0e4) { cerr<<"in ConstBCECDM::neumannBCsToRes, node.center= " <<node.center<<endl; cerr<<"\t flux_x["<<node.interLeft<<"]= " <<flux_x[node.interLeft]<<endl; cerr<<"\t scaling = "<<scaling<<" nit->value= "<<nit->value<<endl; } break; } case FRONT: { //remeber sign for negative boundary // res(globalCenter) = (flux_y[node.interBack] +nit->value)*scaling; //hYcen should be zero I believe real volume = detMap(globalCenter)*hXcen[node.center] *0.5*(hYcen[node.center]+hYcen[node.back]); res(globalCenter) = volume*accumulation + flux_y[node.interBack] + nit->value; //mwf no scaling for now // cout<<"FF"<<'\t'<<flux_y[node.interFront]<<'\t'<<nit->value <<'\t'<< flux_y[node.interBack]<<endl; break; } case BACK: { // res(globalCenter) = (flux_y[node.interFront] -nit->value)*scaling; //hYcen should be zero I believe real volume = detMap(globalCenter)*hXcen[node.center] *0.5*(hYcen[node.center]+hYcen[node.front]); res(globalCenter) = volume*accumulation - flux_y[node.interFront] + nit->value; //mwf no scaling for now // cout<<"FB"<<'\t'<<flux_y[node.interBack] <<'\t'<<nit->value<<'\t'<< flux_y[node.interFront]<<endl; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end if isLocal ++nit; } } template <class JAC, int nv> inline void ConstBCECDM::applyNeumannDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& D_Div, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, const Vec& rho, const Vec& theta, const Vec& Drho, const Vec& Dtheta, const Vec& detMap, real alphaBDF, real scaling) { const Vec & hXcen = div->getSpatialIncrement(0); const Vec & hYcen = div->getSpatialIncrement(1); nit = neumann.begin(); while(nit != neumann.end()) { real volume(1.0); node.globalNode(nit->n); int globalCenter = node.center; if (node.isLocal) { int localNodeNumber = node.globalToLocal(nit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(nit->face) { case LEFT: { volume = detMap(globalCenter)*hYcen[node.center] *0.5*(hXcen[node.center]+hXcen[node.right]); break; } case RIGHT: { volume = detMap(globalCenter)*hYcen[node.center] *0.5*(hXcen[node.center]+hXcen[node.left]); break; } case FRONT: { volume = detMap(globalCenter)*hXcen[node.center] *0.5*(hYcen[node.center]+hYcen[node.back]); break; } case BACK: { volume = detMap(globalCenter)*hXcen[node.center] *0.5*(hYcen[node.center]+hYcen[node.front]); break; } }//end first switch for local }//end first isLocal //mwf now go back through like usual node.globalNode(nit->n); int nl=node.center-node.globalLow; real signOfDiv(1.0); if (node.isLocal) { switch(nit->face) { case LEFT: { signOfDiv = -1.0; break; } case RIGHT: { signOfDiv = -1.0; break; } case FRONT: { signOfDiv = -1.0; break; } case BACK: { signOfDiv = -1.0; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<nit->face<<" not implemented"<<std::endl; exit (1); } }//end switch //mwf no scaling for now signOfDiv *= scaling; real ypJac = volume*(rho[nl]*Dtheta[nl] + Drho[nl] * theta[nl]); DresDy(node.center,node.center) = alphaBDF*ypJac + signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::CENTER][nl]; if (node.anchor->k > 0) DresDy(node.center,node.left) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT][nl]; if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.right) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT][nl]; if (DIM > 0) { if (node.anchor->j > 0) { DresDy(node.center,node.front)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]; //(j-1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftFront)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_FRONT][nl]; //(j-1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightFront) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_FRONT][nl]; } if (node.anchor->j < node.nyNodes-1) { DresDy(node.center,node.back) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][nl]; //(j+1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftBack)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_BACK][nl]; //(j+1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightBack) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_BACK][nl]; } }//end DIM==TWO_D if (DIM > 1) //DIM==THREE_D { if (node.anchor->i > 0) DresDy(node.center,node.bottom)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BOTTOM][nl]; if (node.anchor->i < node.nzNodes-1) DresDy(node.center,node.top) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::TOP][nl]; } DresDy.finalizeRow(node.center); }//end isLocal ++nit; }//end while }//end function //====================robbins=========================== //mwf I don't know yet what to do about robbins and interior bc's //as far as time integration goes inline void ConstBCECDM::applyRobbinsConditionsYprime(Petsc::StencilMM& node, Vec& yPrime) { ruit = robbins.begin(); while(ruit != robbins.end()) { node.globalNode(ruit->n); int globalCenter = node.center; if (node.isLocal) { yPrime(globalCenter) = 0.0; } ++ruit; } } //make global residual be dirMult*p + neuMult*fluxInterior-rVal template <int nv> inline void ConstBCECDM::applyRobbinsConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling) { assert(nv == 1); assert(div); const Vec & flux_x = div->getFlux_x(0); const Vec & flux_y = div->getFlux_y(0); ruit = robbins.begin(); while(ruit != robbins.end()) { node.globalNode(ruit->n); int globalCenter = node.center; real resTerm(0.0); if (node.isLocal) { //do dirichlet part first resTerm = (*ruit->var)(globalCenter)*(ruit->dirMult); int localNodeNumber = node.globalToLocal(ruit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); //now go through and get face values for neumann part switch(ruit->face) { case LEFT: { //using interior flux for the Dirichlet face //and zeroing the exterior flux //remember sign of normal for minus side resTerm -= (ruit->neuMult)*flux_x[node.interRight]; break; } case RIGHT: { resTerm += (ruit->neuMult)*flux_x[node.interLeft]; break; } case FRONT: { //remeber sign for negative boundary resTerm -= (ruit->neuMult)*flux_y[node.interBack]; break; } case BACK: { resTerm += (ruit->neuMult)*flux_y[node.interFront]; //if (globalCenter >= 1069 && globalCenter <= 1082) // { // std::cout<<"in BCrob value= "<<ruit->value // <<" flux_y["<<node.interFront<<"]= " // <<flux_y[node.interFront]<<" dirMult,neuMult= " // <<ruit->dirMult<<" "<<ruit->neuMult<<std::endl; // }//end if for debugging break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<ruit->face<<" not implemented"<<std::endl; exit (1); } }//end switch //now load in specified value res(globalCenter) = (resTerm - ruit->value)*scaling; }//end if isLocal ++ruit; } } //make global residual be dirMult*p + neuMult*fluxInterior-rVal template <class JAC> inline void ConstBCECDM::applyRobbinsDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& D_Div, int DIM, real scaling) { ruit = robbins.begin(); while(ruit != robbins.end()) { node.globalNode(ruit->n); int nl=node.center-node.globalLow; real signOfDiv(1.0); if (node.isLocal) { //do dirichlet part first real dirichletDeriv = (ruit->dirMult)*scaling; switch(ruit->face) { case LEFT: { signOfDiv = 1.0; break; } case RIGHT: { signOfDiv = 1.0; break; } case FRONT: { signOfDiv = 1.0; break; } case BACK: { signOfDiv = 1.0; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<ruit->face<<" not implemented"<<std::endl; exit (1); } }//end switch signOfDiv *= (ruit->neuMult)*scaling; DresDy(node.center,node.center) = dirichletDeriv + signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::CENTER][nl]; if (node.anchor->k > 0) DresDy(node.center,node.left) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT][nl]; if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.right) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT][nl]; if (DIM > 0) { if (node.anchor->j > 0) { DresDy(node.center,node.front)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]; //(j-1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftFront)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_FRONT][nl]; //(j-1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightFront) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_FRONT][nl]; } if (node.anchor->j < node.nyNodes-1) { DresDy(node.center,node.back) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][nl]; //(j+1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftBack)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_BACK][nl]; //(j+1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightBack) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_BACK][nl]; } }//end DIM==TWO_D if (DIM > 1) //DIM==THREE_D { if (node.anchor->i > 0) DresDy(node.center,node.bottom)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BOTTOM][nl]; if (node.anchor->i < node.nzNodes-1) DresDy(node.center,node.top) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::TOP][nl]; } DresDy.finalizeRow(node.center); }//end isLocal ++ruit; }//end while }//end function //====================no flow=========================== //mwf I don't know yet what to do about neumann bc's //as far as time integration goes inline void ConstBCECDM::applyNoFlowConditionsYprime(Petsc::StencilMM& node, Vec& yPrime) { noit = noflow.begin(); while(noit != noflow.end()) { node.globalNode(noit->n); int globalCenter = node.center; if (node.isLocal) { yPrime(globalCenter) = 0.0; } ++noit; } } //make global residual be dirMult*p + neuMult*fluxInterior-rVal template <int nv> inline void ConstBCECDM::applyNoFlowConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling) { assert(nv == 1); assert(div); noit = noflow.begin(); while(noit != noflow.end()) { node.globalNode(noit->n); int globalCenter = node.center; if (node.isLocal) { real fluxVal(0.0); int localNodeNumber = node.globalToLocal(noit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); //now go through and get face values for neumann part switch(noit->face) { case LEFT: { //using single phase flux for gradient //remember sign of normal for minus side fluxVal = div->getSinglePhaseFlux_xLeftBnd(); res(globalCenter)= (fluxVal + noit->value)*scaling; break; } case RIGHT: { fluxVal = div->getSinglePhaseFlux_xRightBnd(); res(globalCenter)= (fluxVal - noit->value)*scaling; break; } case FRONT: { //remeber sign for negative boundary fluxVal = div->getSinglePhaseFlux_yFrontBnd(); res(globalCenter)= (fluxVal + noit->value)*scaling; break; } case BACK: { fluxVal = div->getSinglePhaseFlux_yBackBnd(); res(globalCenter)= (fluxVal - noit->value)*scaling; break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<noit->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end if isLocal ++noit; }//end switch }//end function //make global residual be dirMult*p + neuMult*fluxInterior-rVal template <class JAC, int nv> inline void ConstBCECDM::applyNoFlowDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, DivKgradECDM<ConstBCECDM,nv>* div, int DIM, real scaling) { noit = noflow.begin(); while(noit != noflow.end()) { node.globalNode(noit->n); //int nl=node.center-node.globalLow; if (node.isLocal) { //save these for use with jacobian int globalCenter = node.center; int globalLeft = node.left; int globalRight = node.right; int globalFront = node.front; int globalBack = node.back; int globalLeftBack = node.leftBack; int globalRightBack = node.rightBack; int globalLeftFront = node.leftFront; int globalRightFront= node.rightFront; int globalBackLeft = node.leftBack; int globalBackRight = node.rightBack; int globalFrontLeft = node.leftFront; int globalFrontRight= node.rightFront; int localNodeNumber = node.globalToLocal(noit->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(noit->face) { case LEFT: { real DfluxVal(0.0); DfluxVal = div->getDSinglePhaseFlux_xLeftBnd_center(); DresDy(globalCenter,globalCenter) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_xLeftBnd_right(); DresDy(globalCenter,globalRight) = scaling*DfluxVal; if (DIM > 0) { DfluxVal = div->getDSinglePhaseFlux_xLeftBnd_rightBack(); DresDy(globalCenter,globalRightBack) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_xLeftBnd_rightFront(); DresDy(globalCenter,globalRightFront) = scaling*DfluxVal; } DresDy.finalizeRow(globalCenter); break; } case RIGHT: { real DfluxVal(0.0); DfluxVal = div->getDSinglePhaseFlux_xRightBnd_center(); DresDy(globalCenter,globalCenter) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_xRightBnd_left(); DresDy(globalCenter,globalLeft) = scaling*DfluxVal; if (DIM > 0) { DfluxVal = div->getDSinglePhaseFlux_xRightBnd_leftBack(); DresDy(globalCenter,globalLeftBack) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_xRightBnd_leftFront(); DresDy(globalCenter,globalLeftFront) = scaling*DfluxVal; } DresDy.finalizeRow(globalCenter); break; } case FRONT: { real DfluxVal(0.0); DfluxVal = div->getDSinglePhaseFlux_yFrontBnd_center(); DresDy(globalCenter,globalCenter) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yFrontBnd_back(); DresDy(globalCenter,globalBack) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yFrontBnd_backRight(); DresDy(globalCenter,globalBackRight) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yFrontBnd_backLeft(); DresDy(globalCenter,globalBackLeft) = scaling*DfluxVal; DresDy.finalizeRow(globalCenter); break; } case BACK: { real DfluxVal(0.0); DfluxVal = div->getDSinglePhaseFlux_yBackBnd_center(); DresDy(globalCenter,globalCenter) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yBackBnd_front(); DresDy(globalCenter,globalFront) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yBackBnd_frontRight(); DresDy(globalCenter,globalFrontRight) = scaling*DfluxVal; DfluxVal = div->getDSinglePhaseFlux_yBackBnd_frontLeft(); DresDy(globalCenter,globalFrontLeft) = scaling*DfluxVal; DresDy.finalizeRow(globalCenter); break; } default: { std::cerr<<"ConstBCECDM.h: Face Type "<<noit->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end if isLocal ++noit; }//end switch }//end function //====================interior=========================== //make global residual be fluxLeft-fluxRight template <int nv> inline void ConstBCECDM::applyInteriorConditionsToRes(Petsc::StencilMM& node, Vec& res, DivKgradECDM<ConstBCECDM,nv>* div, real scaling) { assert(nv == 1); assert(div); const Vec & flux_x = div->getFlux_x(0); const Vec & flux_y = div->getFlux_y(0); init = interior.begin(); //std::cout<<dit<<'\t'<<dirichlet.end()<<std::endl<<std::flush; while(init != interior.end()) { node.globalNode(init->n); int globalCenter = node.center; //mwf only set if node is local to this processor? if (node.isLocal) { int localNodeNumber = node.globalToLocal(init->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); switch(init->face) { case INTERIOR_X: { //right flux is headed in negative direction res(globalCenter) = (flux_x[node.interLeft] -flux_x[node.interRight])*scaling; break; } case INTERIOR_Y: { //right flux is headed in negative direction res(globalCenter) = (flux_y[node.interFront] -flux_y[node.interBack])*scaling; break; } default: { std::cerr<<"ConstBCECDM.h:Face Type "<<init->face<<" not implemented"<<std::endl; exit (1); } }//end switch }//end isLocal //cout<<"D"<<'t'<<res(node.center)<<'\t'<<(*dit->var)(node.center)<<'\t'<<dit->value<<endl; ++init; } //end init loop }//end function //make global residual be fluxInterior-qVal template <class JAC> inline void ConstBCECDM::applyInteriorDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, VecVec& D_Div, int DIM, real scaling) { init = interior.begin(); while(init != interior.end()) { node.globalNode(init->n); int nl=node.center-node.globalLow; real signOfDiv(1.0); signOfDiv *= scaling; if (node.isLocal) { DresDy(node.center,node.center) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::CENTER][nl]; if (node.anchor->k > 0) DresDy(node.center,node.left) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT][nl]; if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.right) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT][nl]; if (DIM > 0) { if (node.anchor->j > 0) { DresDy(node.center,node.front)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::FRONT][nl]; //(j-1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftFront)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_FRONT][nl]; //(j-1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightFront) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_FRONT][nl]; } if (node.anchor->j < node.nyNodes-1) { DresDy(node.center,node.back) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BACK][nl]; //(j+1,k-1) if (node.anchor->k > 0) DresDy(node.center,node.leftBack)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::LEFT_BACK][nl]; //(j+1,k+1) if (node.anchor->k < node.nxNodes-1) DresDy(node.center,node.rightBack) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::RIGHT_BACK][nl]; } }//end DIM==TWO_D if (DIM > 1) //DIM==THREE_D { if (node.anchor->i > 0) DresDy(node.center,node.bottom)= signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::BOTTOM][nl]; if (node.anchor->i < node.nzNodes-1) DresDy(node.center,node.top) = signOfDiv*D_Div[DivKgradECDM<ConstBCECDM,1>::TOP][nl]; }//end 3d DresDy.finalizeRow(node.center); }//end isLocal ++init; }//end while }//end function //this one updates derivatives straight into jacobian for left and right terms template <class JAC, int nv> inline void ConstBCECDM::updateInteriorDerivativesToRes(Petsc::StencilMM& node, JAC& DresDy, const VecVec* K, const Vec* Kr, const Vec* Rho, const Vec* P, const VecVecVec& DKr, const Vec* DRho, VecVec& D_Div, int DIM, DivKgradECDM<ConstBCECDM,nv>* div, real scaling) { init = interior.begin(); while(init != interior.end()) { node.globalNode(init->n); //int nl=node.center-node.globalLow; real signOfDiv(1.0); signOfDiv *= scaling; if (node.isLocal) { //save these for use with jacobian //int globalCenter = node.center; int globalLeft = node.left; int globalRight = node.right; int globalFront = node.front; int globalBack = node.back; int localNodeNumber = node.globalToLocal(init->n); //mwf this needs to set flux indexes now node.localNode(localNodeNumber); //set jacobian for neighbors on //either side of interface. They each need an extra //term to express dependence of rel perm coefficient //on neighbors //this goes into the equations for the left and right neighbors //or the back and front (Y) if (init->face == INTERIOR_X) { real fluxDeriv(0.0); int face(0); //interface coefficient is upwind(Kr_{left},Kr_{right})* //1/2(rho_{left}+rho_{right}) //from the right //flux gets used as left flux in right mass eqn face = 1; fluxDeriv = div->getInteriorFluxDerivTerm_x(face); //only way get this derivative DresDy(globalRight,globalLeft) = -fluxDeriv; DresDy.finalizeRow(globalRight); //from the left face = -1; //flux gets used as right flux in right mass eqn fluxDeriv = div->getInteriorFluxDerivTerm_x(face); DresDy(globalLeft,globalRight) = fluxDeriv; DresDy.finalizeRow(globalLeft); }//end x face if (init->face == INTERIOR_Y) { //set boundary values with div routine, don't use rel perm or density //since they're continuous anyway real fluxDeriv(0.0); int face(0); //interface coefficient is upwind(Kr_{back},Kr_{front})* //1/2(rho_{back}+rho_{front}) //from the back //flux gets used as front flux in back mass eqn face = 1; fluxDeriv = div->getInteriorFluxDerivTerm_y(face); DresDy(globalBack,globalFront) = -fluxDeriv; DresDy.finalizeRow(globalBack); //from the front face = -1; fluxDeriv = div->getInteriorFluxDerivTerm_y(face); DresDy(globalFront,globalBack) = fluxDeriv; DresDy.finalizeRow(globalFront); }//end Y face }//end isLocal ++init; }//end while }//end function //mwf I don't know yet what to do about neumann and interior bc's //as far as time integration goes inline void ConstBCECDM::applyInteriorConditionsYprime(Petsc::StencilMM& node, Vec& yPrime) { init = interior.begin(); while(init != interior.end()) { node.globalNode(init->n); int globalCenter = node.center; if (node.isLocal) { yPrime(globalCenter) = 0.0; } ++init; } } ////////////////////// //mwf now I have to use the stupid STL algorithms I guess template <class BcType> class BCnodeIsTheSame { public: typedef typename std::vector<BcType>::iterator first_argument_type ; typedef int second_argument_type ; typedef bool result_type ; BCnodeIsTheSame(int num = 0):gnum(num) {} bool operator()(BcType& iterVal) { return iterVal.n == gnum; } int gnum; }; }//Daetk #endif
medsec/kiasubc
kiasu/test-kiasu.cpp
<filename>kiasu/test-kiasu.cpp // =================================================================== // @last-modified 2016-06-01 // This is free and unencumbered software released into the public domain. // =================================================================== #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include "kiasu.h" // --------------------------------------------------------------------- // Printing // --------------------------------------------------------------------- static void print_hex(const char label[], const uint8_t* x, const size_t n) { printf("%s ", label); for (size_t i = 0; i < n; ++i) { printf("%02x", x[i]); } puts(""); } // --------------------------------------------------------------------- static void print_block(const char label[], const uint8_t* x) { print_hex(label, x, KIASU_BLOCKLEN); } // --------------------------------------------------------------------- // Tests // --------------------------------------------------------------------- static void run_tests(const size_t num_texts, const block k, const block* expected_p, const block* tweaks, const block* expected_c) { kiasu_ctx ctx; kiasu_key_setup(&ctx, k); int num_errors = 0; for (size_t i = 0; i < num_texts; ++i) { block c; kiasu_encrypt(&ctx, c, expected_p[i], tweaks[i], KIASU_ROUNDS); if (memcmp(expected_c[i], c, KIASU_BLOCKLEN)) { printf("Kiasu encryption test %zu failed\n", i); print_block("Expected", expected_c[i]); print_block("But was ", c); num_errors++; } } printf("%zu/%zu encryption tests correct\n", num_texts-num_errors, num_texts); num_errors = 0; for (size_t i = 0; i < num_texts; ++i) { block p; kiasu_decrypt(&ctx, p, expected_c[i], tweaks[i], KIASU_ROUNDS); if (memcmp(expected_p[i], p, KIASU_BLOCKLEN)) { printf("Kiasu decryption test %zu failed\n", i); print_block("Expected", expected_p[i]); print_block("But was ", p); num_errors++; } } printf("%zu/%zu decryption tests correct\n", num_texts-num_errors, num_texts); } // --------------------------------------------------------------------- static void test_kiasu() { const block k = { 0x7d, 0x89, 0x55, 0x51, 0xa4, 0x5f, 0xa7, 0xce, 0x80, 0x25, 0x56, 0xe5, 0xff, 0x76, 0xf1, 0xcf }; #define NUM_KIASU_TEST_TEXTS 4 const block expected_p[NUM_KIASU_TEST_TEXTS] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, { 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE }, { 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0 } }; const block expected_c[NUM_KIASU_TEST_TEXTS] = { { 0xec, 0x7a, 0xfc, 0xce, 0x2b, 0x21, 0x39, 0xee, 0x82, 0x10, 0xda, 0x8f, 0x51, 0x98, 0xcb, 0x60 }, { 0x21, 0xf4, 0x95, 0x6a, 0x44, 0x88, 0x54, 0xe8, 0x4c, 0x64, 0xf4, 0x42, 0xbb, 0x98, 0x41, 0xd5 }, { 0x41, 0x12, 0xa0, 0xe7, 0x1d, 0x22, 0x4e, 0xa0, 0x9e, 0x6e, 0x60, 0xa6, 0x16, 0xec, 0xfe, 0x50 }, { 0xe2, 0x9e, 0xbd, 0x96, 0x38, 0x5b, 0x32, 0xf9, 0x8e, 0xdb, 0xeb, 0xc8, 0x24, 0xc5, 0x63, 0x83 } }; const block tweaks[NUM_KIASU_TEST_TEXTS] = { { 0xe3, 0x23, 0x00, 0x00, 0xe0, 0x11, 0x00, 0x00, 0x84, 0x6d, 0x00, 0x00, 0x6f, 0x87, 0x00, 0x00 }, { 0xe3, 0x23, 0x00, 0x00, 0xe0, 0x11, 0x00, 0x00, 0x84, 0x6d, 0x00, 0x00, 0x6f, 0x87, 0x00, 0x00 }, { 0xe3, 0x23, 0x00, 0x00, 0xe0, 0x11, 0x00, 0x00, 0x84, 0x6d, 0x00, 0x00, 0x6f, 0x87, 0x00, 0x00 }, { 0xe3, 0x23, 0x00, 0x00, 0xe0, 0x11, 0x00, 0x00, 0x84, 0x6d, 0x00, 0x00, 0x6f, 0x87, 0x00, 0x00 } }; run_tests(NUM_KIASU_TEST_TEXTS, k, expected_p, tweaks, expected_c); #undef NUM_KIASU_TEST_TEXTS } // --------------------------------------------------------------------- int main() { test_kiasu(); return 0; }
cmarshall108/panda3d-python3
panda/src/device/dialNode.cxx
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file dialNode.cxx * @author drose * @date 2002-03-12 */ #include "dialNode.h" #include "config_device.h" #include "dataNodeTransmit.h" #include "dcast.h" TypeHandle DialNode::_type_handle; /** * */ DialNode:: DialNode(ClientBase *client, const std::string &device_name) : DataNode(device_name) { nassertv(client != nullptr); PT(ClientDevice) device = client->get_device(ClientDialDevice::get_class_type(), device_name); if (device == nullptr) { device_cat.warning() << "Unable to open dial device " << device_name << "\n"; return; } if (!device->is_of_type(ClientDialDevice::get_class_type())) { device_cat.error() << "Inappropriate device type " << device->get_type() << " created; expected a ClientDialDevice.\n"; return; } _dial = DCAST(ClientDialDevice, device); } /** * */ DialNode:: ~DialNode() { // When the _dial pointer destructs, the ClientDialDevice disconnects itself // from the ClientBase, and everything that needs to get turned off does. // Magic. } /** * The virtual implementation of transmit_data(). This function receives an * array of input parameters and should generate an array of output * parameters. The input parameters may be accessed with the index numbers * returned by the define_input() calls that were made earlier (presumably in * the constructor); likewise, the output parameters should be set with the * index numbers returned by the define_output() calls. */ void DialNode:: do_transmit_data(DataGraphTraverser *, const DataNodeTransmit &, DataNodeTransmit &output) { if (is_valid()) { _dial->poll(); // Not clear yet what we should be transmitting. } }
th3n3rd/micronaut-microservices-poc
agent-portal-gateway/src/main/java/pl/altkom/asc/lab/micronaut/poc/gateway/client/v1/DocumentsGatewayClient.java
<gh_stars>100-1000 package pl.altkom.asc.lab.micronaut.poc.gateway.client.v1; import io.micronaut.http.client.annotation.Client; import io.micronaut.retry.annotation.Retryable; import pl.altkom.asc.lab.micronaut.poc.documents.api.DocumentsOperations; import pl.altkom.asc.lab.micronaut.poc.documents.api.queries.finddocuments.FindDocumentsResult; @Client(id = "documents-service", path = "/documents") @Retryable(attempts = "2", delay = "2s") public interface DocumentsGatewayClient extends DocumentsOperations { @Override FindDocumentsResult find(String policyNumber); }
nayotta/metathings
pkg/plugin/mosquitto/service/service.go
<filename>pkg/plugin/mosquitto/service/service.go package metathings_mosquitto_plugin_service import ( "io/ioutil" "net/http" "time" log "github.com/sirupsen/logrus" passwd_helper "github.com/nayotta/metathings/pkg/common/passwd" webhook_helper "github.com/nayotta/metathings/pkg/common/webhook" storage "github.com/nayotta/metathings/pkg/plugin/mosquitto/storage" ) var ( WEBHOOK_HMAC_TIMESTAMP, _ = time.Parse(time.RFC3339, "2019-01-01T00:00:00Z") WEBHOOK_HMAC_TIMESTAMP_INT64 = int64(1546300800000000000) // WEBHOOK_HMAC_TIMESTAMP.UnixNano() WEBHOOK_HMAC_NONCE = int64(1024) ) func ParseMosquittoPluginPassword(id, secret string) string { return passwd_helper.MustParseHmac(secret, id, WEBHOOK_HMAC_TIMESTAMP, WEBHOOK_HMAC_NONCE) } type MosquittoPluginServiceOption struct { Webhook struct { Secret string } } type MosquittoPluginService struct { logger log.FieldLogger opt *MosquittoPluginServiceOption storage storage.Storage } func (s *MosquittoPluginService) get_logger() log.FieldLogger { return s.logger } func (s *MosquittoPluginService) WebhookHandler(w http.ResponseWriter, r *http.Request) { if !webhook_helper.ValidateHmac(s.opt.Webhook.Secret, r) { s.get_logger().Warningf("failed to validate hmac") return } buf, err := ioutil.ReadAll(r.Body) if err != nil { s.get_logger().WithError(err).Debugf("failed to read request body") return } evt, err := webhook_helper.UnmarshalEvent(buf) if err != nil { s.get_logger().WithError(err).Debugf("bad webhook format") return } act := evt.GetString("action") if act == "" { s.get_logger().WithField("action", act).Warningf("unexpected action") return } logger := s.get_logger().WithField("action", act) switch act { case "create_credential": err = s.handle_create_credential_event(evt) case "delete_credential": err = s.handle_delete_credential_event(evt) } if err != nil { logger.WithError(err).Errorf("failed to handle event") return } } func (s *MosquittoPluginService) handle_create_credential_event(evt *webhook_helper.Event) error { id := evt.GetString("credential.id") if id == "" { s.get_logger().Warningf("invaild argument: credential.id") return ErrBadRequest } secret := evt.GetString("credential.secret") if secret == "" { s.get_logger().Warningf("invalid argument: credential.secret") return ErrBadRequest } logger := s.get_logger().WithField("username", id) hmac := ParseMosquittoPluginPassword(id, secret) passwd := passwd_helper.MustParsePbkdf2(hmac) topic := "mt/#" mask := "rw" usr := &storage.User{ Username: &id, Password: &<PASSWORD>, Permissions: []*storage.Permission{ { Topic: &topic, Mask: &mask, }, }, } err := s.storage.AddUser(usr) if err != nil { logger.Errorf("failed to add user in storage") return err } logger.Debugf("handle create credential event") return nil } func (s *MosquittoPluginService) handle_delete_credential_event(evt *webhook_helper.Event) error { id := evt.GetString("credential.id") if id == "" { s.get_logger().Warningf("invaild argument: crednetial.id") return ErrBadRequest } logger := s.get_logger().WithField("username", id) err := s.storage.RemoveUser(id) if err != nil { logger.Errorf("failed to remove user in storage") return err } logger.Debugf("handle delete credential event") return nil } func NewMosquittoPluginService( opt *MosquittoPluginServiceOption, logger log.FieldLogger, storage storage.Storage, ) (*MosquittoPluginService, error) { return &MosquittoPluginService{ opt: opt, logger: logger, storage: storage, }, nil }
carsonkk/carsonkk.com
src/utils/Date.js
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] function TZDate(date) { const dateObj = new Date(date) const offset = -60000; return new Date(dateObj.getTime() - dateObj.getTimezoneOffset() * offset) } function DayOrdinal(n) { return n + (n > 0 ? ['th', 'st', 'nd', 'rd'][(n > 3 && n < 21) || n % 10 > 3 ? 0 : n % 10] : ''); } export function FancyDateMDY(date) { const fancyDate = TZDate(date) return `${months[fancyDate.getMonth()]} ${DayOrdinal(fancyDate.getDate())}, ${fancyDate.getFullYear()}` } export function FancyDateMD(date) { const fancyDate = TZDate(date) return `${months[fancyDate.getMonth()]} ${DayOrdinal(fancyDate.getDate())}` }
zc806zc/zStudio
form/src/main/java/com/zte/iui/layoutit/bean/JsonFileDesc.java
package com.zte.iui.layoutit.bean; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class JsonFileDesc { private List<JsonFile> list = new ArrayList<JsonFileDesc.JsonFile>(); /** * * @param path * @param moduleName * @return */ public JsonFile generateJsonFile(String path, String moduleName) { JsonFile desc = new JsonFile(); desc.setModuleName(moduleName); desc.setPath(path); return desc; } public void addFile(JsonFile jsonFile) { list.add(jsonFile); } @XmlRootElement class JsonFile { private String path = null; private String moduleName = null; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } } }
a4-data/a4-UI-EXT
packages/ext-web-components-kitchensink/src/view/components/forms/textfield/TextFieldComponent.js
import './TextFieldComponent.html'; export default class TextFieldComponent {}
dewf/opendl
source/win-direct2d/classes/CG/CGPath.cpp
<gh_stars>10-100 #include "CGPath.h"
Frontline-Processing/winprom
winprom/TreeFilter_dlg.cpp
<reponame>Frontline-Processing/winprom // WinProm Copyright 2015 <NAME> // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // TreeFilter_dlg.cpp : implementation file // #include "stdafx.h" #include "winprom.h" #include "TreeFilter_dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif bool TreeFilter::test(const Domain& dom, const Database& data, const CPromDoc *doc) const { short int dc=doc->drain_const(); return peak_ff.test(dom.peak,data) && (!dom.parent.line || dom.peak_topo_prom()>min_prom && sadl_ff.test(dom.parent.saddle->saddle,data)); } ///////////////////////////////////////////////////////////////////////////// // CTreeFilter_dlg dialog CTreeFilter_dlg::CTreeFilter_dlg(TreeFilter& tf, const CPromDoc& d, CWnd *pParent) : CDialog(CTreeFilter_dlg::IDD,pParent),filter(tf),doc(d) { //{{AFX_DATA_INIT(CTreeFilter_dlg) m_min_prom = 0; m_pp_hp_max = 0; m_pp_hp_min = 0; m_pp_filter = FALSE; m_pp_sort = FALSE; m_pp_enable = FALSE; m_pp_child_worst = 0; m_pp_child_best = 0; m_topology = -1; m_runoffs = -1; m_sort_children = -1; //}}AFX_DATA_INIT } void CTreeFilter_dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTreeFilter_dlg) DDX_Control(pDX, IDC_PP_CHILD_WORST, m_pp_child_worst_ctl); DDX_Control(pDX, IDC_PP_CHILD_BEST, m_pp_child_best_ctl); DDX_Text(pDX, IDC_MIN_PROM, m_min_prom); DDX_Text(pDX, IDC_PP_HP_MAX, m_pp_hp_max); DDX_Text(pDX, IDC_PP_HP_MIN, m_pp_hp_min); DDX_Check(pDX, IDC_PP_FILTER, m_pp_filter); DDX_Check(pDX, IDC_PP_SORT, m_pp_sort); DDX_Check(pDX, IDC_PP_ENABLE, m_pp_enable); DDX_Text(pDX, IDC_PP_CHILD_WORST, m_pp_child_worst); DDX_Text(pDX, IDC_PP_CHILD_BEST, m_pp_child_best); DDX_Radio(pDX, IDC_LINE, m_topology); DDX_Radio(pDX, IDC_LRO_NONE, m_runoffs); DDX_Radio(pDX, IDC_SC_PROM, m_sort_children); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_SC_PEAK, m_peak_elev); } BEGIN_MESSAGE_MAP(CTreeFilter_dlg, CDialog) //{{AFX_MSG_MAP(CTreeFilter_dlg) ON_BN_CLICKED(IDC_PEAK_FILTER, OnPeakFilter) ON_BN_CLICKED(IDC_SADL_FILTER, OnSadlFilter) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTreeFilter_dlg message handlers BOOL CTreeFilter_dlg::OnInitDialog() { m_min_prom=filter.min_prom; m_peak_ff=filter.peak_ff; m_sadl_ff=filter.sadl_ff; m_peak_ff.rec_filter.align(doc.data); m_sadl_ff.rec_filter.align(doc.data); m_topology=filter.topology-1; m_runoffs=filter.runoffs; m_pp_enable=filter.pp_enable; m_pp_filter=filter.pp_filter; m_pp_sort=filter.pp_sort; m_pp_hp_min=filter.pp_patrch_prom.low; m_pp_hp_max=filter.pp_patrch_prom.high; m_pp_child_best=filter.pp_child_best; m_pp_child_worst=filter.pp_child_worst; m_sort_children=filter.child_sorting; CDialog::OnInitDialog(); SetIcon(AfxGetApp()->LoadIcon(IDR_LPR_TREE),TRUE); m_peak_elev.SetWindowText(doc.is_drainage?"Basin elevation":"Peak elevation"); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CTreeFilter_dlg::OnOK() { if (!UpdateData(TRUE)) return; if (m_pp_hp_min>m_pp_hp_max) { MessageBox("For patriarch proportional prominence,\n" "the high value must be >= the low value.", "Winprom Entry Error",MB_OK|MB_ICONERROR); return; } if (m_pp_child_best>m_pp_hp_max || m_pp_child_best<m_pp_hp_min) { MessageBox("The \"best for child\" proportional prominence of the patriarch\n" "must be within the patriarch's proportional prominence range.", "Winprom Entry Error",MB_OK|MB_ICONERROR); m_pp_child_best_ctl.SetFocus(); m_pp_child_best_ctl.SetSel(0,-1); return; } if (m_pp_child_worst>m_pp_hp_max || m_pp_child_worst<m_pp_hp_min) { MessageBox("The \"worst for child\" proportional prominence of the patriarch\n" "must be within the patriarch's proportional prominence range.", "Winprom Entry Error",MB_OK|MB_ICONERROR); m_pp_child_worst_ctl.SetFocus(); m_pp_child_worst_ctl.SetSel(0,-1); return; } filter.min_prom=m_min_prom; filter.peak_ff=m_peak_ff; filter.sadl_ff=m_sadl_ff; filter.topology=(Domain::Topology)(m_topology+1); filter.runoffs=(TreeFilter::List_runoffs)m_runoffs; filter.pp_enable=m_pp_enable!=FALSE; filter.pp_filter=m_pp_filter!=FALSE; filter.pp_sort=m_pp_sort!=FALSE; filter.pp_patrch_prom.low=m_pp_hp_min; filter.pp_patrch_prom.high=m_pp_hp_max; filter.pp_child_best=m_pp_child_best; filter.pp_child_worst=m_pp_child_worst; filter.child_sorting=(TreeFilter::Child_sorting)m_sort_children; CDialog::EndDialog(IDOK); } void CTreeFilter_dlg::OnPeakFilter() { CFeatureFilter_dlg(m_peak_ff,this).DoModal(); } void CTreeFilter_dlg::OnSadlFilter() { CFeatureFilter_dlg(m_sadl_ff,this).DoModal(); }
serpis/pynik
plugins/roulette.py
<gh_stars>1-10 # -*- coding: utf-8 -*- # Plugin created by Merola import random from commands import Command class RussianRoulette(Command): revolver_contents = {} usage = "Usage: .roulette reload | .roulette play" def __init__(self): pass def reload_revolver(self, channel): self.revolver_contents[channel] = [False, False, False, False, False, False] self.revolver_contents[channel][random.randint(0, 5)] = True return "Spinning the cylinder..." def pull_trigger(self, ircbot, nickname, channel): contents = self.revolver_contents.get(channel, []) if not contents: return "Maybe it's time to reload..." elif contents.pop(): kick_command = "KICK %s %s BOOM!" % (channel, nickname) ircbot.send(kick_command) return "Poor %s :(" % nickname else: return "You survive, you lucky bastard!" def trig_roulette(self, bot, source, target, trigger, argument): """Russian roulette, IRC style - Will you survive, or be kicked?""" argument = argument.strip().lower() # Show usage if not argument: return "Russian roulette! " + self.usage # Play elif argument == 'play': return self.pull_trigger(bot, source, target) # Reload elif argument == 'reload': return self.reload_revolver(target) # Unknown subcommand else: return "Unknown subcommand! " + self.usage
liqiqing/ZJSDK
ZJSDK/ZJAdSDK/ZJSDKCore.framework/Headers/ZJNativeAdView.h
// // ZJNativeAdView.h // ZJSDKCore // // Created by Rare on 2021/3/29. // #import <UIKit/UIKit.h> #import "ZJNativeAdObject.h" NS_ASSUME_NONNULL_BEGIN @class ZJNativeAdView; @protocol ZJNativeAdViewDelegate <NSObject> @optional //广告曝光回调 -(void)zj_nativeAdViewWillExpose:(ZJNativeAdView *)nativeAdView; //广告点击回调 -(void)zj_nativeAdViewDidClick:(ZJNativeAdView *)nativeAdView; //广告详情页关闭回调 -(void)zj_nativeAdDetailViewClosed:(ZJNativeAdView *)nativeAdView; //广告详情页面即将展示回调 -(void)zj_nativeAdDetailViewWillPresentScreen:(ZJNativeAdView *)nativeAdView; @end @interface ZJNativeAdView : UIView /** 广告 View 时间回调对象 */ @property (nonatomic, weak) id <ZJNativeAdViewDelegate> delegate; /* * viewControllerForPresentingModalView * 详解:开发者需传入用来弹出目标页的ViewController,一般为当前ViewController */ @property (nonatomic, weak) UIViewController *viewController; /** 视频广告的媒体View,绑定数据对象后自动生成,可自定义布局 */ @property (nonatomic, strong) UIView *videoAdView; /** logoView,绑定数据对象后自动生成,可自定义布局 */ @property (nonatomic, strong, readonly) UIView *logoView; /** 自渲染2.0视图注册方法 @param dataObject 数据对象,必传字段 */ - (void)registerDataObject:(ZJNativeAdObject *)dataObject; /** 注册可点击的callToAction视图的方法 建议开发者使用ZJNativeAdObject中的callToAction字段来创建视图,并取代自定义的下载或打开等button, 调用此方法之前必须先调用registerDataObject:clickableViews @param callToActionView CTA视图, 系统自动处理点击事件 */ - (void)registerClickableCallToActionView:(UIView *)callToActionView; /** 注销数据对象,在 tableView、collectionView 等场景需要复用 GDTUnifiedNativeAdView 时, 需要在合适的时机,例如 cell 的 prepareForReuse 方法内执行 unregisterDataObject 方法, 将广告对象与 ZJNativeAdView 解绑 */ - (void)unregisterDataObject; @end NS_ASSUME_NONNULL_END
silenc3502/MYSQL-Arch-Doc-Summary
mysql-server/plugin/group_replication/libmysqlgcs/src/bindings/xcom/gcs_xcom_group_member_information.cc
<reponame>silenc3502/MYSQL-Arch-Doc-Summary<gh_stars>0 /* Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "plugin/group_replication/libmysqlgcs/src/bindings/xcom/gcs_xcom_group_member_information.h" #include <assert.h> #include <cstdlib> #include <cstring> #include <sstream> #include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/gcs_logging_system.h" #include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/xplatform/byteorder.h" #include "plugin/group_replication/libmysqlgcs/include/mysql/gcs/xplatform/my_xp_util.h" #include "plugin/group_replication/libmysqlgcs/src/bindings/xcom/gcs_xcom_proxy.h" #include "plugin/group_replication/libmysqlgcs/src/bindings/xcom/xcom/synode_no.h" Gcs_xcom_node_address::Gcs_xcom_node_address(std::string member_address) : m_member_address(member_address), m_member_ip(), m_member_port(0) { char address[IP_MAX_SIZE]; xcom_port port; int error = get_ip_and_port(const_cast<char *>(member_address.c_str()), address, &port); if (!error) { m_member_ip.append(address); m_member_port = port; } } std::string &Gcs_xcom_node_address::get_member_address() { return m_member_address; } std::string &Gcs_xcom_node_address::get_member_ip() { return m_member_ip; } xcom_port Gcs_xcom_node_address::get_member_port() { return m_member_port; } std::string *Gcs_xcom_node_address::get_member_representation() const { return new std::string(m_member_address); } bool Gcs_xcom_node_address::is_valid() const { return !m_member_ip.empty() && m_member_port != 0; } Gcs_xcom_node_address::~Gcs_xcom_node_address() {} Gcs_xcom_node_information::Gcs_xcom_node_information( const std::string &member_id, bool alive) : m_member_id(member_id), m_uuid(Gcs_xcom_uuid::create_uuid()), m_node_no(VOID_NODE_NO), m_alive(alive), m_member(false), m_suspicion_creation_timestamp(0), m_lost_messages(false), m_max_synode(null_synode) {} Gcs_xcom_node_information::Gcs_xcom_node_information( const std::string &member_id, const Gcs_xcom_uuid &uuid, const unsigned int node_no, const bool alive) : m_member_id(member_id), m_uuid(uuid), m_node_no(node_no), m_alive(alive), m_member(false), m_suspicion_creation_timestamp(0), m_lost_messages(false), m_max_synode(null_synode) {} void Gcs_xcom_node_information::set_suspicion_creation_timestamp(uint64_t ts) { m_suspicion_creation_timestamp = ts; } /* purecov: begin tested */ uint64_t Gcs_xcom_node_information::get_suspicion_creation_timestamp() const { return m_suspicion_creation_timestamp; } /* purecov: end */ const Gcs_member_identifier &Gcs_xcom_node_information::get_member_id() const { return m_member_id; } const Gcs_xcom_uuid &Gcs_xcom_node_information::get_member_uuid() const { return m_uuid; } void Gcs_xcom_node_information::regenerate_member_uuid() { m_uuid = Gcs_xcom_uuid::create_uuid(); } /* purecov: begin tested */ void Gcs_xcom_node_information::set_node_no(unsigned int node_no) { m_node_no = node_no; } /* purecov: end */ unsigned int Gcs_xcom_node_information::get_node_no() const { return m_node_no; } bool Gcs_xcom_node_information::is_alive() const { return m_alive; } bool Gcs_xcom_node_information::is_member() const { return m_member; } void Gcs_xcom_node_information::set_member(bool m) { m_member = m; } std::pair<bool, node_address *> Gcs_xcom_node_information::make_xcom_identity( Gcs_xcom_proxy &xcom_proxy) const { bool constexpr kError = true; bool constexpr kSuccess = false; bool error_code = kError; node_address *xcom_identity = nullptr; /* Get our unique XCom identifier to pass it along to XCom. */ // Address. const std::string &address_str = get_member_id().get_member_id(); char *address[] = {const_cast<char *>(address_str.c_str())}; // Incarnation. bool error_creating_blob; blob incarnation_blob; std::tie(error_creating_blob, incarnation_blob) = get_member_uuid().make_xcom_blob(); if (!error_creating_blob) { blob incarnation[] = {incarnation_blob}; xcom_identity = xcom_proxy.new_node_address_uuid(1, address, incarnation); std::free(incarnation_blob.data.data_val); error_code = kSuccess; } return {error_code, xcom_identity}; } bool Gcs_xcom_node_information::has_timed_out(uint64_t now_ts, uint64_t timeout) { return (m_suspicion_creation_timestamp + timeout) < now_ts; } bool Gcs_xcom_node_information::has_lost_messages() const { return m_lost_messages; } void Gcs_xcom_node_information::set_lost_messages(bool lost_msgs) { m_lost_messages = lost_msgs; } synode_no Gcs_xcom_node_information::get_max_synode() const { return m_max_synode; } void Gcs_xcom_node_information::set_max_synode(synode_no synode) { m_max_synode = synode; } Gcs_xcom_uuid Gcs_xcom_uuid::create_uuid() { Gcs_xcom_uuid uuid; std::ostringstream ss; /* Although it is possible to have collisions if different nodes create the same UUID, this is not a problem because the UUID is only used to distinguish two situations: . whether someone is trying to remove a newer node's incarnation. . whether a new node's incarnation is trying to rejoin a group when there are still references to its old incarnation. So although there might be collissions, this is not a problem because the actual node's identification is the combination of address and UUID. Note that, whatever the UUID is, we have to guarantee that successive node's incarnation don't have the same UUID. Our current solution uses a simple timestamp which is safe because it is very unlikely that the same node will be able to join, fail/leave and rejoin again and will keep the same uuid. In the future, we can start generating real UUIDs if we need them for any reason. The server already has the code to do it, so we could make this an option and pass the information to GCS. */ uint64_t value = My_xp_util::getsystime(); ss << value; uuid.actual_value = ss.str(); return uuid; } bool Gcs_xcom_uuid::encode(uchar **buffer, unsigned int *size) const { if (buffer == nullptr || *buffer == nullptr || size == nullptr) { /* purecov: begin tested */ return false; /* purecov: end */ } memcpy(*buffer, actual_value.c_str(), actual_value.size()); *size = actual_value.size(); return true; } bool Gcs_xcom_uuid::decode(const uchar *buffer, const unsigned int size) { if (buffer == nullptr) { /* purecov: begin tested */ return false; /* purecov: end */ } actual_value = std::string(reinterpret_cast<const char *>(buffer), static_cast<size_t>(size)); return true; } std::pair<bool, blob> Gcs_xcom_uuid::make_xcom_blob() const { bool constexpr kError = true; bool constexpr kSuccess = false; bool error_code = kError; blob incarnation; incarnation.data.data_len = actual_value.size(); incarnation.data.data_val = reinterpret_cast<char *>(std::malloc(incarnation.data.data_len)); if (incarnation.data.data_val == nullptr) goto end; encode(reinterpret_cast<uchar **>(&incarnation.data.data_val), &incarnation.data.data_len); error_code = kSuccess; end: return {error_code, incarnation}; } Gcs_xcom_nodes::Gcs_xcom_nodes() : m_node_no(VOID_NODE_NO), m_nodes(), m_size(0), m_addrs(nullptr), m_uuids(nullptr) {} Gcs_xcom_nodes::Gcs_xcom_nodes(const site_def *site, node_set &nodes) : m_node_no(site->nodeno), m_nodes(), m_size(nodes.node_set_len), m_addrs(nullptr), m_uuids(nullptr) { Gcs_xcom_uuid uuid; for (unsigned int i = 0; i < nodes.node_set_len; ++i) { /* Get member address and save it. */ std::string address(site->nodes.node_list_val[i].address); /* Get member uuid and save it. */ uuid.decode(reinterpret_cast<uchar *>( site->nodes.node_list_val[i].uuid.data.data_val), site->nodes.node_list_val[i].uuid.data.data_len); /* Get member status and save it */ bool alive = nodes.node_set_val[i] ? true : false; Gcs_xcom_node_information node(address, uuid, i, alive); m_nodes.push_back(node); } assert(m_size == m_nodes.size()); } Gcs_xcom_nodes::~Gcs_xcom_nodes() { free_encode(); } /* purecov: begin tested */ void Gcs_xcom_nodes::set_node_no(unsigned int node_no) { m_node_no = node_no; } /* purecov: end */ /* purecov: begin tested */ unsigned int Gcs_xcom_nodes::get_node_no() const { return m_node_no; } /* purecov: end */ const std::vector<Gcs_xcom_node_information> &Gcs_xcom_nodes::get_nodes() const { return m_nodes; } const Gcs_xcom_node_information *Gcs_xcom_nodes::get_node( const Gcs_member_identifier &member_id) const { return get_node(member_id.get_member_id()); } const Gcs_xcom_node_information *Gcs_xcom_nodes::get_node( const std::string &member_id) const { std::vector<Gcs_xcom_node_information>::const_iterator nodes_it; for (nodes_it = m_nodes.begin(); nodes_it != m_nodes.end(); ++nodes_it) { if ((*nodes_it).get_member_id().get_member_id() == member_id) return &(*nodes_it); } return nullptr; } const Gcs_xcom_node_information *Gcs_xcom_nodes::get_node( unsigned int node_no) const { std::vector<Gcs_xcom_node_information>::const_iterator nodes_it; for (nodes_it = m_nodes.begin(); nodes_it != m_nodes.end(); ++nodes_it) { if ((*nodes_it).get_node_no() == node_no) return &(*nodes_it); } return nullptr; /* purecov: tested */ } /* purecov: begin tested */ const Gcs_xcom_node_information *Gcs_xcom_nodes::get_node( const Gcs_xcom_uuid &uuid) const { std::vector<Gcs_xcom_node_information>::const_iterator nodes_it; for (nodes_it = m_nodes.begin(); nodes_it != m_nodes.end(); ++nodes_it) { if ((*nodes_it).get_member_uuid().actual_value == uuid.actual_value) return &(*nodes_it); } return nullptr; } /* purecov: end */ unsigned int Gcs_xcom_nodes::get_size() const { return m_size; } bool Gcs_xcom_nodes::empty() const { return m_size == 0; } void Gcs_xcom_nodes::add_node(const Gcs_xcom_node_information &node) { m_nodes.push_back(node); m_size++; } void Gcs_xcom_nodes::remove_node(const Gcs_xcom_node_information &node) { std::vector<Gcs_xcom_node_information>::iterator nodes_it; for (nodes_it = m_nodes.begin(); nodes_it != m_nodes.end(); ++nodes_it) { if ((*nodes_it).get_member_id() == node.get_member_id()) { m_size--; m_nodes.erase(nodes_it); return; } } } void Gcs_xcom_nodes::add_nodes(const Gcs_xcom_nodes &xcom_nodes) { const std::vector<Gcs_xcom_node_information> &nodes = xcom_nodes.get_nodes(); std::vector<Gcs_xcom_node_information>::const_iterator nodes_it; clear_nodes(); for (nodes_it = nodes.begin(); nodes_it != nodes.end(); ++nodes_it) { add_node(*(nodes_it)); } } void Gcs_xcom_nodes::clear_nodes() { m_nodes.clear(); m_size = 0; } bool Gcs_xcom_nodes::encode(unsigned int *ptr_size, char ***ptr_addrs, blob **ptr_uuids) { /* If there is information already encoded, free it first. */ if (m_addrs != nullptr || m_uuids != nullptr) { /* purecov: begin tested */ free_encode(); /* purecov: end */ } m_addrs = static_cast<char **>(std::calloc(m_size, sizeof(char *))); m_uuids = static_cast<blob *>(std::calloc(m_size, sizeof(blob))); /* If memory was not successfuly allocated, an error is reported. */ if ((m_addrs == nullptr) || (m_uuids == nullptr)) { /* purecov: begin deadcode */ free_encode(); return false; /* purecov: end */ } unsigned int i = 0; size_t uuid_size = 0; std::vector<Gcs_xcom_node_information>::const_iterator nodes_it; for (nodes_it = m_nodes.begin(); nodes_it != m_nodes.end(); i++, ++nodes_it) { m_addrs[i] = const_cast<char *>((*nodes_it).get_member_id().get_member_id().c_str()); uuid_size = (*nodes_it).get_member_uuid().actual_value.size(); m_uuids[i].data.data_val = static_cast<char *>(malloc(uuid_size)); (*nodes_it).get_member_uuid().encode( reinterpret_cast<uchar **>(&m_uuids[i].data.data_val), &m_uuids[i].data.data_len); assert(m_uuids[i].data.data_len == uuid_size); MYSQL_GCS_LOG_TRACE("Node[%d]=(address=%s), (uuid=%s)", i, m_addrs[i], (*nodes_it).get_member_uuid().actual_value.c_str()); } *ptr_size = m_size; *ptr_addrs = m_addrs; *ptr_uuids = m_uuids; return true; } void Gcs_xcom_nodes::free_encode() { unsigned int i = 0; if (m_uuids != nullptr) { for (; i < m_size; i++) { free(m_uuids[i].data.data_val); } } free(m_addrs); free(m_uuids); m_addrs = nullptr; m_uuids = nullptr; }
SCE-Development/Core-v4
src/APIFunctions/2DPrinting.js
import axios from 'axios'; import { PrintApiResponse, ApiResponse } from './ApiResponses'; let config = require('../config/config.json'); let GENERAL_API_URL = process.env.NODE_ENV === 'production' ? config.GENERAL_API_URL_PROD : config.GENERAL_API_URL; let LOGGING_API_URL = process.env.NODE_ENV === 'production' ? config.LOGGING_API_URL_PROD : config.LOGGING_API_URL; let RPC_API_URL = process.env.NODE_ENV === 'production' ? config.RPC_API_URL_PROD : config.RPC_API_URL; /** * Return an array similar to python's range() function * @param {Number} start * @param {Number} end */ export const range = (start, end) => { const length = end - start; return Array.from({ length }, (_, i) => start + i); }; /** * Checks to see if the printer is available to accept requests! */ export async function healthCheck() { let status = new ApiResponse(); await axios.post(RPC_API_URL + '/Printer/healthCheck') .then(res => { status.reponseData = res.data; }) .catch(err => { status.responseData = err; status.error = true; }); return status; } /** * Returns an array of numbers from pages * @param {string} pages String containing array of pages * @param {Number} maxPages Number of pages in the document */ export function parseRange(pages, maxPages) { let result = new Set(); let pagesFromCommaSplit = pages.split(','); pagesFromCommaSplit.forEach(element => { const pagesFromDashSplit = element.split('-'); const arr = range( Number(pagesFromDashSplit[0]), Number(pagesFromDashSplit[pagesFromDashSplit.length - 1]) + 1 ); arr.forEach(element => { result.add(element); }); }); result.delete(0); result.forEach(element => { if (element > maxPages) result.delete(element); }); if (result.size === 0) { let arr = new Set(range(1, maxPages + 1)); return arr; } return result; } /** * Print the page * @param {Object} data - Encoded file and its configurations * @param {String|undefined} data.raw - Encoded file * @param {Number|undefined} data.copies - Number of copies * @param {String|undefined} data.sides - Sides to print: * one-sided or two-sided * @param {String|undefined} data.pageRanges - Pages to print: * 1-2, 5, 7-10 * @returns {ApiResponse} - Containing information for if * the page successfully printed */ export async function printPage(data) { let status = new ApiResponse(); await axios.post(RPC_API_URL + '/Printer/sendPrintRequest', data) .then(response => { status.responseData = response.data.message; }) .catch(() => { status.error = true; }); return status; } /** * Log the print request * @param {Object} data Encoded file * @returns {ApiResponse} Containing information for if * the page is printing */ export async function logPrintRequest(data) { let status = new ApiResponse(); await axios.post(LOGGING_API_URL + '/PrintLog/addPrintLog', data) .catch(() => { status.error = true; }); return status; } /** * Retrieves all print logs * @returns {ApiResponse} Containing all print logs */ export async function getAllLogs() { let status = new ApiResponse(); await axios.get(LOGGING_API_URL + '/PrintLog/getPrintLogs') .then(response => { status.responseData = response.data; }) .catch(() => { status.error = true; }); return status; } /** * Return the number of pages the current user has printed * @param {string} email email of the current user * @param {string} token token of the current user * @param {Set(Number)} totalPages set of all pages to be printed * @param {Number} copies number of copies to be printed * @returns {PrintApiResponse} Returns if user can print, number of pages * user can print, and total pages left */ export async function getPagesPrinted(email, token, totalPages, copies) { let status = new PrintApiResponse(); await axios .post(GENERAL_API_URL+'/user/getPagesPrintedCount', { email, token }) .then(res => { status.canPrint = copies * totalPages.size + res.data <= 30; status.remainingPages = 30 - res.data; }) .catch(() => { status.error = true; }); return status; }
novium258/cortx-1
doc/integrations/pytorch/tests/nightly/gpu/test_tutorial_generator.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest import parlai.utils.testing as testing_utils class TestTutorialTransformerGenerator(unittest.TestCase): def test_ppl(self): valid, _ = testing_utils.eval_model( { 'model': 'transformer/generator', 'model_file': 'zoo:tutorial_transformer_generator/model', 'task': 'dailydialog', 'skip_generation': 'true', 'num_examples': 512, 'batchsize': 32, }, skip_test=True, ) self.assertAlmostEqual(valid['ppl'], 19.59, places=2) self.assertAlmostEqual(valid['token_acc'], 0.4235, places=4)
netlify/build
packages/build/tests/steps/fixtures/pwd/file.js
<reponame>netlify/build import { resolve } from 'path' import { cwd } from 'process' import { fileURLToPath } from 'url' const CURRENT_DIR = fileURLToPath(new URL('.', import.meta.url)) console.log(cwd() === resolve(CURRENT_DIR))
npocmaka/Windows-Server-2003
shell/osshell/games/mshearts/computer.h
/***************************************************************************/ /** Microsoft Windows **/ /** Copyright(c) Microsoft Corp., 1991, 1992 **/ /***************************************************************************/ /**************************************************************************** computer.h This file contains the class declarations and manifest constants necessary for implementing the 'computer' object. FILE HISTORY: KeithMo 01-Mar-1992 Created from JimH's PLAYER.H. ****************************************************************************/ #include "card.h" #include "player.h" #ifndef _COMPUTER_H_ #define _COMPUTER_H_ // // These constants are used for indexing the _CardVectors array. // // Note that this ordering *must* match the ordering used for the // card ID values!! // #define INDEX_CLUBS 0 #define INDEX_DIAMONDS 1 #define INDEX_HEARTS 2 #define INDEX_SPADES 3 // // These constants represent the values returned from the // CardToVector() function. // // Note that this ordering *must* match the ordering used for the // card ID values!! // #define VECTOR_ACE 0x0001 #define VECTOR_2 0x0002 #define VECTOR_3 0x0004 #define VECTOR_4 0x0008 #define VECTOR_5 0x0010 #define VECTOR_6 0x0020 #define VECTOR_7 0x0040 #define VECTOR_8 0x0080 #define VECTOR_9 0x0100 #define VECTOR_10 0x0200 #define VECTOR_JACK 0x0400 #define VECTOR_QUEEN 0x0800 #define VECTOR_KING 0x1000 // // These constants define various combinations of cards. // #define LOW_CARDS (VECTOR_2 | VECTOR_3 | VECTOR_4 | VECTOR_5 \ | VECTOR_6 | VECTOR_7) #define HIGH_CARDS (VECTOR_8 | VECTOR_9 | VECTOR_10 \ | VECTOR_JACK | VECTOR_QUEEN | VECTOR_KING \ | VECTOR_ACE) #define QKA_CARDS (VECTOR_QUEEN | VECTOR_KING | VECTOR_ACE) #define JQKA_CARDS (VECTOR_JACK | VECTOR_QUEEN | VECTOR_KING \ | VECTOR_ACE) /**************************************************************************** computer ****************************************************************************/ class computer : public player { private: static int _VectorPriority[13]; static int _SuitPriority[4]; int _CardVectors[4]; int CardToSuit( int nCard ) const { return nCard % 4; } int CardToValue( int nCard ) const { return nCard / 4; } int CardToVector( int nCard ) const { return 1 << CardToValue( nCard ); } int CountBits( int x ) const; void AddCard( int nCard ) { _CardVectors[CardToSuit(nCard)] |= CardToVector(nCard); } void RemoveCard( int nCard ) { _CardVectors[CardToSuit(nCard)] &= ~CardToVector(nCard); } BOOL TestCard( int nCard ) const { return (_CardVectors[CardToSuit(nCard)] & CardToVector(nCard)) != 0; } int QueryClubsVector( void ) const { return _CardVectors[INDEX_CLUBS]; } int QueryDiamondsVector( void ) const { return _CardVectors[INDEX_DIAMONDS]; } int QueryHeartsVector( void ) const { return _CardVectors[INDEX_HEARTS]; } int QuerySpadesVector( void ) const { return _CardVectors[INDEX_SPADES]; } void ComputeVectors( void ); void PassCardsInVector( int nVector, int nSuit, int * pcPassed ); // comp2.cpp helper functions and data int BestSuitToDump(BOOL bIncludeHearts = TRUE); int BestSuitToLose(BOOL bIncludeHearts = TRUE); SLOT CardBelow(SLOT s); int CardsAbove(SLOT s); int CardsAboveLow(int suit); int CardsBelowLow(int suit); SLOT MidSlot(int suit); SLOT SafeCard(handinfotype &h); SLOT SelectLeadCard(handinfotype &h); SLOT SelectNonLeadCard(handinfotype &h); void Setup(handinfotype &h); int SureLossSuit(BOOL bIncludeHearts); BOOL bFirst; // am I leading? BOOL bLast; // am I last? card *cardled; int nSuitLed; int nValueLed; int currentval; // current winning value int nPoints; // points currently in hand SLOT sBlackLady; // non-EMPTY if in hand SLOT sHighCard[MAXSUIT]; // highest and lowest cards by suit int nHighVal[MAXSUIT]; SLOT sLowCard[MAXSUIT]; int nLowVal[MAXSUIT]; SLOT sHighestCard; // highest and lowest regardless of suit int nHighestVal; SLOT sLowestCard; int nLowestVal; int nAvailable[MAXSUIT][KING+2]; // cards unaccounted for this hand public: computer(int n); virtual void NotifyEndHand(handinfotype &h); virtual void NotifyNewRound(void); virtual void SelectCardsToPass(void); virtual void SelectCardToPlay(handinfotype &h, BOOL bCheating); virtual void UpdateStatus(void) { } virtual void UpdateStatus(int stringid) { status = stringid; } virtual void UpdateStatus(const TCHAR *string) { } }; // class computer #endif // _COMPUTER_H_
MHFNaN/muffin-0.10.4-src-leaked
src/main/java/me/han/muffin/client/mixin/mixins/render/entity/MixinRenderEntityItem.java
package me.han.muffin.client.mixin.mixins.render.entity; import me.han.muffin.client.Muffin; import me.han.muffin.client.event.EventStageable; import me.han.muffin.client.event.events.render.item.RenderItemEvent; import me.han.muffin.client.module.modules.other.ItemRender; import net.minecraft.client.renderer.entity.RenderEntityItem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = RenderEntityItem.class) public class MixinRenderEntityItem { @Inject(method = "doRender", at = @At("HEAD"), require = 1) private void onInjectChamsPre(CallbackInfo callbackInfo) { Muffin.getInstance().getEventManager().dispatchEvent(new RenderItemEvent(EventStageable.EventStage.PRE)); } @Inject(method = "doRender", at = @At("RETURN"), require = 1) private void onInjectChamsPost(CallbackInfo callbackInfo) { Muffin.getInstance().getEventManager().dispatchEvent(new RenderItemEvent(EventStageable.EventStage.POST)); } @Redirect(method = "transformModelCount", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GlStateManager;rotate(FFFF)V")) private void doTransformModelCountRotate(float angle, float x, float y, float z) { if (ItemRender.INSTANCE.isEnabled() && ItemRender.INSTANCE.getItemsAngle().getValue()) ItemRender.INSTANCE.doItemAngle(); } }
ajdinstel/sphere-sunrise-zr
product-catalog/app/productcatalog/services/ProductService.java
<reponame>ajdinstel/sphere-sunrise-zr package productcatalog.services; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.CategoryTreeExtended; import io.sphere.sdk.products.ProductProjection; import io.sphere.sdk.search.PagedSearchResult; import play.libs.F; import productcatalog.controllers.SearchCriteria; import java.util.List; import java.util.Locale; import java.util.Optional; public interface ProductService { /** * Gets a list of Products from a PagedQueryResult * @param page the page to fetch * @param searchCriteria all information regarding the request parameters * @return A promise of a paged result of the search request */ F.Promise<PagedSearchResult<ProductProjection>> searchProducts(final int page, final SearchCriteria searchCriteria); /** * Gets a product, uniquely identified by a locale and a slug * @param locale the locale in which you provide the slug * @param slug the slug * @return A Promise of an optionally found ProductProjection */ F.Promise<Optional<ProductProjection>> findProductBySlug(final Locale locale, final String slug); /** * Gets a List of length numSuggestions of Products related somehow with the given product. * @param product the product to get suggestions for * @param numSuggestions the number of products the returned list should contain. * It might contain less if the requested number is greater * than the number of available products. * @return A Promise of the list of products without duplicates */ F.Promise<List<ProductProjection>> getSuggestions(final ProductProjection product, final CategoryTreeExtended categoryTree, final int numSuggestions); /** * Gets a List of length numSuggestions of Products from the given categories * @param categories the categories to get suggestions from * @param numSuggestions the number of products the returned list should contain. * It might contain less if the requested number is greater * than the number of available products. * @return A Promise of the list of products without duplicates */ F.Promise<List<ProductProjection>> getSuggestions(final List<Category> categories, final int numSuggestions); }
nijabutter/SDL-GUI
main.cpp
<filename>main.cpp #include <iostream> #include <algorithm> #include "SDL_GUI.hpp" #include "Theme.hpp" int main() { Window root = Window(); Dropdown *d = new Dropdown(&root, L"placeholder" , {L"1", L"2", L"3"}); d->grid(0, 0); (new Button(&root, L"set to 1", [d](){d->set(1);}))->grid(0, 1); root.run(); }
yuryshukhrov/mmo-android
src/com/yuri/game/ui/activities/LoginActivity.java
package com.yuri.game.ui.activities; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.yuri.game.GameApplication; import com.yuri.game.R; import com.yuri.game.context.ControllerContext; import com.yuri.game.controller.listeners.LoginListener; import com.yuri.game.controller.listeners.SystemErrorListener; import com.yuri.game.model.duel.DuelRequest; import com.yuri.game.network.ServerRequestFormer; public class LoginActivity extends Activity implements LoginListener, SystemErrorListener { private String login; private String pwd; private ControllerContext controllers; private GameApplication gameApplication; // UI references. private EditText loginView; private EditText pwdView; private TextView lnkRegisterView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_login); gameApplication = GameApplication.getApplicationFromActivityContext(this); this.controllers = gameApplication.controllers; controllers.systemErrorController.systemErrorListeners.add(this); controllers.loginController.loginListeners.add(this); // Set up the login form. loginView = (EditText) findViewById(R.id.login_name); pwdView = (EditText) findViewById(R.id.txtPassword); lnkRegisterView = (TextView) findViewById(R.id.lnkRegister); findViewById(R.id.btnLogin).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); lnkRegisterView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getApplicationContext(), RegistrationActivity.class)); LoginActivity.this.finish(); } }); } @Override protected void onDestroy() { super.onDestroy(); controllers.systemErrorController.systemErrorListeners.remove(this); controllers.loginController.loginListeners.remove(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.login, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (item.getItemId() == R.id.action_close_socket) { controllers.networkController.closeConnection(); Toast.makeText(this, "Connection is closed!", Toast.LENGTH_LONG).show(); } else if (item.getItemId() == R.id.action_show) { List<DuelRequest> duels = gameApplication.world.modelContainer.location.getDuelRequestsList(); StringBuilder b = new StringBuilder(); for (DuelRequest p: duels) { b.append(p.getOwner() + "\n"); } Toast.makeText(this, b.toString(), Toast.LENGTH_LONG).show(); } return super.onMenuItemSelected(featureId, item); } private void attemptLogin() { // Reset errors. loginView.setError(null); pwdView.setError(null); // Store values at the time of the login attempt. login = loginView.getText().toString(); pwd = <PASSWORD>View.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid login. if (TextUtils.isEmpty(login)) { loginView.setError(getString(R.string.error_field_required)); focusView = loginView; cancel = true; } // Check for a valid password. if (TextUtils.isEmpty(pwd)) { pwdView.setError(getString(R.string.error_field_required)); focusView = pwdView; cancel = true; } else if (pwd.length() < 4) { pwdView.setError(getString(R.string.error_invalid_password)); focusView = pwdView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { if (isOnline()) { if (gameApplication.clientSocket.connected) { controllers.networkController .sendRequest(new ServerRequestFormer().loginPlayer( login, pwd)); } else { controllers.networkController.connectToServer(); controllers.networkController .startPendingRequest(new ServerRequestFormer() .loginPlayer(login, pwd)); controllers.networkController .startListeningToServer(); Log.e("attemptLogin", "Launched 3 threads"); } } else { showSystemErrorDialog(R.string.failed_to_open_socket); } } } @Override public void onLoginSuccess() { startActivity(new Intent(getApplicationContext(), MainActivity.class)); LoginActivity.this.finish(); } @Override public void onSocketTerminated() { if (!isFinishing()) { showSystemErrorDialog(R.string.socket_is_closed_by_server); } } @Override public void onWrongRequestStructure() { if (!isFinishing()) { showSystemErrorDialog(R.string.wrong_request_structure); } } @Override public void onWrongCommandOrder() { if (!isFinishing()) { showSystemErrorDialog(R.string.wrong_command_order); } } @Override public void onMissingParameters() { if (!isFinishing()) { showSystemErrorDialog(R.string.params_are_missing); } } @Override public void onParameterNotFound() { if (!isFinishing()) { showSystemErrorDialog(R.string.param_not_found); } } public void showSystemErrorDialog(int messageResourceID) { Log.e("showSystemErrorDialog() Log", "inside"); Dialog d = new AlertDialog.Builder(this) .setTitle(R.string.system_error_message) .setMessage(messageResourceID) .setNeutralButton(android.R.string.ok, null).create(); d.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { //LoginActivity.this.finish(); } }); d.show(); } @Override public void onLoginFail() { if (!isFinishing()) { showSystemErrorDialog(R.string.error_incorrect_password); } } // Checks the network state public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } }
NightglowRE/PiecemealCode
org.nightglower.hutubill/src/service/ReportService.java
package service; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import dao.RecordDAO; import entity.Record; import util.DateUtil; /** * @ClassName ReportService * @Description 报表业务类 * @Author NightGlower * @Date 2020/7/23 23:03 * @Version 1.0 */ public class ReportService { /** * 获取某一天的消费金额 * 这天的消费可能有多笔,把这几笔消费加起来算在一起。 * @param d * @param monthRawData * @return */ public int getDaySpend(Date d,List<Record> monthRawData){ int daySpend = 0; for (Record record : monthRawData) { if(record.date.equals(d)) daySpend+=record.spend; } return daySpend; } /** * 获取一个月的消费记录集合 * 假设本月有30天,那么这个集合就有30条Record。每个Record对应一天的消费总金额,如果那天没有消费,则消费金额为0. * @return */ public List<Record> listThisMonthRecords() { RecordDAO dao= new RecordDAO(); List<Record> monthRawData= dao.listThisMonth(); List<Record> result= new ArrayList<>(); Date monthBegin = DateUtil.monthBegin(); int monthTotalDay = DateUtil.thisMonthTotalDay(); Calendar c = Calendar.getInstance(); for (int i = 0; i < monthTotalDay; i++) { Record r = new Record(); c.setTime(monthBegin); c.add(Calendar.DATE, i); Date eachDayOfThisMonth=c.getTime() ; int daySpend = getDaySpend(eachDayOfThisMonth,monthRawData); r.spend=daySpend; result.add(r); } return result; } }
makhnnar/l2custom_acis
aCis_gameserver/java/net/sf/l2j/gameserver/scripting/scripts/teleports/PaganTeleporters.java
<filename>aCis_gameserver/java/net/sf/l2j/gameserver/scripting/scripts/teleports/PaganTeleporters.java<gh_stars>0 package net.sf.l2j.gameserver.scripting.scripts.teleports; import net.sf.l2j.gameserver.data.xml.DoorData; import net.sf.l2j.gameserver.model.actor.Npc; import net.sf.l2j.gameserver.model.actor.Player; import net.sf.l2j.gameserver.scripting.Quest; import net.sf.l2j.gameserver.scripting.QuestState; public class PaganTeleporters extends Quest { // Items private static final int VISITOR_MARK = 8064; private static final int PAGAN_MARK = 8067; public PaganTeleporters() { super(-1, "teleports"); addStartNpc(32034, 32035, 32036, 32037, 32039, 32040); addTalkId(32034, 32035, 32036, 32037, 32039, 32040); } @Override public String onAdvEvent(String event, Npc npc, Player player) { if (event.equalsIgnoreCase("Close_Door1")) DoorData.getInstance().getDoor(19160001).closeMe(); else if (event.equalsIgnoreCase("Close_Door2")) { DoorData.getInstance().getDoor(19160010).closeMe(); DoorData.getInstance().getDoor(19160011).closeMe(); } return null; } @Override public String onTalk(Npc npc, Player player) { String htmltext = ""; QuestState st = player.getQuestState(getName()); if (st == null) return htmltext; switch (npc.getNpcId()) { case 32034: if (st.hasQuestItems(VISITOR_MARK) || st.hasQuestItems(PAGAN_MARK)) { DoorData.getInstance().getDoor(19160001).openMe(); startQuestTimer("Close_Door1", 10000, npc, player, false); htmltext = "FadedMark.htm"; } else { htmltext = "32034-1.htm"; st.exitQuest(true); } break; case 32035: DoorData.getInstance().getDoor(19160001).openMe(); startQuestTimer("Close_Door1", 10000, npc, player, false); htmltext = "FadedMark.htm"; break; case 32036: if (!st.hasQuestItems(PAGAN_MARK)) htmltext = "32036-1.htm"; else { DoorData.getInstance().getDoor(19160010).openMe(); DoorData.getInstance().getDoor(19160011).openMe(); startQuestTimer("Close_Door2", 10000, npc, player, false); htmltext = "32036-2.htm"; } break; case 32037: DoorData.getInstance().getDoor(19160010).openMe(); DoorData.getInstance().getDoor(19160011).openMe(); startQuestTimer("Close_Door2", 10000, npc, player, false); htmltext = "FadedMark.htm"; break; case 32039: player.teleportTo(-12766, -35840, -10856, 0); break; case 32040: player.teleportTo(34962, -49758, -763, 0); break; } return htmltext; } }
jhmfreitas/SoftwareEngineering-Project
car/src/main/java/pt/ulisboa/tecnico/softeng/car/domain/Motorcycle.java
package pt.ulisboa.tecnico.softeng.car.domain; public class Motorcycle extends Motorcycle_Base { public Motorcycle(String plate, int kilometers, long price, RentACar rentACar) { checkArguments(plate, kilometers, rentACar); setPlate(plate.toUpperCase()); setKilometers(kilometers); setPrice(price); setRentACar(rentACar); } }
sfomuseum/go-www-geotag-whosonfirst
app/flags.go
package flags import ( "flag" "github.com/sfomuseum/go-flags/lookup" "net/url" "strings" ) func AppendWhosOnFirstFlags(fs *flag.FlagSet) error { fs.String("whosonfirst-writer-uri", "", "A valid whosonfirst/go-writer.Writer URI. If present it will be encoded and used to replace the '{whosonfirst_writer}' string in the -writer-uri flag.") fs.String("whosonfirst-reader-uri", "", "A valid whosonfirst/go-reader.Reader URI. If present it will be encoded and used to replace the '{whosonfirst_reader}' string in the -writer-uri flag.") return nil } func AssignWhosOnFirstFlags(fs *flag.FlagSet) error { wof_writer, err := lookup.StringVar(fs, "whosonfirst-writer-uri") if err != nil { return err } wof_reader, err := lookup.StringVar(fs, "whosonfirst-reader-uri") if err != nil { return err } if wof_writer != "" || wof_writer != "" { writer_uri, err := lookup.StringVar(fs, "writer-uri") if err != nil { return err } if wof_writer != "" { enc_wof_writer := url.QueryEscape(wof_writer) writer_uri = strings.Replace(writer_uri, "{whosonfirst_writer}", enc_wof_writer, 1) } if wof_reader != "" { enc_wof_reader := url.QueryEscape(wof_reader) writer_uri = strings.Replace(writer_uri, "{whosonfirst_reader}", enc_wof_reader, 1) } fs.Set("writer-uri", writer_uri) } return nil }
byteshiva/es6-tuts
functionalprogramming/day193/funcday193/index.js
<reponame>byteshiva/es6-tuts const R = require('ramda'); const numbers = [1, 2, 3, 4]; const factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] console.log(factorials);
srotya/sidewinder
core/src/main/java/com/srotya/sidewinder/core/functions/iterative/ReduceFunction.java
<reponame>srotya/sidewinder /** * Copyright <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.srotya.sidewinder.core.functions.iterative; import com.srotya.sidewinder.core.storage.DataPoint; import com.srotya.sidewinder.core.storage.DataPointIterator; public abstract class ReduceFunction extends FunctionIterator { public ReduceFunction(DataPointIterator iterator, boolean isFp) { super(iterator, isFp); } @Override public DataPoint next() { DataPoint out = new DataPoint(); DataPoint next = iterator.next(); out.setTimestamp(next.getTimestamp()); long longValue = next.getLongValue(); double doubleValue = Double.longBitsToDouble(next.getLongValue()); while (iterator.hasNext()) { next = iterator.next(); if (isFp) { doubleValue = reduce(doubleValue, Double.longBitsToDouble(next.getLongValue())); } else { longValue = reduce(longValue, next.getLongValue()); } } if (isFp) { longValue = Double.doubleToLongBits(doubleValue); } out.setLongValue(longValue); return out; } protected abstract double reduce(double prevReturn, double current); protected abstract long reduce(long prevReturn, long current); @Override public void init(Object[] args) throws Exception { } @Override public int getNumberOfArgs() { return 0; } }
jojanper/draal-jsapp
tests/bootstrap.spec.js
// To be executed once before all tests before(done => { const { credentials } = appTestHelper; // Create one active test user appTestHelper.createUser(credentials, () => { appTestHelper.activateUser(credentials.email, () => done()); }); }); // To be executed once all tests have finished after(() => { });
aTiKhan/nuxeo
modules/platform/rest-api/nuxeo-rest-api-server/src/main/java/org/nuxeo/ecm/restapi/server/jaxrs/adapters/PageProviderAdapter.java
<reponame>aTiKhan/nuxeo /* * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and others. * * 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. * * Contributors: * dmetzler */ package org.nuxeo.ecm.restapi.server.jaxrs.adapters; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.nuxeo.ecm.automation.core.util.Paginable; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.query.api.PageProviderDefinition; import org.nuxeo.ecm.platform.query.api.PageProviderService; import org.nuxeo.ecm.webengine.model.WebAdapter; import org.nuxeo.runtime.api.Framework; /** * Adapter that expose a page provider that needs only one parameter that is the document Id * * @since 5.7.2 */ @WebAdapter(name = PageProviderAdapter.NAME, type = "PageProviderService") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON + "+esentity" }) public class PageProviderAdapter extends DocumentModelListPaginableAdapter { public static final String NAME = "pp"; private String pageProviderName = "CURRENT_DOC_CHILDREN"; @Override protected PageProviderDefinition getPageProviderDefinition() { PageProviderService ppService = Framework.getService(PageProviderService.class); return ppService.getPageProviderDefinition(pageProviderName); } @Override protected Object[] getParams() { return new Object[] { getTarget().getAdapter(DocumentModel.class).getId() }; } @GET @Path("{pageProviderName}") public Paginable<DocumentModel> getProviderDocs(@PathParam("pageProviderName") String providerName) { pageProviderName = providerName; return super.getPaginableEntries(); } }
stas-perchenko/bt-recorder
app/src/main/java/com/alperez/bt_microphone/bluetoorh/connector/sound/SoundLevelMeter.java
package com.alperez.bt_microphone.bluetoorh.connector.sound; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; /** * Created by stanislav.perchenko on 4/11/2017. */ public class SoundLevelMeter { private OnSoundLevelListener callback; private Handler uiHandler; public SoundLevelMeter(@NonNull OnSoundLevelListener callback) { this.callback = callback; uiHandler = new Handler(Looper.getMainLooper()); } private int prescCounter = 0; private int prescValue = 0; public void submitSamples(byte[] samples, int offset, int len) { int smp, smpAbs; for (int i=0; i<len; i++) { smp = samples[offset ++]; if (smp >= 0) { smp = 127 - smp; } else { smp = -129 - smp; } //Log.d("Level-Meter", smp+" -> "+smpAbs); updatePeakDetector(smp); prescValue += smp; if ((++ prescCounter) >= 4) { prescCounter = 0; eveluatePrescaledValue( Math.round((float)prescValue/4f) ); prescValue = 0; } } } private long rmsAccum = 0; private int rmsCounter = 0; private void eveluatePrescaledValue(int v) { //Log.d("Level-Meter", "Prescaled = "+v); rmsAccum += v * v; if ((++ rmsCounter) >= 50) { final float rmsV = (float) Math.sqrt(rmsAccum / 50.0); //Log.d("Level-Meter", "--->> RMS = "+rmsV); rmsAccum = 0; rmsCounter = 0; notifyResult(filterRmsValue(rmsV)); } } public static final int RMS_FILTER_LEN = 3; float[] rmsDelayLine = new float[RMS_FILTER_LEN]; int rmsFilterIndex = 0; private float filterRmsValue(float iRms) { rmsDelayLine[rmsFilterIndex ++] = iRms; if (rmsFilterIndex >= RMS_FILTER_LEN) rmsFilterIndex = 0; float sum = 0; for (int i=0; i<RMS_FILTER_LEN; i++) { sum += rmsDelayLine[i]; } return sum / RMS_FILTER_LEN; } private void notifyResult(final float rms) { final int peak = getPeak(); resetPeakDetector(); uiHandler.post(()->callback.onLevelUpdated(rms, peak)); } /********************************* Peak detector section ************************************/ private int peak_hi, peak_lo; private void updatePeakDetector(int level) { int levAbs = Math.abs(level); if (levAbs > peak_hi) { peak_lo = peak_hi; peak_hi = levAbs; } else if (levAbs > peak_lo) { peak_lo = levAbs; } //Log.d("Level-Meter", String.format("level=%d, p_lo=%d, p_hi=%d", level, peak_lo, peak_hi)); } private int getPeak() { return peak_lo; } private void resetPeakDetector() { peak_hi = peak_lo = 0; } }
rio-31/android_frameworks_base-1
core/java/android/view/InputEvent.java
<filename>core/java/android/view/InputEvent.java<gh_stars>100-1000 /* * Copyright (C) 2010 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 android.view; import android.annotation.UnsupportedAppUsage; import android.os.Parcel; import android.os.Parcelable; import java.util.concurrent.atomic.AtomicInteger; /** * Common base class for input events. */ public abstract class InputEvent implements Parcelable { /** @hide */ protected static final int PARCEL_TOKEN_MOTION_EVENT = 1; /** @hide */ protected static final int PARCEL_TOKEN_KEY_EVENT = 2; // Next sequence number. private static final AtomicInteger mNextSeq = new AtomicInteger(); /** @hide */ protected int mSeq; /** @hide */ protected boolean mRecycled; private static final boolean TRACK_RECYCLED_LOCATION = false; private RuntimeException mRecycledLocation; /*package*/ InputEvent() { mSeq = mNextSeq.getAndIncrement(); } /** * Gets the id for the device that this event came from. An id of * zero indicates that the event didn't come from a physical device * and maps to the default keymap. The other numbers are arbitrary and * you shouldn't depend on the values. * * @return The device id. * @see InputDevice#getDevice */ public abstract int getDeviceId(); /** * Gets the device that this event came from. * * @return The device, or null if unknown. */ public final InputDevice getDevice() { return InputDevice.getDevice(getDeviceId()); } /** * Gets the source of the event. * * @return The event source or {@link InputDevice#SOURCE_UNKNOWN} if unknown. * @see InputDevice#getSources */ public abstract int getSource(); /** * Modifies the source of the event. * * @param source The new source. * @hide */ public abstract void setSource(int source); /** * Determines whether the event is from the given source. * * @param source The input source to check against. This can be a specific device type, such as * {@link InputDevice#SOURCE_TOUCH_NAVIGATION}, or a more generic device class, such as * {@link InputDevice#SOURCE_CLASS_POINTER}. * @return Whether the event is from the given source. */ public boolean isFromSource(int source) { return (getSource() & source) == source; } /** * Gets the display id of the event. * @return The display id associated with the event. * @hide */ public abstract int getDisplayId(); /** * Modifies the display id associated with the event * @param displayId * @hide */ public abstract void setDisplayId(int displayId); /** * Copies the event. * * @return A deep copy of the event. * @hide */ public abstract InputEvent copy(); /** * Recycles the event. * This method should only be used by the system since applications do not * expect {@link KeyEvent} objects to be recycled, although {@link MotionEvent} * objects are fine. See {@link KeyEvent#recycle()} for details. * @hide */ public void recycle() { if (TRACK_RECYCLED_LOCATION) { if (mRecycledLocation != null) { throw new RuntimeException(toString() + " recycled twice!", mRecycledLocation); } mRecycledLocation = new RuntimeException("Last recycled here"); } else { if (mRecycled) { throw new RuntimeException(toString() + " recycled twice!"); } mRecycled = true; } } /** * Conditionally recycled the event if it is appropriate to do so after * dispatching the event to an application. * * If the event is a {@link MotionEvent} then it is recycled. * * If the event is a {@link KeyEvent} then it is NOT recycled, because applications * expect key events to be immutable so once the event has been dispatched to * the application we can no longer recycle it. * @hide */ public void recycleIfNeededAfterDispatch() { recycle(); } /** * Reinitializes the event on reuse (after recycling). * @hide */ protected void prepareForReuse() { mRecycled = false; mRecycledLocation = null; mSeq = mNextSeq.getAndIncrement(); } /** * Gets a private flag that indicates when the system has detected that this input event * may be inconsistent with respect to the sequence of previously delivered input events, * such as when a key up event is sent but the key was not down or when a pointer * move event is sent but the pointer is not down. * * @return True if this event is tainted. * @hide */ public abstract boolean isTainted(); /** * Sets a private flag that indicates when the system has detected that this input event * may be inconsistent with respect to the sequence of previously delivered input events, * such as when a key up event is sent but the key was not down or when a pointer * move event is sent but the pointer is not down. * * @param tainted True if this event is tainted. * @hide */ public abstract void setTainted(boolean tainted); /** * Retrieve the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. * * @return Returns the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. */ public abstract long getEventTime(); /** * Retrieve the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base but with * nanosecond (instead of millisecond) precision. * <p> * The value is in nanosecond precision but it may not have nanosecond accuracy. * </p> * * @return Returns the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base but with * nanosecond (instead of millisecond) precision. * * @hide */ public abstract long getEventTimeNano(); /** * Marks the input event as being canceled. * * @hide */ public abstract void cancel(); /** * Gets the unique sequence number of this event. * Every input event that is created or received by a process has a * unique sequence number. Moreover, a new sequence number is obtained * each time an event object is recycled. * * Sequence numbers are only guaranteed to be locally unique within a process. * Sequence numbers are not preserved when events are parceled. * * @return The unique sequence number of this event. * @hide */ @UnsupportedAppUsage public int getSequenceNumber() { return mSeq; } public int describeContents() { return 0; } public static final @android.annotation.NonNull Parcelable.Creator<InputEvent> CREATOR = new Parcelable.Creator<InputEvent>() { public InputEvent createFromParcel(Parcel in) { int token = in.readInt(); if (token == PARCEL_TOKEN_KEY_EVENT) { return KeyEvent.createFromParcelBody(in); } else if (token == PARCEL_TOKEN_MOTION_EVENT) { return MotionEvent.createFromParcelBody(in); } else { throw new IllegalStateException("Unexpected input event type token in parcel."); } } public InputEvent[] newArray(int size) { return new InputEvent[size]; } }; }
jhh67/chapel
third-party/llvm/llvm-src/tools/clang/unittests/Tooling/LookupTest.cpp
<filename>third-party/llvm/llvm-src/tools/clang/unittests/Tooling/LookupTest.cpp //===- unittest/Tooling/LookupTest.cpp ------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Refactoring/Lookup.h" #include "TestVisitor.h" using namespace clang; namespace { struct GetDeclsVisitor : TestVisitor<GetDeclsVisitor> { std::function<void(CallExpr *)> OnCall; std::function<void(RecordTypeLoc)> OnRecordTypeLoc; SmallVector<Decl *, 4> DeclStack; bool VisitCallExpr(CallExpr *Expr) { if (OnCall) OnCall(Expr); return true; } bool VisitRecordTypeLoc(RecordTypeLoc Loc) { if (OnRecordTypeLoc) OnRecordTypeLoc(Loc); return true; } bool TraverseDecl(Decl *D) { DeclStack.push_back(D); bool Ret = TestVisitor::TraverseDecl(D); DeclStack.pop_back(); return Ret; } }; TEST(LookupTest, replaceNestedFunctionName) { GetDeclsVisitor Visitor; auto replaceCallExpr = [&](const CallExpr *Expr, StringRef ReplacementString) { const auto *Callee = cast<DeclRefExpr>(Expr->getCallee()->IgnoreImplicit()); const ValueDecl *FD = Callee->getDecl(); return tooling::replaceNestedName( Callee->getQualifier(), Callee->getLocation(), Visitor.DeclStack.back()->getDeclContext(), FD, ReplacementString); }; Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("bar", replaceCallExpr(Expr, "::bar")); }; Visitor.runOver("namespace a { void foo(); }\n" "namespace a { void f() { foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { void foo(); }\n" "namespace a { void f() { foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { void foo(); }\n" "namespace b { void f() { a::foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("::a::bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { void foo(); }\n" "namespace b { namespace a { void foo(); }\n" "void f() { a::foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("c::bar", replaceCallExpr(Expr, "::a::c::bar")); }; Visitor.runOver("namespace a { namespace b { void foo(); }\n" "void f() { b::foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { namespace b { void foo(); }\n" "void f() { b::foo(); } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("bar", replaceCallExpr(Expr, "::bar")); }; Visitor.runOver("void foo(); void f() { foo(); }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("::bar", replaceCallExpr(Expr, "::bar")); }; Visitor.runOver("void foo(); void f() { ::foo(); }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { void foo(); }\nvoid f() { a::foo(); }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("a::bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver("namespace a { int foo(); }\nauto f = a::foo();\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("bar", replaceCallExpr(Expr, "::a::bar")); }; Visitor.runOver( "namespace a { int foo(); }\nusing a::foo;\nauto f = foo();\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("c::bar", replaceCallExpr(Expr, "::a::c::bar")); }; Visitor.runOver("namespace a { namespace b { void foo(); } }\n" "namespace a { namespace b { namespace {" "void f() { foo(); }" "} } }\n"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("x::bar", replaceCallExpr(Expr, "::a::x::bar")); }; Visitor.runOver("namespace a { namespace b { void foo(); } }\n" "namespace a { namespace b { namespace c {" "void f() { foo(); }" "} } }\n"); // If the shortest name is ambiguous, we need to add more qualifiers. Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("a::y::bar", replaceCallExpr(Expr, "::a::y::bar")); }; Visitor.runOver(R"( namespace a { namespace b { namespace x { void foo() {} } namespace y { void foo() {} } } } namespace a { namespace b { void f() { x::foo(); } } })"); Visitor.OnCall = [&](CallExpr *Expr) { // y::bar would be ambiguous due to "a::b::y". EXPECT_EQ("::y::bar", replaceCallExpr(Expr, "::y::bar")); }; Visitor.runOver(R"( namespace a { namespace b { void foo() {} namespace y { } } } namespace a { namespace b { void f() { foo(); } } })"); Visitor.OnCall = [&](CallExpr *Expr) { EXPECT_EQ("y::bar", replaceCallExpr(Expr, "::y::bar")); }; Visitor.runOver(R"( namespace a { namespace b { namespace x { void foo() {} } namespace y { void foo() {} } } } void f() { a::b::x::foo(); } )"); } TEST(LookupTest, replaceNestedClassName) { GetDeclsVisitor Visitor; auto replaceRecordTypeLoc = [&](RecordTypeLoc TLoc, StringRef ReplacementString) { const auto *FD = cast<CXXRecordDecl>(TLoc.getDecl()); return tooling::replaceNestedName( nullptr, TLoc.getBeginLoc(), Visitor.DeclStack.back()->getDeclContext(), FD, ReplacementString); }; Visitor.OnRecordTypeLoc = [&](RecordTypeLoc Type) { // Filter Types by name since there are other `RecordTypeLoc` in the test // file. if (Type.getDecl()->getQualifiedNameAsString() == "a::b::Foo") { EXPECT_EQ("x::Bar", replaceRecordTypeLoc(Type, "::a::x::Bar")); } }; Visitor.runOver("namespace a { namespace b {\n" "class Foo;\n" "namespace c { Foo f();; }\n" "} }\n"); Visitor.OnRecordTypeLoc = [&](RecordTypeLoc Type) { // Filter Types by name since there are other `RecordTypeLoc` in the test // file. // `a::b::Foo` in using shadow decl is not `TypeLoc`. if (Type.getDecl()->getQualifiedNameAsString() == "a::b::Foo") { EXPECT_EQ("Bar", replaceRecordTypeLoc(Type, "::a::x::Bar")); } }; Visitor.runOver("namespace a { namespace b { class Foo {}; } }\n" "namespace c { using a::b::Foo; Foo f();; }\n"); // Rename TypeLoc `x::y::Old` to new name `x::Foo` at [0] and check that the // type is replaced with "Foo" instead of "x::Foo". Although there is a symbol // `x::y::Foo` in c.cc [1], it should not make "Foo" at [0] ambiguous because // it's not visible at [0]. Visitor.OnRecordTypeLoc = [&](RecordTypeLoc Type) { if (Type.getDecl()->getQualifiedNameAsString() == "x::y::Old") { EXPECT_EQ("Foo", replaceRecordTypeLoc(Type, "::x::Foo")); } }; Visitor.runOver(R"( // a.h namespace x { namespace y { class Old {}; class Other {}; } } // b.h namespace x { namespace y { // This is to be renamed to x::Foo // The expected replacement is "Foo". Old f; // [0]. } } // c.cc namespace x { namespace y { using Foo = ::x::y::Other; // [1] } } )"); } } // end anonymous namespace
bluesky013/Explosion
Common/Asset/Include/Asset/AssetInstance.h
<filename>Common/Asset/Include/Asset/AssetInstance.h // // Created by <NAME> on 2021/9/14. // #ifndef EXPLOSION_ASSETINSTANCE_H #define EXPLOSION_ASSETINSTANCE_H #include <type_traits> #include <cstdint> namespace Explosion { class IAssetInstance { }; template <typename T> class AssetInstance { public: static_assert(std::is_base_of_v<IAssetInstance, T>, "T must derived from IAssetInstance"); AssetInstance() = default; ~AssetInstance() = default; private: uint32_t id; T* resource; }; } #endif//EXPLOSION_ASSETINSTANCE_H
kamchiu/server-side-with-nodejs
rest-server/routes/leaderRouter.js
<filename>rest-server/routes/leaderRouter.js 'use strict' const express = require("express") const bodyParser = require("body-parser") const mongoose = require('mongoose') const leaderships = require('../models/leaders') const leaderRouter = express.Router() leaderRouter.use(bodyParser.json()) leaderRouter.route('/') .get( (req, res, next) => { leaderships.find({}, function(err, leadership) { if(err) throw err; res.json(leadership); }) }) .delete( (req, res, next) => { leaderships.remove({}, function(err, resp) { if(err) throw err; res.json(resp); }) }) .post( (req, res, next) => { leaderships.create(req.body, function(err, leadership) { if(err) throw err; const id = leadership._id; res.writeHead(200, {'Content-Type': 'text/plain'}) res.end('Created leadership with id: ' + id) }) }) leaderRouter.route('/:leaderId') .get( (req, res, next) => { leaderships.findById(req.params.leaderId, function(err, leadership) { if(err) throw err; res.json(leadership); }) }) .delete( (req, res, next) => { leaderships.findByIdAndRemove(req.params.leaderId, function(err, resp) { if(err) throw err; res.json(resp); }) }) .put( (req, res, next) => { leaderships.findByIdAndUpdate(req.params.leaderId, { $set: req.body }, { new: true }, function(err, leadership) { if(err) throw err; res.json(leadership); }) }) module.exports = leaderRouter
MjoaquinM/ModSecurityProyect
modsecurityWafProject/src/main/java/com/fich/wafproject/model/Rule.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fich.wafproject.model; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author martin */ @Entity @Table(name = "Rule", catalog = "waf_project", schema = "") @NamedQueries({ @NamedQuery(name = "Rule.findAll", query = "SELECT r FROM Rule r") , @NamedQuery(name = "Rule.findById", query = "SELECT r FROM Rule r WHERE r.id = :id") , @NamedQuery(name = "Rule.findByRuleId", query = "SELECT r FROM Rule r WHERE r.ruleId = :ruleId") , @NamedQuery(name = "Rule.findByMessage", query = "SELECT r FROM Rule r WHERE r.message = :message") , @NamedQuery(name = "Rule.findBySeverity", query = "SELECT r FROM Rule r WHERE r.severity = :severity")}) public class Rule implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 10) @Column(name = "ruleId") private String ruleId; @Size(max = 1000) @Column(name = "message") private String message; @Size(max = 45) @Column(name = "severity") private String severity; @ManyToMany(mappedBy="rules",fetch = FetchType.EAGER) private List<Event> events; @JoinColumn(name = "fileId", referencedColumnName = "id") @ManyToOne(optional = false) private File fileId; public Rule() { } public Rule(Integer id) { this.id = id; } public Rule(Integer id, String ruleId) { this.id = id; this.ruleId = ruleId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRuleId() { return ruleId; } public void setRuleId(String ruleId) { this.ruleId = ruleId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public File getFileId() { return fileId; } public void setFileId(File fileId) { this.fileId = fileId; } public List<Event> getEvents(){ return this.events; } public void setEvents(List<Event> events){ this.events = events; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Rule)) { return false; } Rule other = (Rule) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.websystique.springmvc.model.Rule[ id=" + id + " ]"; } }
deveshpatel0101/data_structures_algorithms
algorithms/making_change_dp/making_change_dp.go
package main import ( "fmt" "math" ) // MakeChange will generate the necessary matrix which will then be evaluated to know // the number of coins and which coins will be required to have a given change func MakeChange() { for i := 0; i < len(matrix); i++ { for j := 0; j < len(matrix[i]); j++ { if i == 0 || j == 0 { continue } else if i == 1 { matrix[i][j] = 1 + matrix[i][j-int(coins[i-1])] } else if j < int(coins[i-1]) { matrix[i][j] = matrix[i-1][j] } else { matrix[i][j] = math.Min(matrix[i-1][j], 1+matrix[i][j-int(coins[i-1])]) } } } fmt.Println("\nMatrix formed:") for i := 0; i < len(matrix); i++ { for j := 0; j < len(matrix[i]); j++ { fmt.Print(matrix[i][j], " ") } fmt.Println() } i := len(matrix) - 1 j := len(matrix[0]) - 1 result := make([]float64, 0) count := matrix[i][j] for count != 0 { if matrix[i-1][j] == count { i-- } else { j -= int(coins[i-1]) result = append(result, coins[i-1]) count-- } } fmt.Println("You will require", len(result), "coins of values", result, "to make a change for", change, ".") } var change float64 var numCoins float64 var coins []float64 var matrix [][]float64 func main() { fmt.Println("\n-- Making Change Problem using Dynamic Programming. --") fmt.Print("Enter the value for the amount of change you want: ") fmt.Scanf("%f\n", &change) fmt.Print("Enter the number of coins you have: ") fmt.Scanf("%f\n", &numCoins) var coin float64 fmt.Println("Start enter the values of these coins in increasing order:") for i := 0; i < int(numCoins); i++ { fmt.Scanf("%f\n", &coin) coins = append(coins, coin) } matrix = make([][]float64, int(numCoins)+1) for i := 0; i < len(matrix); i++ { matrix[i] = make([]float64, int(change)+1) for j := range matrix[i] { matrix[i][j] = float64(0) } } MakeChange() }
fnando/signal
test/support/callable.rb
# frozen_string_literal: true class Callable < Minitest::Mock def initialize(method_name) super() @method_name = method_name end def to_proc callable = self proc {|*args| callable.send(@method_name, *args) } end end
aryx/principia-softwarica
networking/ftp/ftpfs/ftpfs.c
/*s: networking/ip/ftpfs/ftpfs.c */ #include <u.h> #include <libc.h> #include <auth.h> #include <fcall.h> #include <string.h> #include "ftpfs.h" /* an active fid */ typedef struct Fid Fid; /*s: struct [[Fid]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ struct Fid { int fid; Node *node; /* path to remote file */ int busy; Fid *next; int open; }; /*e: struct [[Fid]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[fids]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ Fid *fids; /* linked list of fids */ /*e: global [[fids]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[errstring]] */ char errstring[128]; /* error to return */ /*e: global [[errstring]] */ /*s: global [[mfd]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ int mfd; /* fd for 9fs */ /*e: global [[mfd]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[messagesize]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ int messagesize = 4*1024*IOHDRSZ; /*e: global [[messagesize]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[mdata]] */ uchar mdata[8*1024*IOHDRSZ]; /*e: global [[mdata]] */ /*s: global [[mbuf]] */ uchar mbuf[8*1024*IOHDRSZ]; /*e: global [[mbuf]] */ /*s: global [[rhdr]] */ Fcall rhdr; /*e: global [[rhdr]] */ /*s: global [[thdr]] */ Fcall thdr; /*e: global [[thdr]] */ /*s: global [[debug]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ int debug; /*e: global [[debug]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[usenlst]] */ int usenlst; /*e: global [[usenlst]] */ /*s: global [[usetls]] */ int usetls; /*e: global [[usetls]] */ /*s: global [[ext]] */ char *ext; /*e: global [[ext]] */ /*s: global [[quiet]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ int quiet; /*e: global [[quiet]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[kapid]] */ int kapid = -1; /*e: global [[kapid]] */ /*s: global [[dying]] */ int dying; /* set when any process decides to die */ /*e: global [[dying]] */ /*s: global [[dokeepalive]] */ int dokeepalive; /*e: global [[dokeepalive]] */ char *rflush(Fid*), *rnop(Fid*), *rversion(Fid*), *rattach(Fid*), *rclone(Fid*), *rwalk(Fid*), *rclwalk(Fid*), *ropen(Fid*), *rcreate(Fid*), *rread(Fid*), *rwrite(Fid*), *rclunk(Fid*), *rremove(Fid*), *rstat(Fid*), *rwstat(Fid*), *rauth(Fid*);; void mountinit(char*); void io(void); int readpdir(Node*); /*s: global [[fcalls]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char *(*fcalls[])(Fid*) = { [Tflush] rflush, [Tversion] rversion, [Tattach] rattach, [Tauth] rauth, [Twalk] rwalk, [Topen] ropen, [Tcreate] rcreate, [Tread] rread, [Twrite] rwrite, [Tclunk] rclunk, [Tremove] rremove, [Tstat] rstat, [Twstat] rwstat, }; /*e: global [[fcalls]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: global [[oslist]] */ /* these names are matched as prefixes, so VMS must precede VM */ OS oslist[] = { { Plan9, "Plan 9", }, { Plan9, "Plan9", }, { Plan9, "UNIX Type: L8 Version: Plan 9", }, { Unix, "SUN", }, { Unix, "UNIX", }, { VMS, "VMS", }, { VM, "VM", }, { Tops, "TOPS", }, { MVS, "MVS", }, { NetWare, "NetWare", }, { NetWare, "NETWARE", }, // { OS½, "OS/2", }, { TSO, "TSO", }, { NT, "Windows_NT", }, /* DOS like interface */ { NT, "WINDOWS_NT", }, /* Unix like interface */ { Unknown, 0 }, }; /*e: global [[oslist]] */ /*s: global [[nouid]] */ char *nouid = "?uid?"; /*e: global [[nouid]] */ /*s: macro [[S2P]] */ #define S2P(x) (((ulong)(x)) & 0xffffff) /*e: macro [[S2P]] */ /*s: global [[nosuchfile]] */ char *nosuchfile = "file does not exist"; /*e: global [[nosuchfile]] */ /*s: global [[keyspec]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char *keyspec = ""; /*e: global [[keyspec]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[usage]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ void usage(void) { fprint(2, "ftpfs [-/dqnt] [-a passwd] [-m mountpoint] [-e ext] [-k keyspec] [-o os] [-r root] [net!]address\n"); exits("usage"); } /*e: function [[usage]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[main]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ void main(int argc, char *argv[]) { char *mountroot = 0; char *mountpoint = "/n/ftp"; char *cpassword = 0; char *cp; int p[2]; OS *o; defos = Unix; user = strdup(getuser()); usetls = 0; ARGBEGIN { case '/': mountroot = "/"; break; case 'a': cpassword = ARGF(); break; case 'd': debug = 1; break; case 'k': keyspec = EARGF(usage()); break; case 'K': dokeepalive = 1; break; case 'm': mountpoint = ARGF(); break; case 'n': usenlst = 1; break; case 'e': ext = ARGF(); break; case 't': usetls = 1; break; case 'o': cp = ARGF(); for(o = oslist; o->os != Unknown; o++) if(strncmp(cp, o->name, strlen(o->name)) == 0){ defos = o->os; break; } break; case 'r': mountroot = ARGF(); break; case 'q': quiet = 1; break; } ARGEND if(argc != 1) usage(); /* get a pipe to mount and run 9fs on */ if(pipe(p) < 0) fatal("pipe failed: %r"); mfd = p[0]; /* initial handshakes with remote side */ hello(*argv); if(cpassword == 0) rlogin(*argv, keyspec); else clogin("anonymous", cpassword); preamble(mountroot); /* start the 9fs protocol */ switch(rfork(RFPROC|RFNAMEG|RFENVG|RFFDG|RFNOTEG|RFREND)){ case -1: fatal("fork: %r"); case 0: /* seal off standard input/output */ close(0); open("/dev/null", OREAD); close(1); open("/dev/null", OWRITE); close(p[1]); fmtinstall('F', fcallfmt); /* debugging */ fmtinstall('D', dirfmt); /* expected by %F */ fmtinstall('M', dirmodefmt); /* expected by %F */ io(); quit(); break; default: close(p[0]); if(mount(p[1], -1, mountpoint, MREPL|MCREATE, "") < 0) fatal("mount failed: %r"); } exits(0); } /*e: function [[main]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[newfid]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /* * lookup an fid. if not found, create a new one. */ Fid * newfid(int fid) { Fid *f, *ff; ff = 0; for(f = fids; f; f = f->next){ if(f->fid == fid){ if(f->busy) return f; else{ ff = f; break; } } else if(!ff && !f->busy) ff = f; } if(ff == 0){ ff = mallocz(sizeof(*f), 1); ff->next = fids; fids = ff; } ff->node = nil; ff->fid = fid; return ff; } /*e: function [[newfid]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[kaproc]] */ /* * a process that sends keep alive messages to * keep the server from shutting down the connection */ int kaproc(void) { int pid; if(!dokeepalive) return -1; switch(pid = rfork(RFPROC|RFMEM)){ case -1: return -1; case 0: break; default: return pid; } while(!dying){ sleep(5000); nop(); } _exits(0); return -1; } /*e: function [[kaproc]] */ /*s: function [[io]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ void io(void) { char *err, buf[ERRMAX]; int n; kapid = kaproc(); while(!dying){ n = read9pmsg(mfd, mdata, messagesize); if(n <= 0){ errstr(buf, sizeof buf); if(buf[0]=='\0' || strstr(buf, "hungup")) exits(""); fatal("mount read: %s\n", buf); } if(convM2S(mdata, n, &thdr) == 0) continue; if(debug) fprint(2, "<-%F\n", &thdr);/**/ if(!fcalls[thdr.type]) err = "bad fcall type"; else err = (*fcalls[thdr.type])(newfid(thdr.fid)); if(err){ rhdr.type = Rerror; rhdr.ename = err; }else{ rhdr.type = thdr.type + 1; rhdr.fid = thdr.fid; } rhdr.tag = thdr.tag; if(debug) fprint(2, "->%F\n", &rhdr);/**/ n = convS2M(&rhdr, mdata, messagesize); if(write(mfd, mdata, n) != n) fatal("mount write"); } } /*e: function [[io]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rnop]] */ char* rnop(Fid *f) { USED(f); return 0; } /*e: function [[rnop]] */ /*s: function [[rversion]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rversion(Fid*) { if(thdr.msize > sizeof(mdata)) rhdr.msize = messagesize; else rhdr.msize = thdr.msize; messagesize = thdr.msize; if(strncmp(thdr.version, "9P2000", 6) != 0) return "unknown 9P version"; rhdr.version = "9P2000"; return nil; } /*e: function [[rversion]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rflush]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rflush(Fid*) { return 0; } /*e: function [[rflush]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rauth]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rauth(Fid*) { return "auth unimplemented"; } /*e: function [[rauth]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rattach]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rattach(Fid *f) { f->busy = 1; f->node = remroot; rhdr.qid = f->node->d->qid; return 0; } /*e: function [[rattach]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rwalk]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rwalk(Fid *f) { Node *np; Fid *nf; char **elems; int i, nelems; char *err; Node *node; /* clone fid */ nf = nil; if(thdr.newfid != thdr.fid){ nf = newfid(thdr.newfid); if(nf->busy) return "newfid in use"; nf->busy = 1; nf->node = f->node; f = nf; } err = nil; elems = thdr.wname; nelems = thdr.nwname; node = f->node; rhdr.nwqid = 0; if(nelems > 0){ /* walk fid */ for(i=0; i<nelems && i<MAXWELEM; i++){ if((node->d->qid.type & QTDIR) == 0){ err = "not a directory"; break; } if(strcmp(elems[i], ".") == 0){ Found: rhdr.wqid[i] = node->d->qid; rhdr.nwqid++; continue; } if(strcmp(elems[i], "..") == 0){ node = node->parent; goto Found; } if(strcmp(elems[i], ".flush.ftpfs") == 0){ /* hack to flush the cache */ invalidate(node); readdir(node); goto Found; } /* some top level names are special */ if((os == Tops || os == VM || os == VMS) && node == remroot){ np = newtopsdir(elems[i]); if(np){ node = np; goto Found; } else { err = nosuchfile; break; } } /* everything else */ node = extendpath(node, s_copy(elems[i])); if(ISCACHED(node->parent)){ /* the cache of the parent is good, believe it */ if(!ISVALID(node)){ err = nosuchfile; break; } if(node->parent->chdirunknown || (node->d->mode & DMSYML)) fixsymbolic(node); } else if(!ISVALID(node)){ /* this isn't a valid node, try cd'ing */ if(changedir(node) == 0){ node->d->qid.type = QTDIR; node->d->mode |= DMDIR; }else{ node->d->qid.type = QTFILE; node->d->mode &= ~DMDIR; } } goto Found; } if(i == 0 && err == 0) err = "file does not exist"; } /* clunk a newly cloned fid if the walk didn't succeed */ if(nf != nil && (err != nil || rhdr.nwqid<nelems)){ nf->busy = 0; nf->fid = 0; } /* if it all worked, point the fid to the enw node */ if(err == nil) f->node = node; return err; } /*e: function [[rwalk]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[ropen]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char * ropen(Fid *f) { int mode; mode = thdr.mode; if(f->node->d->qid.type & QTDIR) if(mode != OREAD) return "permission denied"; if(mode & OTRUNC){ uncache(f->node); uncache(f->node->parent); filedirty(f->node); } else { /* read the remote file or directory */ if(!ISCACHED(f->node)){ filefree(f->node); if(f->node->d->qid.type & QTDIR){ invalidate(f->node); if(readdir(f->node) < 0) return nosuchfile; } else { if(readfile(f->node) < 0) return errstring; } CACHED(f->node); } } rhdr.qid = f->node->d->qid; f->open = 1; f->node->opens++; return 0; } /*e: function [[ropen]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rcreate]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rcreate(Fid *f) { char *name; if((f->node->d->qid.type&QTDIR) == 0) return "not a directory"; name = thdr.name; f->node = extendpath(f->node, s_copy(name)); uncache(f->node); if(thdr.perm & DMDIR){ if(createdir(f->node) < 0) return "permission denied"; } else filedirty(f->node); invalidate(f->node->parent); uncache(f->node->parent); rhdr.qid = f->node->d->qid; f->open = 1; f->node->opens++; return 0; } /*e: function [[rcreate]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rread]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rread(Fid *f) { long off; int n, cnt, rv; Node *np; rhdr.count = 0; off = thdr.offset; cnt = thdr.count; if(cnt > messagesize-IOHDRSZ) cnt = messagesize-IOHDRSZ; if(f->node->d->qid.type & QTDIR){ rv = 0; for(np = f->node->children; np != nil; np = np->sibs){ if(!ISVALID(np)) continue; if(off <= BIT16SZ) break; n = convD2M(np->d, mbuf, messagesize-IOHDRSZ); off -= n; } for(; rv < cnt && np != nil; np = np->sibs){ if(!ISVALID(np)) continue; if(np->d->mode & DMSYML) fixsymbolic(np); n = convD2M(np->d, mbuf + rv, cnt-rv); if(n <= BIT16SZ) break; rv += n; } } else { /* reread file if it's fallen out of the cache */ if(!ISCACHED(f->node)) if(readfile(f->node) < 0) return errstring; CACHED(f->node); rv = fileread(f->node, (char*)mbuf, off, cnt); if(rv < 0) return errstring; } rhdr.data = (char*)mbuf; rhdr.count = rv; return 0; } /*e: function [[rread]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rwrite]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char* rwrite(Fid *f) { long off; int cnt; if(f->node->d->qid.type & QTDIR) return "directories are not writable"; rhdr.count = 0; off = thdr.offset; cnt = thdr.count; cnt = filewrite(f->node, thdr.data, off, cnt); if(cnt < 0) return errstring; filedirty(f->node); rhdr.count = cnt; return 0; } /*e: function [[rwrite]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rclunk]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char * rclunk(Fid *f) { if(fileisdirty(f->node)){ if(createfile(f->node) < 0) fprint(2, "ftpfs: couldn't create %s\n", f->node->d->name); fileclean(f->node); uncache(f->node); } if(f->open){ f->open = 0; f->node->opens--; } f->busy = 0; return 0; } /*e: function [[rclunk]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rremove]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /* * remove is an implicit clunk */ char * rremove(Fid *f) { char *e; e = nil; if(QTDIR & f->node->d->qid.type){ if(removedir(f->node) < 0) e = errstring; } else { if(removefile(f->node) < 0) e = errstring; } uncache(f->node->parent); uncache(f->node); if(e == nil) INVALID(f->node); f->busy = 0; return e; } /*e: function [[rremove]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rstat]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char * rstat(Fid *f) { Node *p; p = f->node->parent; if(!ISCACHED(p)){ invalidate(p); readdir(p); CACHED(p); } if(!ISVALID(f->node)) return nosuchfile; if(p->chdirunknown) fixsymbolic(f->node); rhdr.nstat = convD2M(f->node->d, mbuf, messagesize-IOHDRSZ); rhdr.stat = mbuf; return 0; } /*e: function [[rstat]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[rwstat]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ char * rwstat(Fid *f) { USED(f); return "wstat not implemented"; } /*e: function [[rwstat]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[fatal]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /* * print message and die */ void fatal(char *fmt, ...) { va_list arg; char buf[8*1024]; dying = 1; va_start(arg, fmt); vseprint(buf, buf + (sizeof(buf)-1) / sizeof(*buf), fmt, arg); va_end(arg); fprint(2, "ftpfs: %s\n", buf); if(kapid > 0) postnote(PNGROUP, kapid, "die"); exits(buf); } /*e: function [[fatal]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[safecpy]] */ /* * like strncpy but make sure there's a terminating null */ void* safecpy(void *to, void *from, int n) { char *a = ((char*)to) + n - 1; strncpy(to, from, n); *a = 0; return to; } /*e: function [[safecpy]] */ /*s: function [[seterr]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /* * set the error string */ int seterr(char *fmt, ...) { va_list arg; va_start(arg, fmt); vsnprint(errstring, sizeof errstring, fmt, arg); va_end(arg); return -1; } /*e: function [[seterr]]([[(networking/ip/ftpfs/ftpfs.c)]]) */ /*s: function [[newnode]] */ /* * create a new node */ Node* newnode(Node *parent, String *name) { Node *np; static ulong path; Dir d; np = mallocz(sizeof(Node), 1); if(np == 0) fatal("out of memory"); np->children = 0; if(parent){ np->parent = parent; np->sibs = parent->children; parent->children = np; np->depth = parent->depth + 1; d.dev = 0; /* not stat'd */ } else { /* the root node */ np->parent = np; np->sibs = 0; np->depth = 0; d.dev = 1; } np->remname = name; d.name = s_to_c(name); d.atime = time(0); d.mtime = d.atime; d.uid = nouid; d.gid = nouid; d.muid = nouid; np->fp = 0; d.qid.path = ++path; d.qid.vers = 0; d.qid.type = QTFILE; d.type = 0; np->d = reallocdir(&d, 0); return np; } /*e: function [[newnode]] */ /*s: function [[extendpath]] */ /* * walk one down the local mirror of the remote directory tree */ Node* extendpath(Node *parent, String *elem) { Node *np; for(np = parent->children; np; np = np->sibs) if(strcmp(s_to_c(np->remname), s_to_c(elem)) == 0){ s_free(elem); return np; } return newnode(parent, elem); } /*e: function [[extendpath]] */ /*s: function [[uncache]] */ /* * flush the cached file, write it back if it's dirty */ void uncache(Node *np) { if(fileisdirty(np)) createfile(np); filefree(np); UNCACHED(np); } /*e: function [[uncache]] */ /*s: function [[invalidate]] */ /* * invalidate all children of a node */ void invalidate(Node *node) { Node *np; if(node->opens) return; /* don't invalidate something that's open */ uncachedir(node, 0); /* invalidate children */ for(np = node->children; np; np = np->sibs){ if(np->opens) continue; /* don't invalidate something that's open */ UNCACHED(np); invalidate(np); np->d->dev = 0; } } /*e: function [[invalidate]] */ /*s: function [[newtopsdir]] */ /* * make a top level tops-20 directory. They are automaticly valid. */ Node* newtopsdir(char *name) { Node *np; np = extendpath(remroot, s_copy(name)); if(!ISVALID(np)){ np->d->qid.type = QTDIR; np->d->atime = time(0); np->d->mtime = np->d->atime; np->d->uid = "?uid?"; np->d->gid = "?uid?"; np->d->muid = "?uid?"; np->d->mode = DMDIR|0777; np->d->length = 0; np->d = reallocdir(np->d, 1); if(changedir(np) >= 0) VALID(np); } return np; } /*e: function [[newtopsdir]] */ /*s: function [[fixsymbolic]] */ /* * figure out if a symbolic link is to a directory or a file */ void fixsymbolic(Node *node) { if(changedir(node) == 0){ node->d->mode |= DMDIR; node->d->qid.type = QTDIR; } else node->d->qid.type = QTFILE; node->d->mode &= ~DMSYML; } /*e: function [[fixsymbolic]] */ /*e: networking/ip/ftpfs/ftpfs.c */
OFShare/Algorithm-challenger
洛谷/入门/P3742.cc
/* * Author : OFShare * E-mail : <EMAIL> * Created Time : 2020-02-26 23:00:26 PM * File Name : P3742.cc */ #include <bits/stdc++.h> void debug() { #ifdef Acui freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif } const int N = 1e2 + 5; int n; char x[N], y[N], z[N]; int main() { scanf("%d", &n); scanf("%s %s", x + 1, y + 1); for (int i = 1; i <= n; ++i) { if (y[i] > x[i]) { printf("-1\n"); return 0; } else z[i] = y[i]; } printf("%s", z + 1); return 0; }
luoli233/danbooru
script/fixes/073_change_default_comment_threshold.rb
<gh_stars>100-1000 #!/usr/bin/env ruby require_relative "../../config/environment" User.transaction do users = User.where("comment_threshold > ?", User.anonymous.comment_threshold) p users.count users.update_all(comment_threshold: User.anonymous.comment_threshold) users = User.where("comment_threshold < ?", -100) p users.count users.update_all(comment_threshold: -100) end
luci/luci-go
common/proto/structmask/structmask_test.go
// Copyright 2021 The LUCI Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package structmask import ( "strings" "testing" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/structpb" ) func TestStructMask(t *testing.T) { t.Parallel() cases := []struct { name string mask []*StructMask input string output string }{ { "noop", makeMask(), `{"a": "b"}`, `{"a": "b"}`, }, { "all star 1", makeMask(`*`), `{}`, `{}`, }, { "all star 2", makeMask(`*`, `*`), `{"a": "b", "c": {"d": ["e"]}}`, `{"a": "b", "c": {"d": ["e"]}}`, }, { "field selector", makeMask(`a`), `{"a": "b", "c": {"d": ["e"]}}`, `{"a": "b"}`, }, { "nested field selector", makeMask(`a.b`), `{ "a": {"b": 1, "z": "..."}, "b": 2, "c": {"b": 3} }`, `{"a": {"b": 1}}`, }, { "dict star last", makeMask(`a.*`), `{ "a": {"b": 1, "c": 2}, "b": "zzz" }`, `{ "a": {"b": 1, "c": 2} }`, }, { "dict star not last", makeMask(`*.b`), `{ "a": {"b": 1, "c": 2}, "b": {"z": 123}, "c": 123, "d": [] }`, `{ "a": {"b": 1} }`, }, { "dict star nested", makeMask(`*.b.*`), `{ "f1": 1, "f2": {"z": []}, "f3": {"b": [1, 2, 3]}, "f4": {"b": 123} }`, `{ "f3": {"b": [1, 2, 3]} }`, }, { "list star last", makeMask(`a.*`), `{ "a": [{"a": "b"}, 2, {"a": "b"}], "b": "zzz" }`, `{ "a": [{"a": "b"}, 2, {"a": "b"}] }`, }, { "list star not last", makeMask(`a.*.b`), `{ "a": [{"b": "c"}, 2, {"a": "c"}, null], "b": "zzz" }`, `{ "a": [{"b": "c"}, null, null, null] }`, }, { "list star nested", makeMask(`a.*.*`), `{ "a": [ "skip", null, 123, {"a": "b"}, {"a": {"b": "c"}}, [1, 2, 3] ] }`, `{ "a": [ null, null, null, {"a": "b"}, {"a": {"b": "c"}}, [1, 2, 3] ] }`, }, { "multiple field selectors, no stars", makeMask(`a.a`, `a.b`, `b`), `{ "a": { "a": 1, "b": 2, "c": 3 }, "b": [1, 2, 3], "c": 5 }`, `{ "a": { "a": 1, "b": 2 }, "b": [1, 2, 3] }`, }, { "early leaf nodes, fields", makeMask(`a.b.c`, `a.b`), `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}}, "c": 2 } }`, `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}} } }`, }, { "early leaf nodes, fields, reversed", makeMask(`a.b`, `a.b.c`), `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}}, "c": 2 } }`, `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}} } }`, }, { "early leaf nodes, stars", makeMask(`a.*.c`, `a.*`), `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}}, "c": 2 } }`, `{ "a": { "b": {"c": 1, "d": 2, "e": {"f": 3}}, "c": 2 } }`, }, { "star + field selector merging, simple", makeMask(`*.a`, `a.b`), `{ "a": {"a": 1, "b": 2, "c": 3}, "b": {"a": 1, "b": 2, "c": 3}, "c": 123 }`, `{ "a": {"a": 1, "b": 2}, "b": {"a": 1} }`, }, { "star + field selector merging, deeper", makeMask(`*.a.a`, `a.a.b`), `{ "a": {"a": {"a": 1, "b": 2}}, "b": {"a": {"a": 1, "b": 2}} }`, `{ "a": {"a": {"a": 1, "b": 2}}, "b": {"a": {"a": 1}} }`, }, { "star + field selector merging, deeper, reverse order", makeMask(`a.a.b`, `*.a.a`), `{ "a": {"a": {"a": 1, "b": 2}}, "b": {"a": {"a": 1, "b": 2}} }`, `{ "a": {"a": {"a": 1, "b": 2}}, "b": {"a": {"a": 1}} }`, }, { "list merges, simple", makeMask(`*.*.a`, `a.*.b`), `{ "a": [ {"a": 1, "b": 1}, {"b": 1}, {"c": 1} ], "b": [ {"a": 1, "b": 1}, {"b": 1}, {"c": 1} ] }`, `{ "a": [ {"a": 1, "b": 1}, {"b": 1}, null ], "b": [ {"a": 1}, null, null ] }`, }, { "list merges with nulls", makeMask(`a.*.a`, `*.*.b`), `{ "a": [ {"b": 1, "c": 1}, {"a": 1, "c": 1}, {"c": 1} ] }`, `{ "a": [ {"b": 1}, {"a": 1}, null ] }`, }, { "list merges with nulls, deeper", makeMask(`*.*.*.b`, `x.*.a.c`), `{ "x": [ {"a": {"c": 1}}, {"y": {"b": 1}} ] }`, `{ "x": [ {"a": {"c": 1}}, {"y": {"b": 1}} ] }`, }, { "merging exact same values", makeMask(`a.*`, `*.b`), `{"a": {"b": {"c": 1}}}`, `{"a": {"b": {"c": 1}}}`, }, { "merging scalars into nils", makeMask(`a.*.a`, `*.*`), `{ "a": [ {"b": 1}, 1 ] }`, `{ "a": [ {"b": 1}, 1 ] }`, }, } for _, cs := range cases { t.Run(cs.name, func(t *testing.T) { filter, err := NewFilter(cs.mask) if err != nil { t.Errorf("bad filter: %s", err) return } expected := asProto(cs.output) output := filter.Apply(asProto(cs.input)) if !proto.Equal(output, expected) { t.Errorf("got:\n---------\n%s\n---------\nbut want\n---------\n%s\n---------", asJSON(output), asJSON(expected)) } }) } } func makeMask(masks ...string) []*StructMask { out := make([]*StructMask, len(masks)) for idx, m := range masks { out[idx] = &StructMask{Path: strings.Split(m, ".")} } return out } func asProto(json string) *structpb.Struct { s := &structpb.Struct{} if err := protojson.Unmarshal([]byte(json), s); err != nil { panic(err) } return s } func asJSON(s *structpb.Struct) string { blob, err := (protojson.MarshalOptions{ Multiline: true, Indent: " ", }).Marshal(s) if err != nil { panic(err) } return string(blob) }
jihwahn1018/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/RemoveFenceAgentCommand.java
package org.ovirt.engine.core.bll; import java.util.List; import javax.inject.Inject; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.common.action.FenceAgentCommandParameterBase; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.pm.FenceAgent; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.FenceAgentDao; import org.ovirt.engine.core.dao.VdsDao; public class RemoveFenceAgentCommand<T extends FenceAgentCommandParameterBase> extends FenceAgentCommandBase { @Inject private VdsDao vdsDao; @Inject private FenceAgentDao fenceAgentDao; @Override protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__REMOVE); } @Override protected boolean validate() { if (getParameters() == null || getParameters().getAgent() == null || getParameters().getAgent().getId() == null) { return failValidation(EngineMessage.VDS_REMOVE_FENCE_AGENT_ID_REQUIRED); } // check for removal of last fence agent while PM is enabled in the host Guid vdsId = getParameters().getAgent().getHostId(); VDS host = vdsDao.get(vdsId); if (host == null) { return failValidation(EngineMessage.VDS_INVALID_SERVER_ID); } if (host.isPmEnabled()) { List<FenceAgent> fenceAgents = fenceAgentDao.getFenceAgentsForHost(getVdsId()); if (fenceAgents.size() == 1) { return failValidation(EngineMessage.VDS_REMOVE_LAST_FENCE_AGENT_PM_ENABLED); } } return super.validate(); } @Override protected void executeCommand() { fenceAgentDao.remove(getParameters().getAgent().getId()); setSucceeded(true); } public RemoveFenceAgentCommand(FenceAgentCommandParameterBase parameters, CommandContext cmdContext) { super(parameters, cmdContext); } }
deepnighttwo/inmem-transfer-language
core/src/main/java/com/dnt/itl/ext/ExtensionFunction.java
package com.dnt.itl.ext; /** * User: <NAME> * Date: 2015/4/21 * Time: 20:43 */ public class ExtensionFunction { public static final boolean getResumeRate(double age, String education, double income) { if (income * 0.75 > age) { return true; } return false; } }
CyberCRI/hero-coli-website
Doc/search/classes_70.js
<reponame>CyberCRI/hero-coli-website var searchData= [ ['panelinfos',['PanelInfos',['../class_panel_infos.html',1,'']]], ['peniciline',['Peniciline',['../class_peniciline.html',1,'']]], ['phenofickcontact',['PhenoFickContact',['../class_pheno_fick_contact.html',1,'']]], ['phenolight',['PhenoLight',['../class_pheno_light.html',1,'']]], ['phenospeed',['PhenoSpeed',['../class_pheno_speed.html',1,'']]], ['phenothresholdspreader',['PhenoThresholdSpreader',['../class_pheno_threshold_spreader.html',1,'']]], ['phenotoxic',['PhenoToxic',['../class_pheno_toxic.html',1,'']]], ['phenotype',['Phenotype',['../class_phenotype.html',1,'']]], ['physicalmedium',['PhysicalMedium',['../class_physical_medium.html',1,'']]], ['product',['Product',['../class_product.html',1,'']]], ['promoter',['Promoter',['../class_promoter.html',1,'']]], ['promoterbrick',['PromoterBrick',['../class_promoter_brick.html',1,'']]], ['promoterlexer',['PromoterLexer',['../class_promoter_lexer.html',1,'']]], ['promoterloader',['PromoterLoader',['../class_promoter_loader.html',1,'']]], ['promoternodedata',['PromoterNodeData',['../class_promoter_node_data.html',1,'']]], ['promoterparser',['PromoterParser',['../class_promoter_parser.html',1,'']]], ['promoterproprieties',['PromoterProprieties',['../class_promoter_proprieties.html',1,'']]], ['pushablebox',['PushableBox',['../class_pushable_box.html',1,'']]] ];
EUye9IM/Block_cipher
include/NTL/mat_poly_ZZ.h
<reponame>EUye9IM/Block_cipher #ifndef NTL_mat_poly_ZZ__H #define NTL_mat_poly_ZZ__H #include <NTL/mat_ZZ.h> #include <NTL/ZZX.h> NTL_OPEN_NNS void CharPoly(ZZX& f, const mat_ZZ& M, long deterministic=0); NTL_CLOSE_NNS #endif
charlienzw/LeetCode
java/24/Swap Nodes in Pairs.java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode swapPairs(ListNode head) { if(head == null) return null; if(head.next == null) return head; ListNode temp = head.next; head.next = swapPairs(head.next.next); temp.next = head; return temp; } }
juandopazo/jet
src/form/js/TextareaField.js
<filename>src/form/js/TextareaField.js<gh_stars>1-10 $.TextareaField = $.Base.create('textarea', $.FormField, [], {}, { CONTENT_TEMPLATE: '<textarea/>' });
lessunc/python-guanabara
task013.py
<gh_stars>10-100 #coding: utf-8 #-------------------------------------------------------------- # Um algoritmo que recebe o salário de um funcionário e mostra # seu novo salário com 15% de aumento. #-------------------------------------------------------------- # Reajuste Salarial - Exercício #013 #----------------------------------------------------------- atual = float(input('Qual o salário atual do funcionário? : R$')) reajuste = atual * 15 /100 print(f'''Esse salário de {atual} foi atualizado devido ao aumento de 15% para : \033[1m"{atual + reajuste}" \033[m''')
thandile/msf_communique
app/src/main/java/com/example/msf/msf/API/Models/Patients.java
<filename>app/src/main/java/com/example/msf/msf/API/Models/Patients.java package com.example.msf.msf.API.Models; import com.google.gson.annotations.SerializedName; /** * Created by Thandile on 2016/09/20. */ public class Patients { @SerializedName("id") private String id; @SerializedName("other_names") private String first_name; @SerializedName("last_name") private String last_name; @SerializedName("sex") private String sex; @SerializedName("birth_date") private String birth_date; @SerializedName("contact_number") private String contact_number; @SerializedName("second_contact_number") private String second_contact_number; @SerializedName("third_contact_number") private String third_contact_number; @SerializedName("identifier") private String identifier; @SerializedName("location") private String location; @SerializedName("enrolled_programs") private String[] enrolled_programs; @SerializedName("treatment_start_date") private String treatment_start_date; @SerializedName("interim_outcome") private String interim_outcome; public String getInterim_outcome() { return interim_outcome; } public void setInterim_outcome(String interim_outcome) { this.interim_outcome = interim_outcome; } public String getTreatment_start_date() { return treatment_start_date; } public void setTreatment_start_date(String treatment_start_date) { this.treatment_start_date = treatment_start_date; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getThird_contact_number() { return third_contact_number; } public void setThird_contact_number(String third_contact_number) { this.third_contact_number = third_contact_number; } public String getSecond_contact_number() { return second_contact_number; } public void setSecond_contact_number(String second_contact_number) { this.second_contact_number = second_contact_number; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Patients(String id, String first_name, String last_name, String sex, String birth_date, String contact_number, String second_contact_number, String third_contact_number, String identifier, String location, String[] enrolled_programs, String treatment_start_date, String interim_outcome, String reference_health_centre) { this.id = id; this.first_name = first_name; this.last_name = last_name; this.sex = sex; this.birth_date = birth_date; this.contact_number = contact_number; this.second_contact_number = second_contact_number; this.third_contact_number = third_contact_number; this.identifier = identifier; this.location = location; this.enrolled_programs = enrolled_programs; this.treatment_start_date = treatment_start_date; this.interim_outcome = interim_outcome; this.reference_health_centre = reference_health_centre; } @SerializedName("reference_health_centre") private String reference_health_centre; public String getReference_health_centre() { return reference_health_centre; } public void setReference_health_centre(String reference_health_centre) { this.reference_health_centre = reference_health_centre; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getBirth_date() { return birth_date; } public void setBirth_date(String birth_date) { this.birth_date = birth_date; } public String getContact_number() { return contact_number; } public void setContact_number(String contact_number) { this.contact_number = contact_number; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String[] getEnrolled_programs() { return enrolled_programs; } public void setEnrolled_programs(String[] enrolled_programs) { this.enrolled_programs = enrolled_programs; } public Patients(){ } }