repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
systemaker/Flask-Easy-Template
app/modules/events/models.py
#!/usr/bin/python # -*- coding: utf-8 -*- # ------- IMPORT DEPENDENCIES ------- import datetime import decimal from sqlalchemy import desc from sqlalchemy import or_ # ------- IMPORT LOCAL DEPENDENCIES ------- from app import db import time from app.helpers import * from app.modules.localization.controllers import get_locale, get_timezone from app.modules.users.models import User from app.modules.items.models import Item from app.modules.addresses.models import Address class UserEvent(db.Model): __tablename__ = "userevent" #__table_args__ = db.PrimaryKeyConstraint('user_id', 'event_id') guest_id = db.Column(db.Integer,db.ForeignKey('User.id'), primary_key=True) in_event_id = db.Column(db.Integer,db.ForeignKey('Event.id'), primary_key=True) # bidirectional attribute/collection of "user"/"userevents" and "event"/"userevents". Return object guest = db.relationship("User", back_populates = "userevents") in_event = db.relationship("Event", back_populates ="userevents") # so you can do : # userevent1.append(User(username = 'test'))) # or userevent1.append(user1) # or UserEvent(user1, Event(title_en_US = 'test'), options="test") # Extra data options = db.Column(db.Text()) updated_at = db.Column(db.Integer, default=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow()), onupdate=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow())) created_at = db.Column(db.Integer, default=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow())) # updated_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()), onupdate=time.mktime(datetime.utcnow().timetuple())) # created_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple())) def __repr__(self): # return '<UserEvent: {}>'.format(self.id) return '<UserEvent %r - %r >' % (self.guest_id, self.in_event_id) class Event(db.Model): __tablename__ = "Event" id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String(255), index=True) title_en_US = db.Column(db.String(255), index=True, unique=True) title_fr_FR = db.Column(db.String(255), index=True, unique=True) description_en_US = db.Column(db.Text()) description_fr_FR = db.Column(db.Text()) # amount in decimal , precision=10, scale=2 . amount = db.Column(db.Numeric(10,2), nullable=False, default=0.0) # MANY-TO-ONE relationship with the User model # the backref argument in the user field allows us to access events from the User model # as simple as user.events in our controllers. user_id = db.Column(db.Integer, db.ForeignKey('User.id')) # a bidirectional relationship in many-to-one. Return object user = db.relationship('User', back_populates='events') # MANY-TO-ONE relationship with the Item model # the backref argument in the item field allows us to access events from the Item model # as simple as item.events in our controllers. item_id = db.Column(db.Integer, db.ForeignKey('Item.id')) # a bidirectional relationship in many-to-one. Return object item = db.relationship('Item', back_populates='events') # MANY-TO-ONE relationship with the Address model # the backref argument in the address field allows us to access events from the Address model # as simple as address.events in our controllers. address_id = db.Column(db.Integer, db.ForeignKey('Address.id')) # a bidirectional relationship in many-to-one. Return object address = db.relationship('Address', back_populates='events') # MANY-TO-MANY relationship with with EXTRA_DATA association and the User model as Guest # the cascade will delete orphaned userevents userevents = db.relationship('UserEvent', back_populates='in_event', lazy='dynamic', cascade="all, delete-orphan") # or Get all users in view only mode guests = db.relationship('User', secondary='userevent', viewonly=True, back_populates='in_events', lazy='dynamic') """ Return UserEvent objects collection and requires that child objects are associated with an association instance before being appended to the parent; similarly, access from parent to child goes through the association object: so to append in_events via association guest1.guestdates.append(UserEvent(in_event = Event(title_en_US = 'test'))) or UserEvent(guest = guest1, Event(title_en_US = 'test'), extra_data="test") To iterate through in_events objects via association, including association attributes for guestdate in guest.guestdates: print(guestdate.extra_data) print(guestdate.in_event) WARNING : So don't use directly guest.in_events.append(Event(title_en_US = 'test')) cause it's redundant, it will cause a duplicate INSERT on Association with guest.guestdates.append(UserEvent(in_event=date1)) add viewonly=True on secondary relationship to stop edit, create or delete operations here """ start = db.Column(db.Integer, index=True) end = db.Column(db.Integer, index=True) days = db.Column(db.Integer, index=True) allday = db.Column(db.Boolean, index=True) status = db.Column(db.String(255), index=True) # is_active usually returns True. # This should return False only in cases where we have disabled event. is_active = db.Column(db.Boolean, index=True, nullable=False, default=1) updated_at = db.Column(db.Integer, default=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow()), onupdate=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow())) created_at = db.Column(db.Integer, default=string_datetime_utc_to_string_timestamp_utc(datetime.utcnow())) # updated_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple()), onupdate=time.mktime(datetime.utcnow().timetuple())) # created_at = db.Column(db.Integer, default=time.mktime(datetime.utcnow().timetuple())) def all_data(self, page, LISTINGS_PER_PAGE): return Event.query.order_by(desc(Event.created_at)).paginate(page, LISTINGS_PER_PAGE, False) def read_data(self, some_id): event = Event.query.filter(Event.id == some_id).first_or_404() return event def create_data(self, form): # dateTime conversion to timestamp timestamp_start = string_datetime_utc_to_string_timestamp_utc(form['start']) timestamp_end = string_datetime_utc_to_string_timestamp_utc(form['end']) calculate_days = (form['end'] - form['start']).days event = Event( type = form['type'], title_en_US=form['title_en_US'], title_fr_FR=form['title_fr_FR'], description_en_US=form['description_en_US'], description_fr_FR=form['description_fr_FR'], amount = decimal.Decimal(form['amount']), user = form['user'], item = form['item'], address = form['address'], # convert string to integer format start = int(timestamp_start), # convert string to integer format end = int(timestamp_end), # days = int(form['days']), days = int(calculate_days), allday = form['allday'], status = form['status'], is_active = form['is_active'] ) # MANY-TO-MANY Relationship for guest in form['guests']: userevent = UserEvent(guest = guest, in_event = event) event.userevents.append(userevent) db.session.add(event) db.session.commit() def update_data(self, some_id, form ): event = Event.query.get_or_404(some_id) calculate_days = (form['end'] - form['start']).days event.type = form['type'] event.title_en_US = form['title_en_US'] event.title_fr_FR = form['title_fr_FR'] event.description_en_US = form['description_en_US'] event.description_fr_FR = form['description_fr_FR'] event.amount = decimal.Decimal(form['amount']) event.user = form['user'] event.item = form['item'] event.address = form['address'] # dateTime conversion to timestamp timestamp_start = string_datetime_utc_to_string_timestamp_utc(form['start']) # convert string to integer format event.start = int(timestamp_start) # dateTime conversion to timestamp timestamp_end = string_datetime_utc_to_string_timestamp_utc(form['end']) # convert string to integer format event.end = int(timestamp_end) # event.days = form['days'] event.days = int(calculate_days) event.allday = form['allday'] event.status = form['status'] event.is_active = form['is_active'] # MANY-TO-MANY Relationship event.userevents = [] for guest in form['guests']: userevent = UserEvent(guest = guest, in_event = event) event.userevents.append(userevent) db.session.commit() def destroy_data(self, some_id ): event = Event.query.get_or_404(some_id) db.session.delete(event) db.session.commit() def __repr__(self): # return '<Event: {}>'.format(self.id) return '<Event %r>' % self.id
reachlocal/sidekiq-cleaner
test/test_extensions.rb
# frozen_string_literal: true require_relative 'helper' require 'sidekiq/api' require 'active_record' require 'action_mailer' Sidekiq::Extensions.enable_delay! describe Sidekiq::Extensions do before do Sidekiq.redis {|c| c.flushdb } end class MyModel < ActiveRecord::Base def self.long_class_method raise "Should not be called!" end end it 'allows delayed execution of ActiveRecord class methods' do assert_equal [], Sidekiq::Queue.all.map(&:name) q = Sidekiq::Queue.new assert_equal 0, q.size MyModel.delay.long_class_method assert_equal ['default'], Sidekiq::Queue.all.map(&:name) assert_equal 1, q.size end it 'uses and stringifies specified options' do assert_equal [], Sidekiq::Queue.all.map(&:name) q = Sidekiq::Queue.new('notdefault') assert_equal 0, q.size MyModel.delay(queue: :notdefault).long_class_method assert_equal ['notdefault'], Sidekiq::Queue.all.map(&:name) assert_equal 1, q.size end it 'allows delayed scheduling of AR class methods' do ss = Sidekiq::ScheduledSet.new assert_equal 0, ss.size MyModel.delay_for(5.days).long_class_method assert_equal 1, ss.size end it 'allows until delayed scheduling of AR class methods' do ss = Sidekiq::ScheduledSet.new assert_equal 0, ss.size MyModel.delay_until(1.day.from_now).long_class_method assert_equal 1, ss.size end class UserMailer < ActionMailer::Base def greetings(a, b) raise "Should not be called!" end end it 'allows delayed delivery of ActionMailer mails' do assert_equal [], Sidekiq::Queue.all.map(&:name) q = Sidekiq::Queue.new assert_equal 0, q.size UserMailer.delay.greetings(1, 2) assert_equal ['default'], Sidekiq::Queue.all.map(&:name) assert_equal 1, q.size end it 'allows delayed scheduling of AM mails' do ss = Sidekiq::ScheduledSet.new assert_equal 0, ss.size UserMailer.delay_for(5.days).greetings(1, 2) assert_equal 1, ss.size end it 'allows until delay scheduling of AM mails' do ss = Sidekiq::ScheduledSet.new assert_equal 0, ss.size UserMailer.delay_until(5.days.from_now).greetings(1, 2) assert_equal 1, ss.size end class SomeClass def self.doit(arg) end end it 'allows delay of any ole class method' do q = Sidekiq::Queue.new assert_equal 0, q.size SomeClass.delay.doit(Date.today) assert_equal 1, q.size end module SomeModule def self.doit(arg) end end it 'logs large payloads' do output = capture_logging(Logger::WARN) do SomeClass.delay.doit('a' * 8192) end assert_match(/#{SomeClass}.doit job argument is/, output) end it 'allows delay of any module class method' do q = Sidekiq::Queue.new assert_equal 0, q.size SomeModule.delay.doit(Date.today) assert_equal 1, q.size end it 'allows Psych to serialize anonymous structs' do obj = Struct.new(:attribute).new(my: 'data') assert_equal obj.attribute, Psych.load(Psych.dump(obj)).attribute end end
gxing19/Design-Patterns-Java
src/main/java/com/gxitsky/structural/bridge/full/ConcreteImplementorB.java
package com.gxitsky.structural.bridge.full; /** * @author gxing * @desc 具体实现 * @date 2021/6/18 */ public class ConcreteImplementorB implements Implementor { @Override public void operationImpl() { System.out.println("-----> 具体实现操作 ConcreteImplementorB"); } }
TheoSaify/Yolo-Detector
SURF.py
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('img21.jpg',0) # Create SURF object. You can specify params here or later. # Here I set Hessian Threshold to 400 # surf = cv2.SURF(400) surf = cv2.xfeatures2d.SURF_create() # Find keypoints and descriptors directly kp, des = surf.detectAndCompute(img,None) len(kp) # Check present Hessian threshold # print(surf.hessianThreshold) # We set it to some 50000. Remember, it is just for representing in picture. # In actual cases, it is better to have a value 300-500 # surf.hessianThreshold = 50000 # Again compute keypoints and check its number. kp, des = surf.detectAndCompute(img,None) print(len(kp)) img2 = cv2.drawKeypoints(img,kp,None,(255,0,0),4) plt.imshow(img2) plt.show()
jhu-idc/idc-isle-dc
tests/12-media-tests/testcafe/media_formats.spec.js
import { adminUser } from "./roles.js"; import { findMediaOf } from "./util.js"; import { tryUntilTrue } from "./util.js"; import { download } from "./util.js"; import { uploadImageInUI , uploadFileInUI } from "./util.js"; fixture`Media format tests` .page`https://islandora-idc.traefik.me/migrate_source_ui`.beforeEach( async (t) => { await t.useRole(adminUser); } ); test("Migrate tiff", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated Tiff Object"); // 4 for Tif, service jpg, thumbnail jpg, FITS file return media.length == 4; }) ) .eql(true, "Did not find TIFF derivatives"); }); test("Upload tiff in UI", async (t) => { const file = await download( "http://migration-assets/assets/image/formats/tiff.tif" ); await uploadImageInUI(t, "Uploaded Tiff Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded Tiff Object"); // 4 for Tif, service jpg, thumbnail jpg, FITS file return media.length == 4; }) ) .eql(true, "Did not find TIFF derivatives"); }); test("Migrate jpeg 2000", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated JPEG2000 Object"); // 4 for jp2000, service jpg, thumbnail jpg, FITS file return media.length == 4; }) ) .eql(true, "Did not find JPEG 2000 derivatives"); }); test("Upload jpeg 2000 in UI", async (t) => { const file = await download( "http://migration-assets/assets/image/formats/jp2.jp2" ); await uploadImageInUI(t, "Uploaded JPEG2000 Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded JPEG2000 Object"); // 4 for jp2000, service jpg, thumbnail jpg, FITS file return media.length == 4; }) ) .eql(true, "Did not find jpg 2000 derivatives"); }); test("Migrate Geo Tiff", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated Geo Tiff Object"); // the geo tiff and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find GEO TIF derivatives"); }); test("Upload Geo Tiff in UI", async (t) => { const file = await download( "http://migration-assets/assets/file/NEFF1851_GEO.tfw" ); await uploadFileInUI(t, "Uploaded Geo Tiff Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded Geo Tiff Object"); // the geo tiff and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find Geo Tif derivatives"); }); test("Migrate Zip File", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated Zip Object"); // the zip and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find Zip derivatives"); }); test("Upload Zip in UI", async (t) => { const file = await download( "http://migration-assets/assets/file/file_test.zip" ); await uploadFileInUI(t, "Uploaded Zip Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded Zip Object"); // the zip and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find Zip derivatives"); }); test("Migrate Tar File", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated Tar Object"); // the tar and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find Tar derivatives"); }); test("Upload Tar in UI", async (t) => { const file = await download( "http://migration-assets/assets/file/file_test.tar" ); await uploadFileInUI(t, "Uploaded Tar Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded Tar Object"); // the tar and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find Tar derivatives"); }); test("Migrate GZip File", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated GZip Object"); // the gzip and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find GZip derivatives"); }); test("Upload GZip in UI", async (t) => { const file = await download( "http://migration-assets/assets/file/file_test.tar.gz" ); await uploadFileInUI(t, "Uploaded GZip Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded GZip Object"); // the gzip and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find GZip derivatives"); }); test("Migrate TGZ File", async (t) => { await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Migrated TGZ Object"); // the tgz and just a FITS deriv console.log("tgz count: " + media.length); return media.length == 2; }) ) .eql(true, "Did not find TGZ derivatives"); }); test("Upload TGZ in UI", async (t) => { const file = await download( "http://migration-assets/assets/file/file_test.tgz" ); await uploadFileInUI(t, "Uploaded TGZ Object", file, "Group A"); await t .expect( await tryUntilTrue(async () => { const media = await findMediaOf(t, "Uploaded TGZ Object"); // the tgz and just a FITS deriv return media.length == 2; }) ) .eql(true, "Did not find TGZ derivatives"); });
adipeterca/Laborator-PA
Lab6/src/Compulsory/ControlPanel.java
package Compulsory; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.plaf.ActionMapUIResource; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; public class ControlPanel extends JPanel { final MainFrame frame; JButton saveBtn = new JButton("Save"); JButton loadBtn = new JButton("Load"); JButton resetBtn = new JButton("Reset"); JButton exitBtn = new JButton("Exit"); public ControlPanel(MainFrame frame) { this.frame = frame; init(); } private void init() { //change the default layout manager (just for fun) setLayout(new GridLayout(1, 4)); // Add all the buttons add(saveBtn, BorderLayout.CENTER); add(loadBtn, BorderLayout.CENTER); add(resetBtn, BorderLayout.CENTER); add(exitBtn, BorderLayout.CENTER); //configure listeners for all buttons saveBtn.addActionListener(this::save); loadBtn.addActionListener(this::load); resetBtn.addActionListener(this::reset); exitBtn.addActionListener(this::exit); } private void save(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); // Only choose files of this type fileChooser.setFileFilter(new FileNameExtensionFilter("*.png", "png")); // If the user selects to save the file int option = fileChooser.showSaveDialog(null); if (option == JFileChooser.APPROVE_OPTION) { File fileToSave = fileChooser.getSelectedFile(); try { ImageIO.write(frame.canvas.image, "PNG", new File(fileToSave.getAbsolutePath())); System.out.println("Saved an image."); } catch (IOException exc) { System.out.println(exc.getMessage()); } } else if (option == JFileChooser.CANCEL_OPTION) { System.out.println("Canceled the saving operation."); } else { System.out.println("An error occurred during saving."); } } private void load(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileNameExtensionFilter("*.png", "png")); // The user selected to load an image int option = fileChooser.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { try { Image image = ImageIO.read(new File(fileChooser.getSelectedFile().getAbsolutePath())); frame.getCanvas().graphics.drawImage(image, 0, 0, frame.getCanvas()); frame.getCanvas().repaint(); System.out.println("Loaded an image."); } catch (IOException exc) { System.out.println(exc.getMessage()); } } else if (option == JFileChooser.CANCEL_OPTION) { System.out.println("Canceled the loading operation."); } else { System.out.println("An error occurred during loading."); } } private void reset(ActionEvent e) { frame.canvas.graphics.setColor(new Color(255, 255, 255)); frame.canvas.graphics.fillRect(0, 0, frame.getCanvas().getWidth(), frame.getCanvas().getHeight()); frame.canvas.repaint(); System.out.println("Reset the canvas."); } private void exit(ActionEvent e) { System.out.println("Exited with success!"); System.exit(0); } }
KwonSunJae/CLOUD_AI_WEB_BATMAN_BATNAM_2021
WEB/batman/src/container/home/Runway/RunwayCreate.cntr.js
<reponame>KwonSunJae/CLOUD_AI_WEB_BATMAN_BATNAM_2021 import { useState } from "react"; import Box from "@mui/material/Box"; import Stepper from "@mui/material/Stepper"; import Step from "@mui/material/Step"; import StepLabel from "@mui/material/StepLabel"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; const steps = ["활주로 이름 및 방위 설정", "섹터 만들기", "위치 설정", "확인"]; const LinearStepper = () => { const [activeStep, setActiveStep] = useState(0); const handleNext = () => { setActiveStep(activeStep + 1); }; const handleBack = () => { setActiveStep(activeStep - 1); }; return ( <Box sx={{ width: "100%" }}> <Stepper activeStep={activeStep}> {steps.map((label, index) => { const stepProps = {}; const labelProps = {}; // if (isStepOptional(index)) { // labelProps.optional = ( // <Typography variant="caption">Optional</Typography> // ); // } // if (isStepSkipped(index)) { // stepProps.completed = false; // } return ( <Step key={label} {...stepProps}> <StepLabel {...labelProps}>{label}</StepLabel> </Step> ); })} </Stepper> <Button disabled={activeStep === 0} onClick={handleBack}> Back </Button> {steps[activeStep]} <Button disabled={activeStep === steps.length} onClick={handleNext}> {activeStep >= steps.length - 1 ? "Finish" : "Next"} </Button> </Box> ); }; export default LinearStepper;
lmjacksoniii/hazelcast-aws
hazelcast/src/main/java/com/hazelcast/internal/partition/PartitionRuntimeState.java
<reponame>lmjacksoniii/hazelcast-aws /* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.partition; import com.hazelcast.internal.partition.impl.PartitionDataSerializerHook; import com.hazelcast.nio.Address; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.hazelcast.internal.partition.InternalPartition.MAX_REPLICA_COUNT; import static com.hazelcast.util.StringUtil.LINE_SEPARATOR; public final class PartitionRuntimeState implements IdentifiedDataSerializable { // used for writing state private Map<Address, Integer> addressToIndexes; // used for reading state private Address[] addresses; private int[][] minimizedPartitionTable; private int version; private Collection<MigrationInfo> completedMigrations; // used to know ongoing migrations when master changed private MigrationInfo activeMigration; private Address endpoint; public PartitionRuntimeState() { } public PartitionRuntimeState(InternalPartition[] partitions, Collection<MigrationInfo> migrationInfos, int version) { this.version = version; completedMigrations = migrationInfos != null ? migrationInfos : Collections.<MigrationInfo>emptyList(); addressToIndexes = createAddressToIndexMap(partitions); minimizedPartitionTable = createMinimizedPartitionTable(partitions); } private int[][] createMinimizedPartitionTable(InternalPartition[] partitions) { int[][] partitionTable = new int[partitions.length][MAX_REPLICA_COUNT]; for (InternalPartition partition : partitions) { int[] indexes = partitionTable[partition.getPartitionId()]; for (int replicaIndex = 0; replicaIndex < MAX_REPLICA_COUNT; replicaIndex++) { Address address = partition.getReplicaAddress(replicaIndex); if (address == null) { indexes[replicaIndex] = -1; } else { int index = addressToIndexes.get(address); indexes[replicaIndex] = index; } } } return partitionTable; } private Map<Address, Integer> createAddressToIndexMap(InternalPartition[] partitions) { Map<Address, Integer> map = new HashMap<Address, Integer>(); int addressIndex = 0; for (InternalPartition partition : partitions) { for (int i = 0; i < MAX_REPLICA_COUNT; i++) { Address address = partition.getReplicaAddress(i); if (address == null) { continue; } if (map.containsKey(address)) { continue; } map.put(address, addressIndex++); } } return map; } public Address[][] getPartitionTable() { if (addresses == null) { addresses = new Address[addressToIndexes.size()]; for (Map.Entry<Address, Integer> entry : addressToIndexes.entrySet()) { addresses[entry.getValue()] = entry.getKey(); } } int length = minimizedPartitionTable.length; Address[][] result = new Address[length][MAX_REPLICA_COUNT]; for (int partitionId = 0; partitionId < length; partitionId++) { Address[] replicas = result[partitionId]; int[] addressIndexes = minimizedPartitionTable[partitionId]; for (int replicaIndex = 0; replicaIndex < addressIndexes.length; replicaIndex++) { int index = addressIndexes[replicaIndex]; if (index != -1) { Address address = addresses[index]; assert address != null; replicas[replicaIndex] = address; } } } return result; } public Address getEndpoint() { return endpoint; } public void setEndpoint(final Address endpoint) { this.endpoint = endpoint; } public Collection<MigrationInfo> getCompletedMigrations() { return completedMigrations != null ? completedMigrations : Collections.<MigrationInfo>emptyList(); } public MigrationInfo getActiveMigration() { return activeMigration; } public void setActiveMigration(MigrationInfo activeMigration) { this.activeMigration = activeMigration; } public void setCompletedMigrations(Collection<MigrationInfo> completedMigrations) { this.completedMigrations = completedMigrations; } @Override public void readData(ObjectDataInput in) throws IOException { version = in.readInt(); int memberCount = in.readInt(); addresses = new Address[memberCount]; for (int i = 0; i < memberCount; i++) { Address address = new Address(); address.readData(in); int index = in.readInt(); assert addresses[index] == null : "Duplicate address! Address: " + address + ", index: " + index + ", addresses: " + Arrays.toString(addresses); addresses[index] = address; } int partitionCount = in.readInt(); minimizedPartitionTable = new int[partitionCount][MAX_REPLICA_COUNT]; for (int i = 0; i < partitionCount; i++) { int[] indexes = minimizedPartitionTable[i]; for (int ix = 0; ix < MAX_REPLICA_COUNT; ix++) { indexes[ix] = in.readInt(); } } if (in.readBoolean()) { activeMigration = new MigrationInfo(); activeMigration.readData(in); } int k = in.readInt(); if (k > 0) { completedMigrations = new ArrayList<MigrationInfo>(k); for (int i = 0; i < k; i++) { MigrationInfo migrationInfo = new MigrationInfo(); migrationInfo.readData(in); completedMigrations.add(migrationInfo); } } } @SuppressWarnings("checkstyle:npathcomplexity") @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(version); if (addressToIndexes == null) { out.writeInt(addresses.length); for (int index = 0; index < addresses.length; index++) { Address address = addresses[index]; address.writeData(out); out.writeInt(index); } } else { int memberCount = addressToIndexes.size(); out.writeInt(memberCount); for (Map.Entry<Address, Integer> entry : addressToIndexes.entrySet()) { Address address = entry.getKey(); address.writeData(out); int index = entry.getValue(); out.writeInt(index); } } out.writeInt(minimizedPartitionTable.length); for (int[] indexes : minimizedPartitionTable) { for (int ix = 0; ix < MAX_REPLICA_COUNT; ix++) { out.writeInt(indexes[ix]); } } if (activeMigration != null) { out.writeBoolean(true); activeMigration.writeData(out); } else { out.writeBoolean(false); } if (completedMigrations != null) { int k = completedMigrations.size(); out.writeInt(k); for (MigrationInfo migrationInfo : completedMigrations) { migrationInfo.writeData(out); } } else { out.writeInt(0); } } @Override public String toString() { StringBuilder sb = new StringBuilder("PartitionRuntimeState [" + version + "]{" + LINE_SEPARATOR); if (addressToIndexes == null) { //addressToIndexes is null after deserialization. let's use the array for (Address address : addresses) { sb.append(address).append(LINE_SEPARATOR); } } else { for (Address address : addressToIndexes.keySet()) { sb.append(address).append(LINE_SEPARATOR); } } sb.append(", completedMigrations=").append(completedMigrations); sb.append('}'); return sb.toString(); } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @Override public int getFactoryId() { return PartitionDataSerializerHook.F_ID; } @Override public int getId() { return PartitionDataSerializerHook.PARTITION_RUNTIME_STATE; } }
degarashi/boomstick
cone3D.cpp
#include "geom3D.hpp" namespace boom { namespace geo3d { namespace { //! 直線と,原点からZ方向へ伸びる無限円錐との交点を求める (内部関数) /*! @param[in] rad_d 円錐の長さ1に対する半径の割合 @param[in] q 直線オフセット @param[in] v 直線の傾き @return 交点の0番目のtの値, 交点の1番目のtの値, 交点の数 */ std::tuple<float,float,int> CrossCone(float rad_d, const Vec3& q, const Vec3& v) { using spn::Square; float a = Square(v.x) + Square(v.y) + Square(rad_d*v.z), b = 2*q.x*v.x + 2*q.y*v.y + 2*Square(rad_d)*q.z*v.z, c = Square(q.x) + Square(q.y) - Square(rad_d*q.z); float D = Square(b)-4*a*c; if(std::fabs(D) <= Point::NEAR_THRESHOLD) { float val = -b/(2*a); return std::make_tuple(val, val, 1); } if(D <= 0) return std::make_tuple(1e8f, 1e8f, 0); D = std::sqrt(D); float t0 = (-b + D) / (2*a), t1 = (-b - D) / (2*a); return std::make_tuple(t0, t1, 2); } //! 直線と, 原点からcdir方向へ伸びる無限円錐との交点を求める (内部関数) /*! @param[in] rad_d 円錐の長さ1に対する半径の割合 @param[in] cdir 円錐の方向 @param[in] ofs 直線オフセット @param[in] dir 直線の方向 @return 交点の0番目のtの値, 交点の1番目のtの値, 交点の数 */ std::tuple<float,float,int> _NearConeLine(float rad_d, const Vec3& cdir, const Vec3& ofs, const Vec3& dir) { // ofsとdirを円錐座標系へ変換 Vec3 yA(0,1,0), xA; if(std::fabs(cdir.y - 1.0f) <= Point::NEAR_THRESHOLD) yA = Vec3(1,0,0); xA = yA % cdir; xA.normalize(); yA = cdir % xA; Mat33 m(xA.x, yA.x, cdir.x, xA.y, yA.y, cdir.y, xA.z, yA.z, cdir.z); int nVal; float f0,f1; std::tie(f0,f1,nVal) = CrossCone(rad_d, ofs * m, dir * m); if(nVal == 0) return std::make_tuple(0.0f,0.0f,0); return std::make_tuple(f0,f1,nVal); } //! 円錐と直線の交差判定 /*! @param[in] cone 円錐クラス @param[in] st 直線クラス @return 交点の0番目の座標, 交点の1番目の座標, 交点の数 */ std::tuple<Vec3,Vec3,int> CrossConeLineV(const Cone& cone, const Line& st) { int nf; float f0,f1; std::tie(f0,f1,nf) = _NearConeLine(cone.radius / cone.length, cone.dir, st.pos - cone.center, st.dir); return std::make_tuple(st.pos+st.dir*f0, st.pos+st.dir*f1, nf); } std::tuple<float,float,int> CrossConeLineF(const Cone& cone, const Line& st) { return _NearConeLine(cone.radius / cone.length, cone.dir, st.pos - cone.center, st.dir); } } Cone::Cone(const Vec3& c, const Vec3& d, float rad, float len): center(c), dir(d), radius(rad), length(len) {} Sphere Cone::bs_getBVolume() const { return Sphere{}; } Mat33 Cone::bs_getInertia() const { throw std::runtime_error("not implemented yet"); } float Cone::bs_getArea() const { return spn::Square(radius) * length * (1.f/3); } Vec3 Cone::bs_getCenter() const { return center + dir * length * .5f; } Vec3 Cone::bs_getGCenter() const { return center + dir * length * (1.f/4); } float Cone::getAngle() const { float r = radius / length; return std::atan(r); } bool Cone::hit(const Plane& p) const { // 始点と末端の線分が平面と交差していればtrue Vec3 vEnd = center + dir*length; if(Segment(center, vEnd).crossPoint(p)) return true; // tmp=平面への最短方向 Vec3 tmp = dir % p.getNormal(); float len = tmp.length(); if(std::fabs(len) <= Point::NEAR_THRESHOLD) return false; tmp = dir % tmp; tmp /= len; vEnd += tmp * radius; return p.dot(vEnd) <= 0; } bool Cone::hit(const Segment& s) const { int nc; float f0,f1; std::tie(f0,f1,nc) = CrossConeLineF(*this, s.asLine()); float len = s.getLength(); return spn::IsInRange(f0, 0.0f, len) || spn::IsInRange(f1, 0.0f, len); } bool Cone::hit(const Vec3& p) const { Vec3 toP = p - center; float d = toP.dot(dir); if(d > length) return false; return (center + dir*d).dist_sq(p) <= radius * d / length; } Vec3 Cone::support(const Vec3& dir) const { // 側面の線 Vec3 endP = center + this->dir * length; Vec3 tv = dir % this->dir; tv = this->dir % tv; tv.normalize(); tv = endP + tv*radius; if(this->dir.dot(dir) >= 1.0f-1e-5f) return endP; float f0 = center.dot(dir), f1 = tv.dot(dir); if(f0 > f1) return center; return tv; } std::pair<Vec3,float> Cone::nearestPoint(const Plane& plane) const { const auto& nml = plane.getNormal(); Vec3 bnml = nml % dir; bnml %= dir; Vec3 ret = center + dir*length + bnml*radius; return std::make_pair(ret, plane.dot(ret)); } Cone Cone::operator * (const AMat43& m) const { Cone c; c.center = center.asVec4(1) * m; c.dir = dir.asVec4(0) * m; c.dir -= c.center; c.dir.normalize(); c.radius = radius; c.length = length; return c; } std::ostream& operator << (std::ostream& os, const Cone& c) { return os << "Cone(3d) [ center: " << c.center << std::endl << "dir: " << c.dir << ']'; } } }
cheriodone/H7-TOOL_STM32H7_App
User/daplink/source/daplink/cmsis-dap/debug_ca.h
<reponame>cheriodone/H7-TOOL_STM32H7_App<filename>User/daplink/source/daplink/cmsis-dap/debug_ca.h /** * @file debug_ca.h * @brief Access to ARM DAP (Cortex-A) using CMSIS-DAP protocol * * DAPLink Interface Firmware * Copyright (c) 2009-2016, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DEBUG_CA_H #define DEBUG_CA_H #include "debug_cm.h" // Debug registers #define DEBUG_REGSITER_BASE (0x80030000) #define DBGDIDR (DEBUG_REGSITER_BASE + (0 * 4)) // Debug ID #define DBGWFAR (DEBUG_REGSITER_BASE + (6 * 4)) // Watchpoint Fault Address #define DBGVCR (DEBUG_REGSITER_BASE + (7 * 4)) // Vector Catch #define DBGECR (DEBUG_REGSITER_BASE + (9 * 4)) // Event Catch #define DBGDTRRX (DEBUG_REGSITER_BASE + (32 * 4)) // Host to Target Data Transfer #define DBGITR (DEBUG_REGSITER_BASE + (33 * 4)) // WO Instruction Transfer #define DBGDSCR (DEBUG_REGSITER_BASE + (34 * 4)) // Debug Status and Control #define DBGDTRTX (DEBUG_REGSITER_BASE + (35 * 4)) // Target to Host Data Transfer #define DBGDRCR (DEBUG_REGSITER_BASE + (36 * 4)) // Debug Run Control #define DBGEACR (DEBUG_REGSITER_BASE + (37 * 4)) // External Auxiliary Control #define DBGPCSR (DEBUG_REGSITER_BASE + (40 * 4)) // Program Counter Sampling #define DBGCIDSR (DEBUG_REGSITER_BASE + (41 * 4)) // Context ID Sampling #define DBGVIDSR (DEBUG_REGSITER_BASE + (42 * 4)) // Virtualization ID Sampling #define DBGBVR0 (DEBUG_REGSITER_BASE + (64 * 4)) // Breakpoint Value #define DBGBVR1 (DEBUG_REGSITER_BASE + (65 * 4)) // Breakpoint Value #define DBGBVR2 (DEBUG_REGSITER_BASE + (66 * 4)) // Breakpoint Value #define DBGBVR3 (DEBUG_REGSITER_BASE + (67 * 4)) // Breakpoint Value #define DBGBVR4 (DEBUG_REGSITER_BASE + (68 * 4)) // Breakpoint Value #define DBGBVR5 (DEBUG_REGSITER_BASE + (69 * 4)) // Breakpoint Value #define DBGBVR6 (DEBUG_REGSITER_BASE + (70 * 4)) // Breakpoint Value #define DBGBVR7 (DEBUG_REGSITER_BASE + (71 * 4)) // Breakpoint Value #define DBGBVR8 (DEBUG_REGSITER_BASE + (72 * 4)) // Breakpoint Value #define DBGBVR9 (DEBUG_REGSITER_BASE + (73 * 4)) // Breakpoint Value #define DBGBVR10 (DEBUG_REGSITER_BASE + (74 * 4)) // Breakpoint Value #define DBGBVR11 (DEBUG_REGSITER_BASE + (75 * 4)) // Breakpoint Value #define DBGBVR12 (DEBUG_REGSITER_BASE + (76 * 4)) // Breakpoint Value #define DBGBVR13 (DEBUG_REGSITER_BASE + (77 * 4)) // Breakpoint Value #define DBGBVR14 (DEBUG_REGSITER_BASE + (78 * 4)) // Breakpoint Value #define DBGBVR15 (DEBUG_REGSITER_BASE + (79 * 4)) // Breakpoint Value #define DBGBCR0 (DEBUG_REGSITER_BASE + (80 * 4)) // Breakpoint Control #define DBGBCR1 (DEBUG_REGSITER_BASE + (81 * 4)) // Breakpoint Control #define DBGBCR2 (DEBUG_REGSITER_BASE + (82 * 4)) // Breakpoint Control #define DBGBCR3 (DEBUG_REGSITER_BASE + (83 * 4)) // Breakpoint Control #define DBGBCR4 (DEBUG_REGSITER_BASE + (84 * 4)) // Breakpoint Control #define DBGBCR5 (DEBUG_REGSITER_BASE + (85 * 4)) // Breakpoint Control #define DBGBCR6 (DEBUG_REGSITER_BASE + (86 * 4)) // Breakpoint Control #define DBGBCR7 (DEBUG_REGSITER_BASE + (87 * 4)) // Breakpoint Control #define DBGBCR8 (DEBUG_REGSITER_BASE + (88 * 4)) // Breakpoint Control #define DBGBCR9 (DEBUG_REGSITER_BASE + (89 * 4)) // Breakpoint Control #define DBGBCR10 (DEBUG_REGSITER_BASE + (90 * 4)) // Breakpoint Control #define DBGBCR11 (DEBUG_REGSITER_BASE + (91 * 4)) // Breakpoint Control #define DBGBCR12 (DEBUG_REGSITER_BASE + (92 * 4)) // Breakpoint Control #define DBGBCR13 (DEBUG_REGSITER_BASE + (93 * 4)) // Breakpoint Control #define DBGBCR14 (DEBUG_REGSITER_BASE + (94 * 4)) // Breakpoint Control #define DBGBCR15 (DEBUG_REGSITER_BASE + (95 * 4)) // Breakpoint Control #define DBGWVR0 (DEBUG_REGSITER_BASE + (96 * 4)) // Watchpoint Value #define DBGWVR1 (DEBUG_REGSITER_BASE + (97 * 4)) // Watchpoint Value #define DBGWVR2 (DEBUG_REGSITER_BASE + (98 * 4)) // Watchpoint Value #define DBGWVR3 (DEBUG_REGSITER_BASE + (99 * 4)) // Watchpoint Value #define DBGWVR4 (DEBUG_REGSITER_BASE + (100 * 4)) // Watchpoint Value #define DBGWVR5 (DEBUG_REGSITER_BASE + (101 * 4)) // Watchpoint Value #define DBGWVR6 (DEBUG_REGSITER_BASE + (102 * 4)) // Watchpoint Value #define DBGWVR7 (DEBUG_REGSITER_BASE + (103 * 4)) // Watchpoint Value #define DBGWVR8 (DEBUG_REGSITER_BASE + (104 * 4)) // Watchpoint Value #define DBGWVR9 (DEBUG_REGSITER_BASE + (105 * 4)) // Watchpoint Value #define DBGWVR10 (DEBUG_REGSITER_BASE + (106 * 4)) // Watchpoint Value #define DBGWVR11 (DEBUG_REGSITER_BASE + (107 * 4)) // Watchpoint Value #define DBGWVR12 (DEBUG_REGSITER_BASE + (108 * 4)) // Watchpoint Value #define DBGWVR13 (DEBUG_REGSITER_BASE + (109 * 4)) // Watchpoint Value #define DBGWVR14 (DEBUG_REGSITER_BASE + (110 * 4)) // Watchpoint Value #define DBGWVR15 (DEBUG_REGSITER_BASE + (111 * 4)) // Watchpoint Value #define DBGWCR0 (DEBUG_REGSITER_BASE + (112 * 4)) // Watchpoint Control #define DBGWCR1 (DEBUG_REGSITER_BASE + (113 * 4)) // Watchpoint Control #define DBGWCR2 (DEBUG_REGSITER_BASE + (114 * 4)) // Watchpoint Control #define DBGWCR3 (DEBUG_REGSITER_BASE + (115 * 4)) // Watchpoint Control #define DBGWCR4 (DEBUG_REGSITER_BASE + (116 * 4)) // Watchpoint Control #define DBGWCR5 (DEBUG_REGSITER_BASE + (117 * 4)) // Watchpoint Control #define DBGWCR6 (DEBUG_REGSITER_BASE + (118 * 4)) // Watchpoint Control #define DBGWCR7 (DEBUG_REGSITER_BASE + (119 * 4)) // Watchpoint Control #define DBGWCR8 (DEBUG_REGSITER_BASE + (120 * 4)) // Watchpoint Control #define DBGWCR9 (DEBUG_REGSITER_BASE + (121 * 4)) // Watchpoint Control #define DBGWCR10 (DEBUG_REGSITER_BASE + (122 * 4)) // Watchpoint Control #define DBGWCR11 (DEBUG_REGSITER_BASE + (123 * 4)) // Watchpoint Control #define DBGWCR12 (DEBUG_REGSITER_BASE + (124 * 4)) // Watchpoint Control #define DBGWCR13 (DEBUG_REGSITER_BASE + (125 * 4)) // Watchpoint Control #define DBGWCR14 (DEBUG_REGSITER_BASE + (126 * 4)) // Watchpoint Control #define DBGWCR15 (DEBUG_REGSITER_BASE + (127 * 4)) // Watchpoint Control #define DBGBXVR0 (DEBUG_REGSITER_BASE + (144 * 4)) // Breakpoint Extended Valueb #define DBGBXVR1 (DEBUG_REGSITER_BASE + (145 * 4)) // Breakpoint Extended Valueb #define DBGBXVR2 (DEBUG_REGSITER_BASE + (146 * 4)) // Breakpoint Extended Valueb #define DBGBXVR3 (DEBUG_REGSITER_BASE + (147 * 4)) // Breakpoint Extended Valueb #define DBGBXVR4 (DEBUG_REGSITER_BASE + (148 * 4)) // Breakpoint Extended Valueb #define DBGBXVR5 (DEBUG_REGSITER_BASE + (149 * 4)) // Breakpoint Extended Valueb #define DBGBXVR6 (DEBUG_REGSITER_BASE + (150 * 4)) // Breakpoint Extended Valueb #define DBGBXVR7 (DEBUG_REGSITER_BASE + (151 * 4)) // Breakpoint Extended Valueb #define DBGBXVR8 (DEBUG_REGSITER_BASE + (152 * 4)) // Breakpoint Extended Valueb #define DBGBXVR9 (DEBUG_REGSITER_BASE + (153 * 4)) // Breakpoint Extended Valueb #define DBGBXVR10 (DEBUG_REGSITER_BASE + (154 * 4)) // Breakpoint Extended Valueb #define DBGBXVR11 (DEBUG_REGSITER_BASE + (155 * 4)) // Breakpoint Extended Valueb #define DBGBXVR12 (DEBUG_REGSITER_BASE + (156 * 4)) // Breakpoint Extended Valueb #define DBGBXVR13 (DEBUG_REGSITER_BASE + (157 * 4)) // Breakpoint Extended Valueb #define DBGBXVR14 (DEBUG_REGSITER_BASE + (158 * 4)) // Breakpoint Extended Valueb #define DBGBXVR15 (DEBUG_REGSITER_BASE + (159 * 4)) // Breakpoint Extended Valueb #define DBGOSLAR (DEBUG_REGSITER_BASE + (192 * 4)) // OS Lock Access #define DBGOSLSR (DEBUG_REGSITER_BASE + (193 * 4)) // OS Lock Status #define DBGPRCR (DEBUG_REGSITER_BASE + (196 * 4)) // Powerdown and Reset Control #define DBGPRSR (DEBUG_REGSITER_BASE + (197 * 4)) // Powerdown and Reset Status #define DBGITCTRL (DEBUG_REGSITER_BASE + (960 * 4)) // Integration Mode Control #define DBGCLAIMSET (DEBUG_REGSITER_BASE + (1000 * 4)) // Claim Tag Set #define DBGCLAIMCLR (DEBUG_REGSITER_BASE + (1001 * 4)) // Claim Tag Clear #define DBGLAR (DEBUG_REGSITER_BASE + (1004 * 4)) // Lock Access #define DBGLSR (DEBUG_REGSITER_BASE + (1005 * 4)) // Lock Status #define DBGAUTHSTATUS (DEBUG_REGSITER_BASE + (1006 * 4)) // Authentication Status #define DBGDEVID2 (DEBUG_REGSITER_BASE + (1008 * 4)) // Debug Device ID 2 #define DBGDEVID1 (DEBUG_REGSITER_BASE + (1009 * 4)) // Debug Device ID 1 #define DBGDEVID (DEBUG_REGSITER_BASE + (1010 * 4)) // Debug Device ID #define DBGDEVTYPE (DEBUG_REGSITER_BASE + (1011 * 4)) // Device Type #define DBGPID0 (DEBUG_REGSITER_BASE + (1012 * 4)) // Debug Peripheral ID #define DBGPID1 (DEBUG_REGSITER_BASE + (1013 * 4)) // Debug Peripheral ID #define DBGPID2 (DEBUG_REGSITER_BASE + (1014 * 4)) // Debug Peripheral ID #define DBGPID3 (DEBUG_REGSITER_BASE + (1015 * 4)) // Debug Peripheral ID #define DBGPID4 (DEBUG_REGSITER_BASE + (1016 * 4)) // Debug Peripheral ID #define DBGCID0 (DEBUG_REGSITER_BASE + (1020 * 4)) // Debug Component ID #define DBGCID1 (DEBUG_REGSITER_BASE + (1021 * 4)) // Debug Component ID #define DBGCID2 (DEBUG_REGSITER_BASE + (1022 * 4)) // Debug Component ID #define DBGCID3 (DEBUG_REGSITER_BASE + (1023 * 4)) // Debug Component ID #endif
modelpaintmixer/mpm-frontend
src/pages/standard.js
<reponame>modelpaintmixer/mpm-frontend<filename>src/pages/standard.js import React from "react" import PropTypes from "prop-types" import { Link } from "gatsby" import queryString from "query-string" import ScaleLoader from "react-spinners/ScaleLoader" import useDataApi from "../utils/data-api" import Layout from "../components/layout" import ColorBlocks from "../components/color-blocks" import PaintBlocks from "../components/paint-blocks" import SEO from "../components/seo" import RenderMarkdown from "../components/render-markdown" const StandardPage = props => { const values = queryString.parse(props.location.search) if (!values.id) { return ( <> <h2>An Error Occurred</h2> <div className="text-block"> <p>This page was requested without a standard ID.</p> <p> To browse all standards, visit the <Link to="/standards">All Standards</Link> page. </p> </div> </> ) } else { const [{ data, loading, error }] = useDataApi( `/api/view/standard/${values.id}`, { data: {}, } ) if (error) { return ( <div> <p>An error occurred trying to load data:</p> <p>{error.message}</p> </div> ) } else if (loading) { return ( <div className="text-block"> <div className="loading"> <ScaleLoader /> </div> </div> ) } else { let { name, abbreviation, notes, Origin: origin, Periods: periods, Colors: colors, Paints: paints, } = data.standard let relPeriods = [] let count = 0 for (let period of periods) { if (count++) { relPeriods.push(", ") } relPeriods.push( <a href={`/period/?id=${period.id}`} title={period.name}> {period.abbreviation} </a> ) } return ( <> <SEO title={`Standard: ${name} (${abbreviation})`} /> <Layout title={`Standard: ${name} (${abbreviation})`}> <div className="text-block"> {notes === null ? ( "" ) : ( <> <h3>Notes</h3> <RenderMarkdown>{notes}</RenderMarkdown> </> )} <h3>Origin</h3> <p>{origin.name}</p> {periods.length === 0 ? ( "" ) : ( <> <h3>Related periods</h3> <p>{relPeriods}</p> </> )} {colors.length === 0 ? ( "" ) : ( <> <h3>Related colors</h3> <ColorBlocks colors={colors} /> </> )} {paints.length === 0 ? ( "" ) : ( <> <h3>Related paints</h3> <PaintBlocks paints={paints} /> </> )} </div> </Layout> </> ) } } } StandardPage.propTypes = { location: PropTypes.object, } export default StandardPage
Juanbz123/bootcamp-2021-5
src/test/java/selenium/kmollecundo/BabyTuto.java
<filename>src/test/java/selenium/kmollecundo/BabyTuto.java package selenium.kmollecundo; import io.github.bonigarcia.wdm.WebDriverManager; import org.junit.*; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; import java.util.concurrent.TimeUnit; public class BabyTuto { private WebDriver driver; @BeforeClass public static void Setup(){ //Initialization del web driver con chrome WebDriverManager.chromedriver().setup(); } @Before public void Init(){ //Instanciamos init driver = new ChromeDriver(); //Metodo para iniciar siempre con la pantalla maximizada driver.manage().window().maximize(); //Cargar la página driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("https://www.babytuto.com/"); } @Test public void atc01_FiltrarProductosPorMarca(){ //Cierro pantalla de subscripcion driver.findElement(By.cssSelector("#newsletter > button")).click(); //Selecciono categiria Coches List<WebElement> option_list = driver.findElements(By.cssSelector("div.bar-2-products ul li a")); for (WebElement l: option_list ) { if (l.getText().contains("COCHES")){ l.click(); break; } } //Selecciono Accesorios de coches WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.bar-2-products .sub-cats .sub-cat ul.tree li a"))); List<WebElement> option_listsubmenu = driver.findElements(By.cssSelector("div.bar-2-products .sub-cats .sub-cat ul.tree li a")); for (WebElement s: option_listsubmenu ) { if (s.getText().contains("Accesorios para coches")){ s.click(); break; } } //Filtro por marca BBPRO WebDriverWait wait1 = new WebDriverWait(driver,15); wait1.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.main-container .container .main-big .categories .span2 .filter ul li a span.lbl"))); List<WebElement> filter = driver.findElements(By.cssSelector("div.main-container .container .main-big .categories .span2 .filter ul li a span.lbl")); for (WebElement f: filter ) { if (f.getText().contains("BBpro")){ f.click(); break; } } //Verifico que solo encuentre productos BBPRO WebElement marca = driver.findElement(By.cssSelector("div.span10 .items .item .info .merchant-name")); Assert.assertEquals("BBPRO",marca.getText()); } @After public void Close(){ if (driver != null) { // driver.close(); } } }
dbflute-test/dbflute-test-active-hangar
src/main/java/org/docksidestage/hangar/dbflute/bsbhv/BsWhiteBaseOne10CelebBhv.java
<gh_stars>0 package org.docksidestage.hangar.dbflute.bsbhv; import java.util.List; import org.dbflute.*; import org.dbflute.bhv.readable.*; import org.dbflute.bhv.writable.*; import org.dbflute.bhv.writable.coins.DateUpdateAdjuster; import org.dbflute.bhv.referrer.*; import org.dbflute.cbean.*; import org.dbflute.cbean.chelper.HpSLSFunction; import org.dbflute.cbean.result.*; import org.dbflute.exception.*; import org.dbflute.optional.OptionalEntity; import org.dbflute.outsidesql.executor.*; import org.docksidestage.hangar.dbflute.exbhv.*; import org.docksidestage.hangar.dbflute.bsbhv.loader.*; import org.docksidestage.hangar.dbflute.exentity.*; import org.docksidestage.hangar.dbflute.bsentity.dbmeta.*; import org.docksidestage.hangar.dbflute.cbean.*; /** * The behavior of WHITE_BASE_ONE10_CELEB as TABLE. <br> * <pre> * [primary key] * CELEB_ID * * [column] * CELEB_ID, CELEB_NAME, BASE_ID * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * WHITE_BASE * * [referrer table] * * * [foreign property] * whiteBase * * [referrer property] * * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsWhiteBaseOne10CelebBhv extends org.docksidestage.hangar.dbflute.nogen.ExtendedAbstractBehaviorWritable<WhiteBaseOne10Celeb, WhiteBaseOne10CelebCB> { // =================================================================================== // Definition // ========== /*df:beginQueryPath*/ /*df:endQueryPath*/ // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public WhiteBaseOne10CelebDbm asDBMeta() { return WhiteBaseOne10CelebDbm.getInstance(); } /** {@inheritDoc} */ public String asTableDbName() { return "WHITE_BASE_ONE10_CELEB"; } // =================================================================================== // New Instance // ============ /** {@inheritDoc} */ public WhiteBaseOne10CelebCB newConditionBean() { return new WhiteBaseOne10CelebCB(); } // =================================================================================== // Count Select // ============ /** * Select the count of uniquely-selected records by the condition-bean. {IgnorePagingCondition, IgnoreSpecifyColumn}<br> * SpecifyColumn is ignored but you can use it only to remove text type column for union's distinct. * <pre> * <span style="color: #70226C">int</span> count = <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectCount</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The count for the condition. (NotMinus) */ public int selectCount(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return facadeSelectCount(createCB(cbLambda)); } // =================================================================================== // Entity Select // ============= /** * Select the entity by the condition-bean. <br> * It returns not-null optional entity, so you should ... <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, alwaysPresent().</span> <br> * <span style="color: #AD4747; font-size: 120%">If it might be no data, isPresent() and orElse(), ...</span> * <pre> * <span style="color: #3F7E5E">// if the data always exists as your business rule</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectEntity</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }).<span style="color: #CC4747">alwaysPresent</span>(<span style="color: #553000">whiteBaseOne10Celeb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if present, or exception</span> * ... = <span style="color: #553000">whiteBaseOne10Celeb</span>.get... * }); * * <span style="color: #3F7E5E">// if it might be no data, ...</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectEntity</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }).<span style="color: #CC4747">ifPresent</span>(<span style="color: #553000">whiteBaseOne10Celeb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if present</span> * ... = <span style="color: #553000">whiteBaseOne10Celeb</span>.get... * }).<span style="color: #994747">orElse</span>(() <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if not present</span> * }); * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The optional entity selected by the condition. (NotNull: if no data, empty entity) * @throws EntityAlreadyDeletedException When get(), required() of return value is called and the value is null, which means entity has already been deleted (not found). * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<WhiteBaseOne10Celeb> selectEntity(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return facadeSelectEntity(createCB(cbLambda)); } protected OptionalEntity<WhiteBaseOne10Celeb> facadeSelectEntity(WhiteBaseOne10CelebCB cb) { return doSelectOptionalEntity(cb, typeOfSelectedEntity()); } protected <ENTITY extends WhiteBaseOne10Celeb> OptionalEntity<ENTITY> doSelectOptionalEntity(WhiteBaseOne10CelebCB cb, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectEntity(cb, tp), cb); } protected Entity doReadEntity(ConditionBean cb) { return facadeSelectEntity(downcast(cb)).orElse(null); } /** * Select the entity by the condition-bean with deleted check. <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, this method is good.</span> * <pre> * WhiteBaseOne10Celeb <span style="color: #553000">whiteBaseOne10Celeb</span> = <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectEntityWithDeletedCheck</span>(cb <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> cb.acceptPK(1)); * ... = <span style="color: #553000">whiteBaseOne10Celeb</span>.get...(); <span style="color: #3F7E5E">// the entity always be not null</span> * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The entity selected by the condition. (NotNull: if no data, throws exception) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public WhiteBaseOne10Celeb selectEntityWithDeletedCheck(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return facadeSelectEntityWithDeletedCheck(createCB(cbLambda)); } /** * Select the entity by the primary-key value. * @param celebId : PK, NotNull, INTEGER(10). (NotNull) * @return The optional entity selected by the PK. (NotNull: if no data, empty entity) * @throws EntityAlreadyDeletedException When get(), required() of return value is called and the value is null, which means entity has already been deleted (not found). * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<WhiteBaseOne10Celeb> selectByPK(Integer celebId) { return facadeSelectByPK(celebId); } protected OptionalEntity<WhiteBaseOne10Celeb> facadeSelectByPK(Integer celebId) { return doSelectOptionalByPK(celebId, typeOfSelectedEntity()); } protected <ENTITY extends WhiteBaseOne10Celeb> ENTITY doSelectByPK(Integer celebId, Class<? extends ENTITY> tp) { return doSelectEntity(xprepareCBAsPK(celebId), tp); } protected <ENTITY extends WhiteBaseOne10Celeb> OptionalEntity<ENTITY> doSelectOptionalByPK(Integer celebId, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectByPK(celebId, tp), celebId); } protected WhiteBaseOne10CelebCB xprepareCBAsPK(Integer celebId) { assertObjectNotNull("celebId", celebId); return newConditionBean().acceptPK(celebId); } /** * Select the entity by the unique-key value. * @param baseId : UQ, INTEGER(10), FK to WHITE_BASE. (NotNull) * @return The optional entity selected by the unique key. (NotNull: if no data, empty entity) * @throws EntityAlreadyDeletedException When get(), required() of return value is called and the value is null, which means entity has already been deleted (not found). * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<WhiteBaseOne10Celeb> selectByUniqueOf(Integer baseId) { return facadeSelectByUniqueOf(baseId); } protected OptionalEntity<WhiteBaseOne10Celeb> facadeSelectByUniqueOf(Integer baseId) { return doSelectByUniqueOf(baseId, typeOfSelectedEntity()); } protected <ENTITY extends WhiteBaseOne10Celeb> OptionalEntity<ENTITY> doSelectByUniqueOf(Integer baseId, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectEntity(xprepareCBAsUniqueOf(baseId), tp), baseId); } protected WhiteBaseOne10CelebCB xprepareCBAsUniqueOf(Integer baseId) { assertObjectNotNull("baseId", baseId); return newConditionBean().acceptUniqueOf(baseId); } // =================================================================================== // List Select // =========== /** * Select the list as result bean. * <pre> * ListResultBean&lt;WhiteBaseOne10Celeb&gt; <span style="color: #553000">whiteBaseOne10CelebList</span> = <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectList</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set...; * <span style="color: #553000">cb</span>.query().addOrderBy...; * }); * <span style="color: #70226C">for</span> (WhiteBaseOne10Celeb <span style="color: #553000">whiteBaseOne10Celeb</span> : <span style="color: #553000">whiteBaseOne10CelebList</span>) { * ... = <span style="color: #553000">whiteBaseOne10Celeb</span>.get...; * } * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The result bean of selected list. (NotNull: if no data, returns empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public ListResultBean<WhiteBaseOne10Celeb> selectList(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return facadeSelectList(createCB(cbLambda)); } @Override protected boolean isEntityDerivedMappable() { return true; } // =================================================================================== // Page Select // =========== /** * Select the page as result bean. <br> * (both count-select and paging-select are executed) * <pre> * PagingResultBean&lt;WhiteBaseOne10Celeb&gt; <span style="color: #553000">page</span> = <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectPage</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * <span style="color: #553000">cb</span>.query().addOrderBy... * <span style="color: #553000">cb</span>.<span style="color: #CC4747">paging</span>(20, 3); <span style="color: #3F7E5E">// 20 records per a page and current page number is 3</span> * }); * <span style="color: #70226C">int</span> allRecordCount = <span style="color: #553000">page</span>.getAllRecordCount(); * <span style="color: #70226C">int</span> allPageCount = <span style="color: #553000">page</span>.getAllPageCount(); * <span style="color: #70226C">boolean</span> isExistPrePage = <span style="color: #553000">page</span>.isExistPrePage(); * <span style="color: #70226C">boolean</span> isExistNextPage = <span style="color: #553000">page</span>.isExistNextPage(); * ... * <span style="color: #70226C">for</span> (WhiteBaseOne10Celeb whiteBaseOne10Celeb : <span style="color: #553000">page</span>) { * ... = whiteBaseOne10Celeb.get...; * } * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The result bean of selected page. (NotNull: if no data, returns bean as empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public PagingResultBean<WhiteBaseOne10Celeb> selectPage(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return facadeSelectPage(createCB(cbLambda)); } // =================================================================================== // Cursor Select // ============= /** * Select the cursor by the condition-bean. * <pre> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectCursor</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }, <span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">member</span>.getMemberName(); * }); * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @param entityLambda The handler of entity row of WhiteBaseOne10Celeb. (NotNull) */ public void selectCursor(CBCall<WhiteBaseOne10CelebCB> cbLambda, EntityRowHandler<WhiteBaseOne10Celeb> entityLambda) { facadeSelectCursor(createCB(cbLambda), entityLambda); } // =================================================================================== // Scalar Select // ============= /** * Select the scalar value derived by a function from uniquely-selected records. <br> * You should call a function method after this method called like as follows: * <pre> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">selectScalar</span>(Date.class).max(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">column...</span>; <span style="color: #3F7E5E">// required for the function</span> * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param <RESULT> The type of result. * @param resultType The type of result. (NotNull) * @return The scalar function object to specify function for scalar value. (NotNull) */ public <RESULT> HpSLSFunction<WhiteBaseOne10CelebCB, RESULT> selectScalar(Class<RESULT> resultType) { return facadeScalarSelect(resultType); } // =================================================================================== // Sequence // ======== @Override protected Number doReadNextVal() { String msg = "This table is NOT related to sequence: " + asTableDbName(); throw new UnsupportedOperationException(msg); } // =================================================================================== // Load Referrer // ============= /** * Load referrer for the list by the referrer loader. * <pre> * List&lt;Member&gt; <span style="color: #553000">memberList</span> = <span style="color: #0000C0">memberBhv</span>.selectList(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * memberBhv.<span style="color: #CC4747">load</span>(<span style="color: #553000">memberList</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * <span style="color: #70226C">for</span> (Member member : <span style="color: #553000">memberList</span>) { * List&lt;Purchase&gt; purchaseList = member.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param whiteBaseOne10CelebList The entity list of whiteBaseOne10Celeb. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList, ReferrerLoaderHandler<LoaderOfWhiteBaseOne10Celeb> loaderLambda) { xassLRArg(whiteBaseOne10CelebList, loaderLambda); loaderLambda.handle(new LoaderOfWhiteBaseOne10Celeb().ready(whiteBaseOne10CelebList, _behaviorSelector)); } /** * Load referrer for the entity by the referrer loader. * <pre> * Member <span style="color: #553000">member</span> = <span style="color: #0000C0">memberBhv</span>.selectEntityWithDeletedCheck(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> <span style="color: #553000">cb</span>.acceptPK(1)); * <span style="color: #0000C0">memberBhv</span>.<span style="color: #CC4747">load</span>(<span style="color: #553000">member</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * List&lt;Purchase&gt; purchaseList = <span style="color: #553000">member</span>.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param whiteBaseOne10Celeb The entity of whiteBaseOne10Celeb. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(WhiteBaseOne10Celeb whiteBaseOne10Celeb, ReferrerLoaderHandler<LoaderOfWhiteBaseOne10Celeb> loaderLambda) { xassLRArg(whiteBaseOne10Celeb, loaderLambda); loaderLambda.handle(new LoaderOfWhiteBaseOne10Celeb().ready(xnewLRAryLs(whiteBaseOne10Celeb), _behaviorSelector)); } // =================================================================================== // Pull out Relation // ================= /** * Pull out the list of foreign table 'WhiteBase'. * @param whiteBaseOne10CelebList The list of whiteBaseOne10Celeb. (NotNull, EmptyAllowed) * @return The list of foreign table. (NotNull, EmptyAllowed, NotNullElement) */ public List<WhiteBase> pulloutWhiteBase(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return helpPulloutInternally(whiteBaseOne10CelebList, "whiteBase"); } // =================================================================================== // Extract Column // ============== /** * Extract the value list of (single) primary key celebId. * @param whiteBaseOne10CelebList The list of whiteBaseOne10Celeb. (NotNull, EmptyAllowed) * @return The list of the column value. (NotNull, EmptyAllowed, NotNullElement) */ public List<Integer> extractCelebIdList(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return helpExtractListInternally(whiteBaseOne10CelebList, "celebId"); } /** * Extract the value list of (single) unique key baseId. * @param whiteBaseOne10CelebList The list of whiteBaseOne10Celeb. (NotNull, EmptyAllowed) * @return The list of the column value. (NotNull, EmptyAllowed, NotNullElement) */ public List<Integer> extractBaseIdList(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return helpExtractListInternally(whiteBaseOne10CelebList, "baseId"); } // =================================================================================== // Entity Update // ============= /** * Insert the entity modified-only. (DefaultConstraintsEnabled) * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * whiteBaseOne10Celeb.setFoo...(value); * whiteBaseOne10Celeb.setBar...(value); * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.set...;</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">insert</span>(whiteBaseOne10Celeb); * ... = whiteBaseOne10Celeb.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * <p>While, when the entity is created by select, all columns are registered.</p> * @param whiteBaseOne10Celeb The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insert(WhiteBaseOne10Celeb whiteBaseOne10Celeb) { doInsert(whiteBaseOne10Celeb, null); } /** * Update the entity modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can update by unique keys using entity's uniqueOf(). * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * whiteBaseOne10Celeb.setPK...(value); <span style="color: #3F7E5E">// required</span> * whiteBaseOne10Celeb.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.set...;</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * whiteBaseOne10Celeb.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">update</span>(whiteBaseOne10Celeb); * </pre> * @param whiteBaseOne10Celeb The entity of update. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void update(WhiteBaseOne10Celeb whiteBaseOne10Celeb) { doUpdate(whiteBaseOne10Celeb, null); } /** * Insert or update the entity modified-only. (DefaultConstraintsEnabled, NonExclusiveControl) <br> * if (the entity has no PK) { insert() } else { update(), but no data, insert() } <br> * <p><span style="color: #994747; font-size: 120%">Also you can update by unique keys using entity's uniqueOf().</span></p> * @param whiteBaseOne10Celeb The entity of insert or update. (NotNull, ...depends on insert or update) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insertOrUpdate(WhiteBaseOne10Celeb whiteBaseOne10Celeb) { doInsertOrUpdate(whiteBaseOne10Celeb, null, null); } /** * Delete the entity. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can delete by unique keys using entity's uniqueOf(). * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * whiteBaseOne10Celeb.setPK...(value); <span style="color: #3F7E5E">// required</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * whiteBaseOne10Celeb.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #70226C">try</span> { * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">delete</span>(whiteBaseOne10Celeb); * } <span style="color: #70226C">catch</span> (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param whiteBaseOne10Celeb The entity of delete. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void delete(WhiteBaseOne10Celeb whiteBaseOne10Celeb) { doDelete(whiteBaseOne10Celeb, null); } // =================================================================================== // Batch Update // ============ /** * Batch-insert the entity list modified-only of same-set columns. (DefaultConstraintsEnabled) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <p><span style="color: #CC4747; font-size: 120%">The columns of least common multiple are registered like this:</span></p> * <pre> * <span style="color: #70226C">for</span> (... : ...) { * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * whiteBaseOne10Celeb.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * whiteBaseOne10Celeb.setFooPrice(123); * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are registered</span> * <span style="color: #3F7E5E">// FOO_PRICE not-called in any entities are registered as null without default value</span> * <span style="color: #3F7E5E">// columns not-called in all entities are registered as null or default value</span> * whiteBaseOne10CelebList.add(whiteBaseOne10Celeb); * } * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">batchInsert</span>(whiteBaseOne10CelebList); * </pre> * <p>While, when the entities are created by select, all columns are registered.</p> * <p>And if the table has an identity, entities after the process don't have incremented values. * (When you use the (normal) insert(), you can get the incremented value from your entity)</p> * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNullAllowed: when auto-increment) * @return The array of inserted count. (NotNull, EmptyAllowed) */ public int[] batchInsert(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return doBatchInsert(whiteBaseOne10CelebList, null); } /** * Batch-update the entity list modified-only of same-set columns. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <span style="color: #CC4747; font-size: 120%">You should specify same-set columns to all entities like this:</span> * <pre> * for (... : ...) { * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * whiteBaseOne10Celeb.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * whiteBaseOne10Celeb.setFooPrice(123); * } <span style="color: #70226C">else</span> { * whiteBaseOne10Celeb.setFooPrice(null); <span style="color: #3F7E5E">// updated as null</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setFooDate(...); // *not allowed, fragmented</span> * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are updated</span> * <span style="color: #3F7E5E">// (others are not updated: their values are kept)</span> * whiteBaseOne10CelebList.add(whiteBaseOne10Celeb); * } * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">batchUpdate</span>(whiteBaseOne10CelebList); * </pre> * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of updated count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchUpdate(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return doBatchUpdate(whiteBaseOne10CelebList, null); } /** * Batch-delete the entity list. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchDelete(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList) { return doBatchDelete(whiteBaseOne10CelebList, null); } // =================================================================================== // Query Update // ============ /** * Insert the several entities by query (modified-only for fixed value). * <pre> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">queryInsert</span>(new QueryInsertSetupper&lt;WhiteBaseOne10Celeb, WhiteBaseOne10CelebCB&gt;() { * public ConditionBean setup(WhiteBaseOne10Celeb entity, WhiteBaseOne10CelebCB intoCB) { * FooCB cb = FooCB(); * cb.setupSelect_Bar(); * * <span style="color: #3F7E5E">// mapping</span> * intoCB.specify().columnMyName().mappedFrom(cb.specify().columnFooName()); * intoCB.specify().columnMyCount().mappedFrom(cb.specify().columnFooCount()); * intoCB.specify().columnMyDate().mappedFrom(cb.specify().specifyBar().columnBarDate()); * entity.setMyFixedValue("foo"); <span style="color: #3F7E5E">// fixed value</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//entity.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//entity.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">//entity.setVersionNo(value);</span> * * return cb; * } * }); * </pre> * @param manyArgLambda The callback to set up query-insert. (NotNull) * @return The inserted count. */ public int queryInsert(QueryInsertSetupper<WhiteBaseOne10Celeb, WhiteBaseOne10CelebCB> manyArgLambda) { return doQueryInsert(manyArgLambda, null); } /** * Update the several entities by query non-strictly modified-only. (NonExclusiveControl) * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setPK...(value);</span> * whiteBaseOne10Celeb.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setVersionNo(value);</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">queryUpdate</span>(whiteBaseOne10Celeb, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param whiteBaseOne10Celeb The entity that contains update values. (NotNull, PrimaryKeyNullAllowed) * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition. */ public int queryUpdate(WhiteBaseOne10Celeb whiteBaseOne10Celeb, CBCall<WhiteBaseOne10CelebCB> cbLambda) { return doQueryUpdate(whiteBaseOne10Celeb, createCB(cbLambda), null); } /** * Delete the several entities by query. (NonExclusiveControl) * <pre> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">queryDelete</span>(whiteBaseOne10Celeb, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition. */ public int queryDelete(CBCall<WhiteBaseOne10CelebCB> cbLambda) { return doQueryDelete(createCB(cbLambda), null); } // =================================================================================== // Varying Update // ============== // ----------------------------------------------------- // Entity Update // ------------- /** * Insert the entity with varying requests. <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as insert(entity). * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * whiteBaseOne10Celeb.setFoo...(value); * whiteBaseOne10Celeb.setBar...(value); * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">varyingInsert</span>(whiteBaseOne10Celeb, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// you can insert by your values for common columns</span> * <span style="color: #553000">op</span>.disableCommonColumnAutoSetup(); * }); * ... = whiteBaseOne10Celeb.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * @param whiteBaseOne10Celeb The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsert(WhiteBaseOne10Celeb whiteBaseOne10Celeb, WritableOptionCall<WhiteBaseOne10CelebCB, InsertOption<WhiteBaseOne10CelebCB>> opLambda) { doInsert(whiteBaseOne10Celeb, createInsertOption(opLambda)); } /** * Update the entity with varying requests modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification), disableCommonColumnAutoSetup(). <br> * Other specifications are same as update(entity). * <pre> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * whiteBaseOne10Celeb.setPK...(value); <span style="color: #3F7E5E">// required</span> * whiteBaseOne10Celeb.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * whiteBaseOne10Celeb.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #3F7E5E">// you can update by self calculation values</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">varyingUpdate</span>(whiteBaseOne10Celeb, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">columnXxxCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// XXX_COUNT = XXX_COUNT + 1</span> * }); * </pre> * @param whiteBaseOne10Celeb The entity of update. (NotNull, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingUpdate(WhiteBaseOne10Celeb whiteBaseOne10Celeb, WritableOptionCall<WhiteBaseOne10CelebCB, UpdateOption<WhiteBaseOne10CelebCB>> opLambda) { doUpdate(whiteBaseOne10Celeb, createUpdateOption(opLambda)); } /** * Insert or update the entity with varying requests. (ExclusiveControl: when update) <br> * Other specifications are same as insertOrUpdate(entity). * @param whiteBaseOne10Celeb The entity of insert or update. (NotNull) * @param insertOpLambda The callback for option of insert for varying requests. (NotNull) * @param updateOpLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsertOrUpdate(WhiteBaseOne10Celeb whiteBaseOne10Celeb, WritableOptionCall<WhiteBaseOne10CelebCB, InsertOption<WhiteBaseOne10CelebCB>> insertOpLambda, WritableOptionCall<WhiteBaseOne10CelebCB, UpdateOption<WhiteBaseOne10CelebCB>> updateOpLambda) { doInsertOrUpdate(whiteBaseOne10Celeb, createInsertOption(insertOpLambda), createUpdateOption(updateOpLambda)); } /** * Delete the entity with varying requests. (ZeroUpdateException, NonExclusiveControl) <br> * Now a valid option does not exist. <br> * Other specifications are same as delete(entity). * @param whiteBaseOne10Celeb The entity of delete. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void varyingDelete(WhiteBaseOne10Celeb whiteBaseOne10Celeb, WritableOptionCall<WhiteBaseOne10CelebCB, DeleteOption<WhiteBaseOne10CelebCB>> opLambda) { doDelete(whiteBaseOne10Celeb, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Batch Update // ------------ /** * Batch-insert the list with varying requests. <br> * For example, disableCommonColumnAutoSetup() * , disablePrimaryKeyIdentity(), limitBatchInsertLogging(). <br> * Other specifications are same as batchInsert(entityList). * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchInsert(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList, WritableOptionCall<WhiteBaseOne10CelebCB, InsertOption<WhiteBaseOne10CelebCB>> opLambda) { return doBatchInsert(whiteBaseOne10CelebList, createInsertOption(opLambda)); } /** * Batch-update the list with varying requests. <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), limitBatchUpdateLogging(). <br> * Other specifications are same as batchUpdate(entityList). * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchUpdate(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList, WritableOptionCall<WhiteBaseOne10CelebCB, UpdateOption<WhiteBaseOne10CelebCB>> opLambda) { return doBatchUpdate(whiteBaseOne10CelebList, createUpdateOption(opLambda)); } /** * Batch-delete the list with varying requests. <br> * For example, limitBatchDeleteLogging(). <br> * Other specifications are same as batchDelete(entityList). * @param whiteBaseOne10CelebList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) */ public int[] varyingBatchDelete(List<WhiteBaseOne10Celeb> whiteBaseOne10CelebList, WritableOptionCall<WhiteBaseOne10CelebCB, DeleteOption<WhiteBaseOne10CelebCB>> opLambda) { return doBatchDelete(whiteBaseOne10CelebList, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Query Update // ------------ /** * Insert the several entities by query with varying requests (modified-only for fixed value). <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as queryInsert(entity, setupper). * @param manyArgLambda The set-upper of query-insert. (NotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The inserted count. */ public int varyingQueryInsert(QueryInsertSetupper<WhiteBaseOne10Celeb, WhiteBaseOne10CelebCB> manyArgLambda, WritableOptionCall<WhiteBaseOne10CelebCB, InsertOption<WhiteBaseOne10CelebCB>> opLambda) { return doQueryInsert(manyArgLambda, createInsertOption(opLambda)); } /** * Update the several entities by query with varying requests non-strictly modified-only. {NonExclusiveControl} <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), allowNonQueryUpdate(). <br> * Other specifications are same as queryUpdate(entity, cb). * <pre> * <span style="color: #3F7E5E">// ex) you can update by self calculation values</span> * WhiteBaseOne10Celeb whiteBaseOne10Celeb = <span style="color: #70226C">new</span> WhiteBaseOne10Celeb(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setPK...(value);</span> * whiteBaseOne10Celeb.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//whiteBaseOne10Celeb.setVersionNo(value);</span> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">varyingQueryUpdate</span>(whiteBaseOne10Celeb, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFooCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// FOO_COUNT = FOO_COUNT + 1</span> * }); * </pre> * @param whiteBaseOne10Celeb The entity that contains update values. (NotNull) {PrimaryKeyNotRequired} * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryUpdate(WhiteBaseOne10Celeb whiteBaseOne10Celeb, CBCall<WhiteBaseOne10CelebCB> cbLambda, WritableOptionCall<WhiteBaseOne10CelebCB, UpdateOption<WhiteBaseOne10CelebCB>> opLambda) { return doQueryUpdate(whiteBaseOne10Celeb, createCB(cbLambda), createUpdateOption(opLambda)); } /** * Delete the several entities by query with varying requests non-strictly. <br> * For example, allowNonQueryDelete(). <br> * Other specifications are same as queryDelete(cb). * <pre> * <span style="color: #0000C0">whiteBaseOne10CelebBhv</span>.<span style="color: #CC4747">queryDelete</span>(whiteBaseOne10Celeb, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>... * }); * </pre> * @param cbLambda The callback for condition-bean of WhiteBaseOne10Celeb. (NotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryDelete(CBCall<WhiteBaseOne10CelebCB> cbLambda, WritableOptionCall<WhiteBaseOne10CelebCB, DeleteOption<WhiteBaseOne10CelebCB>> opLambda) { return doQueryDelete(createCB(cbLambda), createDeleteOption(opLambda)); } // =================================================================================== // OutsideSql // ========== /** * Prepare the all facade executor of outside-SQL to execute it. * <pre> * <span style="color: #3F7E5E">// main style</span> * whiteBaseOne10CelebBhv.outideSql().selectEntity(pmb); <span style="color: #3F7E5E">// optional</span> * whiteBaseOne10CelebBhv.outideSql().selectList(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * whiteBaseOne10CelebBhv.outideSql().selectPage(pmb); <span style="color: #3F7E5E">// PagingResultBean</span> * whiteBaseOne10CelebBhv.outideSql().selectPagedListOnly(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * whiteBaseOne10CelebBhv.outideSql().selectCursor(pmb, handler); <span style="color: #3F7E5E">// (by handler)</span> * whiteBaseOne10CelebBhv.outideSql().execute(pmb); <span style="color: #3F7E5E">// int (updated count)</span> * whiteBaseOne10CelebBhv.outideSql().call(pmb); <span style="color: #3F7E5E">// void (pmb has OUT parameters)</span> * * <span style="color: #3F7E5E">// traditional style</span> * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().selectEntity(path, pmb, entityType); * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().selectList(path, pmb, entityType); * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().selectPage(path, pmb, entityType); * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().selectPagedListOnly(path, pmb, entityType); * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().selectCursor(path, pmb, handler); * whiteBaseOne10CelebBhv.outideSql().traditionalStyle().execute(path, pmb); * * <span style="color: #3F7E5E">// options</span> * whiteBaseOne10CelebBhv.outideSql().removeBlockComment().selectList() * whiteBaseOne10CelebBhv.outideSql().removeLineComment().selectList() * whiteBaseOne10CelebBhv.outideSql().formatSql().selectList() * </pre> * <p>The invoker of behavior command should be not null when you call this method.</p> * @return The new-created all facade executor of outside-SQL. (NotNull) */ public OutsideSqlAllFacadeExecutor<WhiteBaseOne10CelebBhv> outsideSql() { return doOutsideSql(); } // =================================================================================== // Framework Filter Override // ========================= @Override protected void frameworkFilterEntityOfInsert(Entity entity, org.dbflute.optional.OptionalThing<InsertOption<? extends ConditionBean>> option) { super.frameworkFilterEntityOfInsert(entity, option); new DateUpdateAdjuster().truncatePrecisionOfEntityProperty(entity); } @Override protected void frameworkFilterEntityOfUpdate(Entity entity, org.dbflute.optional.OptionalThing<UpdateOption<? extends ConditionBean>> option) { super.frameworkFilterEntityOfUpdate(entity, option); new DateUpdateAdjuster().truncatePrecisionOfEntityProperty(entity); } // =================================================================================== // Type Helper // =========== protected Class<? extends WhiteBaseOne10Celeb> typeOfSelectedEntity() { return WhiteBaseOne10Celeb.class; } protected Class<WhiteBaseOne10Celeb> typeOfHandlingEntity() { return WhiteBaseOne10Celeb.class; } protected Class<WhiteBaseOne10CelebCB> typeOfHandlingConditionBean() { return WhiteBaseOne10CelebCB.class; } }
vmgeremias/sampserver
PlayHappy/plugins/sscanf/array.cpp
<reponame>vmgeremias/sampserver<filename>PlayHappy/plugins/sscanf/array.cpp /* * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the sscanf 2.0 SA:MP plugin. * * The Initial Developer of the Original Code is Alex "Y_Less" Cole. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Special Thanks to: * * SA:MP Team past, present and future */ #include "SDK/amx/amx.h" #include "utils.h" #include "specifiers.h" #include "data.h" #include "sscanf.h" extern logprintf_t logprintf; #define SAVE_VALUE(m) \ if (cptr) \ *cptr++ = m #define SAVE_VALUE_F(m) \ if (cptr) { \ float f = (float)m; \ *cptr++ = amx_ftoc(f); } #define UPDATE_VALUES(m) \ if (defaults) { \ if (count) { \ diff.c = m - last.c; \ last.c = m; \ } else { \ last.c = m; \ diff.c = 0; } } \ SkipOneSpacer(&string); \ ++count #define UPDATE_VALUES_F(m) \ if (defaults) { \ if (count) { \ diff.d = m - last.d; \ last.d = m; \ } else { \ last.d = m; \ diff.d = 0; } } \ SkipOneSpacer(&string); \ ++count #define DO_LOOP(n) \ count < length && *string && Do##n(&string, &b) // Macros for the regular values. #define DO(m,n) \ {m b; \ while (DO_LOOP(n)) { \ SAVE_VALUE((cell)b); \ UPDATE_VALUES((cell)b); } } \ break; #define DOV(m,n) \ {m b; \ while (count < length && *string) { \ Do##n(&string, &b); \ SAVE_VALUE((cell)b); \ UPDATE_VALUES((cell)b); } } \ break; #define DOF(m,n) \ {m b; \ while (DO_LOOP(n)) { \ SAVE_VALUE_F(b) \ UPDATE_VALUES_F(b); } } \ break; #define OPTIONAL_INVALID \ logprintf("sscanf warning: Optional types invalid in array specifiers, consider using 'A'.") #define DX(m,n) \ OPTIONAL_INVALID; #define DXF(m,n) \ OPTIONAL_INVALID; union update_u { cell c; double d; }; int DoArrayValues(char type, char ** input, cell * cptr, int length, bool defaults) { int count = 0; union update_u last, diff; last.d = 0; diff.d = 0; char * string = *input; switch (type) { // Copied directly from the main loop, just with different macros. case 'L': DX(bool, L) // FALLTHROUGH case 'l': { // The only custom code here. If the result is either "true" // or "false" it makes no sense to alternate in defaults as we // will just end up with larger values of true. bool b; while (count < length && *string) { DoL(&string, &b); SAVE_VALUE((cell)b); if (defaults) { last.c = (cell)b; } SkipOneSpacer(&string); ++count; } } break; case 'B': DX(int, B) // FALLTHROUGH case 'b': DO(int, B) case 'N': DX(int, N) // FALLTHROUGH case 'n': DO(int, N) case 'C': DX(char, C) // FALLTHROUGH case 'c': DO(char, C) case 'I': case 'D': DX(int, I) // FALLTHROUGH case 'i': case 'd': DO(int, I) case 'H': case 'X': DX(int, H) // FALLTHROUGH case 'h': case 'x': DO(int, H) case 'O': DX(int, O) // FALLTHROUGH case 'o': DO(int, O) case 'F': DXF(double, F) // FALLTHROUGH case 'f': DOF(double, F) case 'G': DXF(double, G) // FALLTHROUGH case 'g': { double b; while (DO_LOOP(G)) { float f = (float)b; if (cptr) { *cptr++ = amx_ftoc(f); } if (defaults) { switch (amx_ftoc(f)) { default: if (count) { diff.d = b - last.d; last.d = b; break; } // FALLTHROUGH case FLOAT_NEG_INFINITY: case FLOAT_INFINITY: case FLOAT_NAN: case FLOAT_NAN_E: last.d = b; diff.d = 0; break; } } SkipOneSpacer(&string); ++count; } } break; case 'U': DX(int, U) // FALLTHROUGH case 'u': DOV(int, U) break; case 'Q': DX(int, Q) // FALLTHROUGH case 'q': DOV(int, Q) break; case 'R': DX(int, R) // FALLTHROUGH case 'r': DOV(int, R) break; case 'A': case 'a': logprintf("sscanf error: Multi-dimensional arrays are not supported."); return SSCANF_FAIL_RETURN; case '\'': logprintf("sscanf error: Search strings are not supported in arrays."); return SSCANF_FAIL_RETURN; case 'P': case 'p': logprintf("sscanf error: Delimiters are not supported in arrays."); return SSCANF_FAIL_RETURN; case 'Z': case 'z': case 'S': case 's': logprintf("sscanf error: Strings are not supported in arrays."); return SSCANF_FAIL_RETURN; case '{': case '}': logprintf("sscanf error: Quiet sections are not supported in arrays."); return SSCANF_FAIL_RETURN; default: logprintf("sscanf error: Unknown format specifier '%c'.", type); return SSCANF_FAIL_RETURN; } // Save the end of the string. *input = string; if (defaults) { if (count < length) { if (*string) { // Error in format specifier. logprintf("sscanf warning: Invalid values in array defaults."); } else if (((type | 0x20) == 'f') || ((type | 0x20) == 'g')) { // Float type. do { last.d += diff.d; SAVE_VALUE_F(last.d); ++count; } while (count < length); } else { do { // Other type. while (count < length) { last.c += diff.c; SAVE_VALUE(last.c); ++count; } } while (count < length); } } else if (*string) { logprintf("sscanf warning: Excess array defaults found."); } } else { if (count < length) { if (*string) { // Invalid value entered. return SSCANF_FAIL_RETURN; } else { // Ran out of values - check if this is an optional array at a // higher level. return SSCANF_CONT_RETURN; } } } return SSCANF_TRUE_RETURN; } bool DoA(char ** defaults, char ** input, cell * cptr, bool optional) { // First, get the type of the array. char type = GetSingleType(defaults), * opts = 0; if (optional) { // Optional parameters - just collect the data for // now and use it later. if (**defaults == '(') { // Find the end of the options. Based on // SkipDefaultEx, but saving the start point. ++(*defaults); SkipWhitespace(defaults); // Got the start of the values. opts = *defaults; // Skip the defaults for now, we don't know the length yet. while (**defaults && **defaults != ')') { // Don't need to check for escaped ")"s here as you can't have // arrays of strings, which is the only place that would be. ++(*defaults); } if (**defaults) { if (opts == *defaults) { // No defaults found. logprintf("sscanf warning: Empty default values."); optional = false; } // Found a valid end. Make it null for // later array getting (easy to detect a // null end and we'll never need to // backtrack to here in the specifiers). **defaults = '\0'; ++(*defaults); } else { logprintf("sscanf warning: Unclosed default value."); } } else { logprintf("sscanf warning: No default value found."); optional = false; } } // GetLength has "true" as arrays, being new, MUST have lengths. int length = GetLength(defaults, true); if (length) { // Got the length of the array, it's all good. if (optional) { // Optional parameters are always separated by commans, not // whatever the coder may choose. TempDelimiter(','); if (DoArrayValues(type, &opts, cptr, length, true) == SSCANF_FAIL_RETURN) { RestoreDelimiter(); return false; } RestoreDelimiter(); } if (input) { switch (DoArrayValues(type, input, cptr, length, false)) { case SSCANF_CONT_RETURN: if (optional) { return true; } else { return false; } case SSCANF_TRUE_RETURN: return true; default: return false; } } else { return true; } } // Default fail - only gets here if there is no length. return false; }
pengcong06/openpitrix
pkg/service/runtime/handler.go
<filename>pkg/service/runtime/handler.go // Copyright 2017 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. package runtime import ( "context" "fmt" "time" clusterclient "openpitrix.io/openpitrix/pkg/client/cluster" providerclient "openpitrix.io/openpitrix/pkg/client/runtime_provider" "openpitrix.io/openpitrix/pkg/constants" "openpitrix.io/openpitrix/pkg/db" "openpitrix.io/openpitrix/pkg/gerr" "openpitrix.io/openpitrix/pkg/logger" "openpitrix.io/openpitrix/pkg/manager" "openpitrix.io/openpitrix/pkg/models" "openpitrix.io/openpitrix/pkg/pb" "openpitrix.io/openpitrix/pkg/pi" "openpitrix.io/openpitrix/pkg/util/ctxutil" "openpitrix.io/openpitrix/pkg/util/pbutil" ) func (p *Server) CreateRuntime(ctx context.Context, req *pb.CreateRuntimeRequest) (*pb.CreateRuntimeResponse, error) { return p.createRuntime(ctx, req, false) } func (p *Server) CreateDebugRuntime(ctx context.Context, req *pb.CreateRuntimeRequest) (*pb.CreateRuntimeResponse, error) { return p.createRuntime(ctx, req, true) } func (p *Server) createRuntime(ctx context.Context, req *pb.CreateRuntimeRequest, debug bool) (*pb.CreateRuntimeResponse, error) { s := ctxutil.GetSender(ctx) runtimeId := models.NewRuntimeId() runtimeCredentialId := req.GetRuntimeCredentialId().GetValue() zone := req.GetZone().GetValue() runtimeCredential, err := CheckRuntimeCredentialPermission(ctx, runtimeCredentialId) if err != nil { return nil, err } if runtimeCredential.Status == constants.StatusDeleted { logger.Error(ctx, "Runtime credential [%s] has been deleted", runtimeCredentialId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorResourceAlreadyDeleted, runtimeCredentialId) } if runtimeCredential.Provider != req.GetProvider().GetValue() { logger.Error(ctx, "Runtime credential [%s] provider is [%s] not [%s]", runtimeCredentialId, runtimeCredential.Provider, req.GetProvider().GetValue()) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorCreateResourcesFailed) } if runtimeCredential.Debug != debug { logger.Error(ctx, "Runtime credential [%s] debug is [%t] not [%t]", runtimeCredentialId, runtimeCredential.Debug, debug) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorCreateResourcesFailed) } runtimeCredential.RuntimeCredentialContent, err = encodeRuntimeCredentialContent( runtimeCredential.Provider, runtimeCredential.RuntimeCredentialContent) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } err = ValidateRuntime(ctx, runtimeId, zone, runtimeCredential, true) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorCreateResourcesFailed) } query := pi.Global().DB(ctx). Select(models.RuntimeColumns...). From(constants.TableRuntime). Where(db.Eq(constants.ColumnRuntimeCredentialId, runtimeCredentialId)). Where(db.Eq(constants.ColumnZone, req.GetZone().GetValue())). Where(db.Eq(constants.ColumnStatus, constants.StatusActive)). Where(db.Eq(constants.ColumnProvider, req.GetProvider().GetValue())). Where(db.Eq(constants.ColumnDebug, debug)). Where(db.Eq(constants.ColumnOwner, s.GetOwnerPath().Owner())). Where(db.Eq(constants.ColumnOwnerPath, s.GetOwnerPath())) count, err := query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorCreateResourcesFailed) } if count > 0 { return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorRuntimeExists) } newRuntime := models.NewRuntime( runtimeId, req.GetName().GetValue(), req.GetDescription().GetValue(), req.GetProvider().GetValue(), runtimeCredentialId, req.GetZone().GetValue(), s.GetOwnerPath(), debug, ) _, err = pi.Global().DB(ctx). InsertInto(constants.TableRuntime). Record(newRuntime). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorCreateResourcesFailed) } res := &pb.CreateRuntimeResponse{ RuntimeId: pbutil.ToProtoString(runtimeId), } return res, nil } func (p *Server) DescribeRuntimes(ctx context.Context, req *pb.DescribeRuntimesRequest) (*pb.DescribeRuntimesResponse, error) { return p.describeRuntimes(ctx, req, false) } func (p *Server) DescribeDebugRuntimes(ctx context.Context, req *pb.DescribeRuntimesRequest) (*pb.DescribeRuntimesResponse, error) { return p.describeRuntimes(ctx, req, true) } func (p *Server) describeRuntimes(ctx context.Context, req *pb.DescribeRuntimesRequest, debug bool) (*pb.DescribeRuntimesResponse, error) { offset := pbutil.GetOffsetFromRequest(req) limit := pbutil.GetLimitFromRequest(req) var runtimes []*models.Runtime displayColumns := manager.GetDisplayColumns(req.GetDisplayColumns(), models.RuntimeColumns) query := pi.Global().DB(ctx). Select(displayColumns...). From(constants.TableRuntime). Offset(offset). Limit(limit). Where(manager.BuildPermissionFilter(ctx)). Where(manager.BuildFilterConditions(req, constants.TableRuntime)) query = query.Where(db.Eq(constants.ColumnDebug, debug)) query = manager.AddQueryOrderDir(query, req, constants.ColumnCreateTime) if len(displayColumns) > 0 { _, err := query.Load(&runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } } count, err := query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } res := &pb.DescribeRuntimesResponse{ RuntimeSet: models.RuntimeToPbs(runtimes), TotalCount: count, } return res, nil } func (p *Server) DescribeRuntimeDetails(ctx context.Context, req *pb.DescribeRuntimesRequest) (*pb.DescribeRuntimeDetailsResponse, error) { offset := pbutil.GetOffsetFromRequest(req) limit := pbutil.GetLimitFromRequest(req) var runtimes []*models.Runtime var count uint32 query := pi.Global().DB(ctx). Select(models.RuntimeColumns...). From(constants.TableRuntime). Offset(offset). Limit(limit). Where(manager.BuildPermissionFilter(ctx)). Where(manager.BuildFilterConditions(req, constants.TableRuntime)) query = manager.AddQueryOrderDir(query, req, constants.ColumnCreateTime) _, err := query.Load(&runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } count, err = query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } pbRuntimeDetails, err := formatRuntimeDetailSet(ctx, runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } res := &pb.DescribeRuntimeDetailsResponse{ RuntimeDetailSet: pbRuntimeDetails, TotalCount: count, } return res, nil } func (p *Server) ModifyRuntime(ctx context.Context, req *pb.ModifyRuntimeRequest) (*pb.ModifyRuntimeResponse, error) { runtimeId := req.GetRuntimeId().GetValue() runtime, err := CheckRuntimePermission(ctx, runtimeId) if err != nil { return nil, err } if runtime.Status == constants.StatusDeleted { logger.Error(ctx, "Runtime [%s] has been deleted", runtimeId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorResourceAlreadyDeleted, runtimeId) } attributes := manager.BuildUpdateAttributes(req, constants.ColumnName, constants.ColumnDescription) attributes[constants.ColumnStatusTime] = time.Now() runtimeCredentialId := req.GetRuntimeCredentialId().GetValue() if len(runtimeCredentialId) > 0 { runtimeCredential, err := CheckRuntimeCredentialPermission(ctx, runtimeCredentialId) if err != nil { return nil, err } if runtimeCredential.Status == constants.StatusDeleted { logger.Error(ctx, "Runtime credential [%s] has been deleted", runtimeCredentialId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorResourceAlreadyDeleted, runtimeCredentialId) } err = ValidateRuntime(ctx, runtime.RuntimeId, runtime.Zone, runtimeCredential, false) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorModifyResourceFailed, runtimeId) } attributes[constants.ColumnRuntimeCredentialId] = runtimeCredentialId } _, err = pi.Global().DB(ctx). Update(constants.TableRuntime). SetMap(attributes). Where(db.Eq(constants.ColumnRuntimeId, runtimeId)). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorModifyResourceFailed, runtimeId) } res := &pb.ModifyRuntimeResponse{ RuntimeId: req.GetRuntimeId(), } return res, nil } func (p *Server) DeleteRuntimes(ctx context.Context, req *pb.DeleteRuntimesRequest) (*pb.DeleteRuntimesResponse, error) { var err error var clusterIds []string var response *pb.DescribeClustersResponse runtimeIds := req.GetRuntimeId() runtimes, err := CheckRuntimesPermission(ctx, runtimeIds) if err != nil { return nil, err } clusterClient, err := clusterclient.NewClient() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } for _, runtime := range runtimes { if runtime.Status == constants.StatusDeleted { logger.Error(ctx, "Runtime [%s] has been deleted", runtime.RuntimeId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorResourceAlreadyDeleted, runtime.RuntimeId) } // There can be no cluster in the runtime request := &pb.DescribeClustersRequest{ RuntimeId: []string{runtime.RuntimeId}, Status: []string{ constants.StatusActive, constants.StatusStopped, constants.StatusSuspended, constants.StatusPending, }, } if runtime.Debug { response, err = clusterClient.DescribeDebugClusters(ctx, request) } else { response, err = clusterClient.DescribeClusters(ctx, request) } if response.TotalCount > 0 { if req.GetForce().GetValue() { for _, cluster := range response.ClusterSet { clusterIds = append(clusterIds, cluster.GetClusterId().GetValue()) } err = clusterClient.DeleteAndCeaseClusters(ctx, clusterIds, req.GetForce().GetValue()) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } } else { err = fmt.Errorf("there are still [%d] clusters in the runtime [%s]", response.TotalCount, runtime.RuntimeId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorDeleteResourcesFailed) } } } err = deleteRuntime(ctx, runtimeIds) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } res := &pb.DeleteRuntimesResponse{ RuntimeId: runtimeIds, } return res, nil } func (p *Server) CreateRuntimeCredential(ctx context.Context, req *pb.CreateRuntimeCredentialRequest) (*pb.CreateRuntimeCredentialResponse, error) { return p.createRuntimeCredential(ctx, req, false) } func (p *Server) CreateDebugRuntimeCredential(ctx context.Context, req *pb.CreateRuntimeCredentialRequest) (*pb.CreateRuntimeCredentialResponse, error) { return p.createRuntimeCredential(ctx, req, true) } func (p *Server) createRuntimeCredential(ctx context.Context, req *pb.CreateRuntimeCredentialRequest, debug bool) (*pb.CreateRuntimeCredentialResponse, error) { s := ctxutil.GetSender(ctx) runtimeCredentialId := models.NewRuntimeCredentialId() provider := req.Provider.GetValue() runtimeUrl := req.RuntimeUrl.GetValue() runtimeCredentialContent := req.RuntimeCredentialContent.GetValue() runtimeCredential := &models.RuntimeCredential{ RuntimeUrl: runtimeUrl, Provider: provider, RuntimeCredentialContent: runtimeCredentialContent, } err := ValidateRuntime(ctx, "", "", runtimeCredential, false) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorCreateResourcesFailed) } content, err := decodeRuntimeCredentialContent(provider, runtimeCredentialContent) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorCreateResourcesFailed) } query := pi.Global().DB(ctx). Select(models.RuntimeCredentialColumns...). From(constants.TableRuntimeCredential). Where(db.Eq(constants.ColumnRuntimeUrl, req.GetRuntimeUrl().GetValue())). Where(db.Eq(constants.ColumnRuntimeCredentialContent, content)). Where(db.Eq(constants.ColumnProvider, req.GetProvider().GetValue())). Where(db.Eq(constants.ColumnDebug, debug)). Where(db.Eq(constants.ColumnOwner, s.GetOwnerPath().Owner())). Where(db.Eq(constants.ColumnOwnerPath, s.GetOwnerPath())) count, err := query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorCreateResourcesFailed) } if count > 0 { return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorRuntimeCredentialExists) } newRuntimeCredential := models.NewRuntimeCredential( runtimeCredentialId, req.GetName().GetValue(), req.GetDescription().GetValue(), req.GetRuntimeUrl().GetValue(), content, req.GetProvider().GetValue(), s.GetOwnerPath(), debug, ) _, err = pi.Global().DB(ctx). InsertInto(constants.TableRuntimeCredential). Record(newRuntimeCredential). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorCreateResourcesFailed) } res := &pb.CreateRuntimeCredentialResponse{ RuntimeCredentialId: pbutil.ToProtoString(newRuntimeCredential.RuntimeCredentialId), } return res, nil } func (p *Server) DescribeRuntimeCredentials(ctx context.Context, req *pb.DescribeRuntimeCredentialsRequest) (*pb.DescribeRuntimeCredentialsResponse, error) { return p.describeRuntimeCredentials(ctx, req, false) } func (p *Server) DescribeDebugRuntimeCredentials(ctx context.Context, req *pb.DescribeRuntimeCredentialsRequest) (*pb.DescribeRuntimeCredentialsResponse, error) { return p.describeRuntimeCredentials(ctx, req, true) } func (p *Server) describeRuntimeCredentials(ctx context.Context, req *pb.DescribeRuntimeCredentialsRequest, debug bool) (*pb.DescribeRuntimeCredentialsResponse, error) { offset := pbutil.GetOffsetFromRequest(req) limit := pbutil.GetLimitFromRequest(req) var runtimeCredentials []*models.RuntimeCredential var count uint32 query := pi.Global().DB(ctx). Select(models.RuntimeCredentialColumns...). From(constants.TableRuntimeCredential). Offset(offset). Limit(limit). Where(manager.BuildPermissionFilter(ctx)). Where(manager.BuildFilterConditions(req, constants.TableRuntimeCredential)) query = query.Where(db.Eq(constants.ColumnDebug, debug)) query = manager.AddQueryOrderDir(query, req, constants.ColumnCreateTime) _, err := query.Load(&runtimeCredentials) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } count, err = query.Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } // encrypt runtime credential contents for _, runtimeCredential := range runtimeCredentials { runtimeCredential.RuntimeCredentialContent = "******" } res := &pb.DescribeRuntimeCredentialsResponse{ RuntimeCredentialSet: models.RuntimeCredentialToPbs(runtimeCredentials), TotalCount: count, } return res, nil } func (p *Server) DeleteRuntimeCredentials(ctx context.Context, req *pb.DeleteRuntimeCredentialsRequest) (*pb.DeleteRuntimeCredentialsResponse, error) { runtimeCredentialIds := req.GetRuntimeCredentialId() runtimeCredentials, err := CheckRuntimeCredentialsPermission(ctx, runtimeCredentialIds) if err != nil { return nil, err } for _, runtimeCredential := range runtimeCredentials { if runtimeCredential.Status == constants.StatusDeleted { logger.Info(ctx, "Runtime credential [%s] has been deleted", runtimeCredential.RuntimeCredentialId) continue } count, err := pi.Global().DB(ctx). Select(models.RuntimeCredentialColumns...). From(constants.TableRuntime). Where(db.Eq(constants.ColumnRuntimeCredentialId, runtimeCredential.RuntimeCredentialId)). Where(db.Eq(constants.ColumnStatus, constants.StatusActive)). Count() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } if count > 0 { err = fmt.Errorf("there are still [%d] runtimes use credential [%s]", count, runtimeCredential.RuntimeCredentialId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorDeleteResourcesFailed) } } _, err = pi.Global().DB(ctx). Update(constants.TableRuntimeCredential). Set(constants.ColumnStatus, constants.StatusDeleted). Set(constants.ColumnStatusTime, time.Now()). Where(db.Eq(constants.ColumnRuntimeCredentialId, runtimeCredentialIds)). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDeleteResourcesFailed) } res := &pb.DeleteRuntimeCredentialsResponse{ RuntimeCredentialId: runtimeCredentialIds, } return res, nil } func (p *Server) ModifyRuntimeCredential(ctx context.Context, req *pb.ModifyRuntimeCredentialRequest) (*pb.ModifyRuntimeCredentialResponse, error) { runtimeCredentialId := req.GetRuntimeCredentialId().GetValue() runtimeCredentialContent := req.GetRuntimeCredentialContent().GetValue() runtimeCredential, err := CheckRuntimeCredentialPermission(ctx, runtimeCredentialId) if err != nil { return nil, err } if runtimeCredential.Status == constants.StatusDeleted { logger.Error(ctx, "Runtime credential [%s] has been deleted", runtimeCredentialId) return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorResourceAlreadyDeleted, runtimeCredentialId) } attributes := manager.BuildUpdateAttributes(req, constants.ColumnName, constants.ColumnDescription) attributes[constants.ColumnStatusTime] = time.Now() if len(runtimeCredentialContent) > 0 { var runtimes []*models.Runtime query := pi.Global().DB(ctx). Select(models.RuntimeColumns...). From(constants.TableRuntime). Where(db.Eq(constants.ColumnRuntimeCredentialId, runtimeCredentialId)). Where(db.Eq(constants.ColumnStatus, constants.StatusActive)) _, err = query.Load(&runtimes) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorModifyResourceFailed, runtimeCredentialId) } for _, runtime := range runtimes { newRuntimeCredential := &models.RuntimeCredential{ RuntimeUrl: runtimeCredential.RuntimeUrl, RuntimeCredentialContent: runtimeCredentialContent, Provider: runtimeCredential.Provider, } err = ValidateRuntime(ctx, runtime.RuntimeId, runtime.Zone, newRuntimeCredential, false) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorModifyResourceFailed, runtimeCredentialId) } } newContent, err := decodeRuntimeCredentialContent(runtimeCredential.Provider, runtimeCredentialContent) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorModifyResourceFailed, runtimeCredentialId) } attributes[constants.ColumnRuntimeCredentialContent] = newContent } _, err = pi.Global().DB(ctx). Update(constants.TableRuntimeCredential). SetMap(attributes). Where(db.Eq(constants.ColumnRuntimeCredentialId, runtimeCredentialId)). Exec() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorModifyResourceFailed, runtimeCredentialId) } res := &pb.ModifyRuntimeCredentialResponse{ RuntimeCredentialId: req.GetRuntimeCredentialId(), } return res, nil } func (p *Server) ValidateRuntimeCredential(ctx context.Context, req *pb.ValidateRuntimeCredentialRequest) (*pb.ValidateRuntimeCredentialResponse, error) { runtimeCredential := &models.RuntimeCredential{ RuntimeUrl: req.GetRuntimeUrl().GetValue(), RuntimeCredentialContent: req.GetRuntimeCredentialContent().GetValue(), Provider: req.GetProvider().GetValue(), } err := ValidateRuntime(ctx, "", "", runtimeCredential, false) if err != nil { return &pb.ValidateRuntimeCredentialResponse{ Ok: pbutil.ToProtoBool(false), }, gerr.NewWithDetail(ctx, gerr.InvalidArgument, err, gerr.ErrorValidateFailed) } return &pb.ValidateRuntimeCredentialResponse{ Ok: pbutil.ToProtoBool(true), }, nil } func (p *Server) DescribeRuntimeProviderZones(ctx context.Context, req *pb.DescribeRuntimeProviderZonesRequest) (*pb.DescribeRuntimeProviderZonesResponse, error) { runtimeCredentialId := req.GetRuntimeCredentialId().GetValue() runtimeCredential, err := CheckRuntimeCredentialPermission(ctx, runtimeCredentialId) if err != nil { return nil, err } providerClient, err := providerclient.NewRuntimeProviderManagerClient() if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorInternalError) } response, err := providerClient.DescribeZones(ctx, &pb.DescribeZonesRequest{ Provider: pbutil.ToProtoString(runtimeCredential.Provider), RuntimeCredential: models.RuntimeCredentialToPb(runtimeCredential), }) if err != nil { return nil, gerr.NewWithDetail(ctx, gerr.PermissionDenied, err, gerr.ErrorDescribeResourceFailed) } return &pb.DescribeRuntimeProviderZonesResponse{ RuntimeCredentialId: req.GetRuntimeCredentialId(), Zone: response.Zones, }, nil } type runtimeStatistic struct { Date string `db:"DATE_FORMAT(create_time, '%Y-%m-%d')"` Count uint32 `db:"COUNT(runtime_id)"` } type providerStatistic struct { Provider string `db:"provider"` Count uint32 `db:"COUNT(runtime_id)"` } func (p *Server) GetRuntimeStatistics(ctx context.Context, req *pb.GetRuntimeStatisticsRequest) (*pb.GetRuntimeStatisticsResponse, error) { res := &pb.GetRuntimeStatisticsResponse{ LastTwoWeekCreated: make(map[string]uint32), TopTenProviders: make(map[string]uint32), } runtimeCount, err := pi.Global().DB(ctx). Select(constants.ColumnRuntimeId). From(constants.TableRuntime). Where(db.Neq(constants.ColumnStatus, constants.StatusDeleted)). Count() if err != nil { logger.Error(ctx, "Failed to get runtime count, error: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } res.RuntimeCount = runtimeCount err = pi.Global().DB(ctx). Select("COUNT(DISTINCT provider)"). From(constants.TableRuntime). Where(db.Neq(constants.ColumnStatus, constants.StatusDeleted)). LoadOne(&res.ProviderCount) if err != nil { logger.Error(ctx, "Failed to get provider count, error: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } time2week := time.Now().Add(-14 * 24 * time.Hour) var rs []*runtimeStatistic _, err = pi.Global().DB(ctx). Select("DATE_FORMAT(create_time, '%Y-%m-%d')", "COUNT(runtime_id)"). From(constants.TableRuntime). GroupBy("DATE_FORMAT(create_time, '%Y-%m-%d')"). Where(db.Gte(constants.ColumnCreateTime, time2week)). Limit(14).Load(&rs) if err != nil { logger.Error(ctx, "Failed to get runtime statistics, error: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } for _, a := range rs { res.LastTwoWeekCreated[a.Date] = a.Count } var ps []*providerStatistic _, err = pi.Global().DB(ctx). Select("provider", "COUNT(runtime_id)"). From(constants.TableRuntime). Where(db.Neq(constants.ColumnStatus, constants.StatusDeleted)). GroupBy(constants.ColumnProvider). OrderDir("COUNT(runtime_id)", false). Limit(10).Load(&ps) if err != nil { logger.Error(ctx, "Failed to get provider statistics, error: %+v", err) return nil, gerr.NewWithDetail(ctx, gerr.Internal, err, gerr.ErrorDescribeResourcesFailed) } for _, a := range ps { res.TopTenProviders[a.Provider] = a.Count } return res, nil }
EnisBerk/speech_audio_understanding
src/nna/tests/dataimport_test.py
import pytest from nna import dataimport test_data_megan_excell_row2yaml_code = [ ( { 'Anthro/Bio': '', 'Category': 'Bug', 'Specific Category': '', }, 'V1', '1.3.0', ), ( { 'Anthro/Bio': 'TEST', 'Category': 'BUg', 'Specific Category': '', }, 'V1', '1.3.0', ), ( { 'Anthro/Bio': 'antH', 'Category': '', 'Specific Category': '', }, 'V1', '0.0.0', ), ] @pytest.mark.parametrize('row,version, expected_output', test_data_megan_excell_row2yaml_code) def test_megan_excell_row2yaml_code(row, expected_output,version): output = dataimport.megan_excell_row2yaml_code(row,version=version) assert expected_output == output testv2_data_megan_excell_row2yaml_code = [ ( { 'Anthro/Bio': '', 'Category': 'Bug', 'Specific Category': '', }, 'V2', [], ), ( { 'bird': '1', }, 'V2', ['1.1.0'], ), ( { 'Bio': 1, 'bird': '1', 'flare': '0', }, 'V2', ['1.0.0','1.1.0',], ), ] # testing version 2 of the same function @pytest.mark.parametrize('row,version, expected_output', testv2_data_megan_excell_row2yaml_code) def testv2_megan_excell_row2yaml_code(row, expected_output,version): output = dataimport.megan_excell_row2yaml_code(row,version=version) assert expected_output == output
wangyang2010344/mve
public/index/S-Lisp/interpret.js
<gh_stars>1-10 ({ data:{ s:"./s.js" }, delay:true, success:function() { var getPath=function(scope) { var pathOf=lib.s.kvs_find1st(scope,"pathOf"); if(pathOf && pathOf.isFun){ return pathOf.exec(null); }else{ return ""; } }; var calNodes=function(children,scope) { var r=null; while(children!=null){ var child=children.First(); r=lib.s.extend(interpret(child,scope),r); children=children.Rest(); } return r; }; var match_Exception=function(scope,msg,exp){ return exp.exception(getPath(scope)+":\t"+msg); }; var error_throw=function(msg,exp,scope,children) { return exp.exception(getPath(scope)+":\t"+msg+"\r\n"+exp.toString(true)+"\r\n"+children.toString(true)); }; var interpret=function(input,scope) { if(input.type=="()"){ var nodes=calNodes(input.r_children,scope); var first=nodes.First(); if(first && first.isFun){ try{ return first.exec(nodes.Rest()); }catch(err){ if(err.isLocationException){ err.addStack(getPath(scope),input.left,input.right,input.toString()); throw err; }else{ throw error_throw(err,input,scope,nodes); } } }else{ throw error_throw("参数0必须为函数",input,scope,nodes); } }else if (input.type=="[]") { return calNodes(input.r_children,scope); }else if(input.type=="{}"){ return new UserFun(input,scope); }else if(input.type=="id"){ var paths=input.paths; if(paths==null){ throw match_Exception(scope,input.token.value+"不是合法的ID类型23",input); }else{ var c_scope=scope; var value=null; while(paths!=null){ var key=paths.First(); value=lib.s.kvs_find1st(c_scope,key); paths=paths.Rest(); if(paths!=null){ if(value==null || value.isList){ c_scope=value; }else{ throw match_Exception(scope,"计算"+paths.toString()+",其中"+value+"不是合法的kvs类型:\t"+input.token.value,input); } } } return value; } }else{ /*string/int/float/bool*/ return input.token.value; } }; var letSmallMatch=function(small,vs,scope){ var ks=small.children; if(vs==null || vs.isList){ while(ks!=null){ var v=null; if(vs!=null){ v=vs.First(); } var k=ks.First(); ks=ks.Rest(); if(k.type=="let-id"){ scope=lib.s.kvs_extend(k.token.value,v,scope); }else if(k.type=="let-()"){ scope=letSmallMatch(k,v,scope); }else if(k.type=="let-..."){ scope=lib.s.kvs_extend(k.token.value,vs,scope); }else{ throw k.exception("非法"+k.toString()); } if(vs!=null){ vs=vs.Rest(); } } return scope; }else{ throw small.exception(vs.toString()+"不是合法的list类型,无法参与无组匹配:"+small.toString()); } }; var runQueue=function(scope) { return function(exps) { var r=null; while(exps!=null){ var exp=exps.First(); if(exp.type=="let"){ var cs=exp.children.Rest(); while(cs!=null){ var key=cs.First(); cs=cs.Rest(); var value=interpret(cs.First(),scope); cs=cs.Rest(); if(key.type=="let-id"){ scope=lib.s.kvs_extend(key.token.value,value,scope); }else if(key.type=="let-()"){ scope=letSmallMatch(key,value,scope); } } r=null; }else{ r=interpret(exp,scope); } exps=exps.Rest(); } return r; }; }; /*基础函数*/ var Fun=new Function(); Fun.prototype.isFun=true; Fun.prototype.Function_type={ lib:0, user:1, cache:2 }; /*库函数*/ function LibFun(key,fun) { this.fun=fun; this.key=key; } LibFun.prototype=new Fun(); mb.Object.ember(LibFun.prototype,{ toString:function() { return this.key; }, ftype:function() { return this.Function_type.lib; }, exec:function(node) { try{ return this.fun(node); }catch(e){ mb.log(e,node.toString(),this.fun.toString()); return null; } } }); /*用户自定义函数*/ var UserFun=function(input,parentScope) { this.input=input; this.parentScope=parentScope; }; UserFun.prototype=new Fun(); mb.Object.ember(UserFun.prototype,{ toString:function() { return this.input.toString(); }, exec:function(node){ var scope=lib.s.kvs_extend("args",node,this.parentScope); scope=lib.s.kvs_extend("this",this,scope); var rq=runQueue(scope); return rq(this.input.children); }, ftype:function() { return this.Function_type.user; } }); return { runQueue:runQueue, Fun:Fun, buildLibFun:function(k,fun) { return new LibFun(k,fun); }, buildUserFun:function(exp,scope) { return new UserFun(exp,scope); } }; } })
ArekZw/async
src/cache/cache.js
<reponame>ArekZw/async /** * Async CSS and Script loader * Released under the terms of MIT license * * Copyright (C) 2019 Style.Tools * @link https://github.com/style-tools/async */ function NAMESPACE(key) { return VAR(VAR_DATA_C) + ':' + (key || ''); } function IS_EXPIRED(date, expire) { return date && ((date + expire) < TIMESTAMP()); } var LOCALSTORAGE; var CACHE_API; var CACHE_UPDATE; var XHR; var MAX_SIZE_NO_SAVE = {}; var READ_CSSTEXT; var CACHE_CSS; var CACHE_JS; // get css from cache function CACHE_GET(src, config, callback) { config = OBJECT(config, VAR_TYPE); var type = config[VAR_TYPE]; var namespace = config[VAR_NAMESPACE]; var fallback = config[VAR_FALLBACK]; var method; // localStorage module if (type === VAR_LOCALSTORAGE && LOCALSTORAGE) { method = LOCALSTORAGE[0]; } else if (type === VAR_CACHE_API && CACHE_API) { // cache api method = CACHE_API[0]; } if (method) { method(src, function(cached, method_disabled) { // max size limit if (cached && IS_ARRAY(cached[0])) { MAX_SIZE_NO_SAVE[type] = OBJECT(MAX_SIZE_NO_SAVE[type]); MAX_SIZE_NO_SAVE[type][src] = 1; cached = 0; } if (cached || !fallback) { if (cached) { cached[9] = type; } callback(cached, method_disabled); } else { CACHE_GET(src, fallback, function(res) { callback(res); }); } }); } else { callback(0, 1); } } // get css from cache function CACHE_SAVE(src, config, text, last_modified, viaCORS) { config = OBJECT(config, VAR_TYPE); var type = config[VAR_TYPE], expire = config[VAR_EXPIRE], namespace = config[VAR_NAMESPACE], fallback = config[VAR_FALLBACK], method, len, over_max_size; if (src in OBJECT(MAX_SIZE_NO_SAVE[type])) { // max size, use fallback } else { // localStorage module if (type === VAR_LOCALSTORAGE && LOCALSTORAGE) { method = LOCALSTORAGE[1]; } else if (type === VAR_CACHE_API && CACHE_API) { // cache api method = CACHE_API[1]; } } if (method) { // over max size = [-1] len = LENGTH(text); over_max_size = (IS_INT(config[VAR_MAX_SIZE]) && config[VAR_MAX_SIZE] < len); if (DEBUG) { if (over_max_size) { var debug_data = { size: FILE_SIZE(len), "max-size": FILE_SIZE(config[VAR_MAX_SIZE]) }; CONSOLE_INFO('cache.max-size', 'skipped save', LOCAL_URL(src), debug_data); } } method(src, over_max_size ? [] : text, expire, last_modified, viaCORS); } // save in fallback cache if (fallback) { CACHE_SAVE(src, fallback, text, last_modified, viaCORS); } } CACHE = function(args, callback) { function cache_or_options(key, alt) { return cache[key] || cache_options[key] || alt; } function save_asset(asset, assetEl) { if (!cache_method_disabled) { // use requestIdleCallback if available via timed loading module var save_callback = function() { function save(text, last_modified, viaCORS) { if (IS_STRING(text)) { if (DEBUG) { var debug_data = { size: FILE_SIZE(LENGTH(text)) }; switch (cache[VAR_TYPE]) { case VAR_LOCALSTORAGE: debug_data.type = 'localStorage'; break; case VAR_CACHE_API: debug_data.type = 'cache-api'; break; } CONSOLE_LOG('cache', 'saved' + ((viaCORS) ? ' (via CORS proxy)' : ''), LOCAL_URL(src), debug_data); } // save CACHE_SAVE(src, cache, text, last_modified, viaCORS); } else { if (DEBUG) { // report request error var debug_data = { error: 'no source' }; switch (cache[VAR_TYPE]) { case VAR_LOCALSTORAGE: debug_data.type = 'localStorage'; break; case VAR_CACHE_API: debug_data.type = 'cache-api'; break; } CONSOLE_ERROR('cache', 'failed' + ((viaCORS) ? ' (via CORS proxy)' : ''), LOCAL_URL(src), debug_data); } if (API) { ERROR('cache', ['save', LOCAL_URL(src)]); } } } var rules, text = '', textRetrieved; FOREACH(sources, function(source) { if (!textRetrieved) { if (asset_type === VAR_CSS && source === VAR_CSSTEXT) { // cache-css module MODULE(READ_CSSTEXT, assetEl, function(text) { textRetrieved = source; save(text); }, 1); } // CORS or XHR if (source !== VAR_CSSTEXT) { // XHR module to retrieve asset source MODULE(XHR, [src, xhr_options, // xhr settings sources_cors ? cors_options : 0, // cors proxy source === VAR_CORS // force cors ], save); textRetrieved = source; } } }); } // requestIdleCallback MODULE(_requestIdleCallback, save_callback, save_callback); } } var cached, asset = args[0], options = args[1], asset_type = args[2], attrs = OBJECT(args[3]), cache_options = OBJECT(options[VAR_CACHE]), src = args[4], cache = OBJECT(asset[VAR_CACHE] || cache_options, VAR_TYPE), disabled, cache_method_disabled, assetEl, skip_cache_save_max_size, // skip cache save when previously skipped due to max size text, xhr_options = cache_or_options(VAR_XHR), cors_options = cache_or_options(VAR_CORS), sources = ARRAY(cache_or_options(VAR_SOURCE, [VAR_CSSTEXT, VAR_XHR, VAR_CORS])), sources_cors, sources_xhr; // @todo (IE8 fix) FOREACH(sources, function(source, i) { sources[i] = source = VAR_INDEX(source); if (source === VAR_CORS) { sources_cors = 1; } if (source === VAR_XHR) { sources_xhr = 1; } }); // get from cache if (src && cache[VAR_TYPE]) { // cache after render ONCE(src, save_asset); CACHE_GET(src, cache, function(cached, method_disabled) { cache_method_disabled = method_disabled; if (cached) { // load css via <style> text = cached[0]; // remove save handler OFF(src, save_asset); // stylesheet if (asset_type === VAR_CSS) { MODULE(CACHE_CSS, [asset, attrs, src, text], function(_assetEl, _attrs) { assetEl = _assetEl; attrs = _attrs; }, 1); } else { // script MODULE(CACHE_JS, [attrs, src, text], function(_text, _attrs) { assetEl = _text; // exec via little-loader attrs = _attrs; }, 1); } // update asset in background MODULE(CACHE_UPDATE, [ src, asset, cache, cached, xhr_options, sources_cors ? cors_options : 0, // cors proxy !sources_xhr // force cors proxy ]); cached = [assetEl, attrs]; if (DEBUG) { if (cached[1] === VAR_LOCALSTORAGE) { cached[2] = 'localStorage'; } if (cached[1] === VAR_CACHE_API) { cached[2] = 'cache-api'; } } } callback(cached); }); } else { callback(); } }
pwendell/akka
akka-persistence/src/main/scala/akka/persistence/journal/japi/AsyncWriteJournal.scala
/** * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com> */ package akka.persistence.journal.japi import scala.collection.immutable import scala.collection.JavaConverters._ import akka.persistence.journal.{ AsyncWriteJournal ⇒ SAsyncWriteJournal } import akka.persistence.PersistentRepr /** * Java API: abstract journal, optimized for asynchronous, non-blocking writes. */ abstract class AsyncWriteJournal extends AsyncReplay with SAsyncWriteJournal with AsyncWritePlugin { import context.dispatcher final def writeAsync(persistentBatch: immutable.Seq[PersistentRepr]) = doWriteAsync(persistentBatch.asJava).map(Unit.unbox) final def deleteAsync(processorId: String, fromSequenceNr: Long, toSequenceNr: Long, permanent: Boolean) = doDeleteAsync(processorId, fromSequenceNr, toSequenceNr, permanent).map(Unit.unbox) final def confirmAsync(processorId: String, sequenceNr: Long, channelId: String) = doConfirmAsync(processorId, sequenceNr, channelId).map(Unit.unbox) }
Oluwasegun-AA/BackEnd
mongoDb/helpers/validator.js
<gh_stars>0 import { isEmpty } from 'lodash'; // const extractJoiErrorMessage = error => { // const { message } = error.details[0]; // return message // .replace(/"/g, ''); // }; // const joiValidateHelper = async (req, res, next, schema) => { // try { // await schema.validateAsync(req.body); // next(); // } catch (err) { // const msg = extractJoiErrorMessage(err); // ResponseHandler.error( // res, // statusCodes.badRequest, // statusMessages.badRequest(msg) // ); // } // }; const checkEvery = data => data.every(data => isEmpty(data.userId) && isEmpty(data.username)); const validate = (Model, data) => { const newModel = new Model(data); const error = newModel.validateSync(); return error; }; const validatePath = async (schema, pathName) => { schema .path(pathName) .validate( data => !checkEvery(data), `Bad request, ${pathName} not supplied or invalid ` ); }; export { validate, validatePath };
bmccarthy/looker-go-sdk
client/user/create_user_access_filter_responses.go
// Code generated by go-swagger; DO NOT EDIT. package user // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" models "github.com/billtrust/looker-go-sdk/models" ) // CreateUserAccessFilterReader is a Reader for the CreateUserAccessFilter structure. type CreateUserAccessFilterReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *CreateUserAccessFilterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewCreateUserAccessFilterOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewCreateUserAccessFilterBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewCreateUserAccessFilterNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 409: result := NewCreateUserAccessFilterConflict() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 422: result := NewCreateUserAccessFilterUnprocessableEntity() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewCreateUserAccessFilterOK creates a CreateUserAccessFilterOK with default headers values func NewCreateUserAccessFilterOK() *CreateUserAccessFilterOK { return &CreateUserAccessFilterOK{} } /*CreateUserAccessFilterOK handles this case with default header values. Access Filter */ type CreateUserAccessFilterOK struct { Payload *models.AccessFilter } func (o *CreateUserAccessFilterOK) Error() string { return fmt.Sprintf("[POST /users/{user_id}/access_filters][%d] createUserAccessFilterOK %+v", 200, o.Payload) } func (o *CreateUserAccessFilterOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.AccessFilter) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateUserAccessFilterBadRequest creates a CreateUserAccessFilterBadRequest with default headers values func NewCreateUserAccessFilterBadRequest() *CreateUserAccessFilterBadRequest { return &CreateUserAccessFilterBadRequest{} } /*CreateUserAccessFilterBadRequest handles this case with default header values. Bad Request */ type CreateUserAccessFilterBadRequest struct { Payload *models.Error } func (o *CreateUserAccessFilterBadRequest) Error() string { return fmt.Sprintf("[POST /users/{user_id}/access_filters][%d] createUserAccessFilterBadRequest %+v", 400, o.Payload) } func (o *CreateUserAccessFilterBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.Error) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateUserAccessFilterNotFound creates a CreateUserAccessFilterNotFound with default headers values func NewCreateUserAccessFilterNotFound() *CreateUserAccessFilterNotFound { return &CreateUserAccessFilterNotFound{} } /*CreateUserAccessFilterNotFound handles this case with default header values. Not Found */ type CreateUserAccessFilterNotFound struct { Payload *models.Error } func (o *CreateUserAccessFilterNotFound) Error() string { return fmt.Sprintf("[POST /users/{user_id}/access_filters][%d] createUserAccessFilterNotFound %+v", 404, o.Payload) } func (o *CreateUserAccessFilterNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.Error) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateUserAccessFilterConflict creates a CreateUserAccessFilterConflict with default headers values func NewCreateUserAccessFilterConflict() *CreateUserAccessFilterConflict { return &CreateUserAccessFilterConflict{} } /*CreateUserAccessFilterConflict handles this case with default header values. Resource Already Exists */ type CreateUserAccessFilterConflict struct { Payload *models.Error } func (o *CreateUserAccessFilterConflict) Error() string { return fmt.Sprintf("[POST /users/{user_id}/access_filters][%d] createUserAccessFilterConflict %+v", 409, o.Payload) } func (o *CreateUserAccessFilterConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.Error) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateUserAccessFilterUnprocessableEntity creates a CreateUserAccessFilterUnprocessableEntity with default headers values func NewCreateUserAccessFilterUnprocessableEntity() *CreateUserAccessFilterUnprocessableEntity { return &CreateUserAccessFilterUnprocessableEntity{} } /*CreateUserAccessFilterUnprocessableEntity handles this case with default header values. Validation Error */ type CreateUserAccessFilterUnprocessableEntity struct { Payload *models.ValidationError } func (o *CreateUserAccessFilterUnprocessableEntity) Error() string { return fmt.Sprintf("[POST /users/{user_id}/access_filters][%d] createUserAccessFilterUnprocessableEntity %+v", 422, o.Payload) } func (o *CreateUserAccessFilterUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ValidationError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
HeliumEdu/platform
helium/auth/views/apis/usersettingsviews.py
<reponame>HeliumEdu/platform import logging from django.contrib.auth import get_user_model from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from helium.auth.serializers.usersettingsserializer import UserSettingsSerializer from helium.common.views.views import HeliumAPIView __author__ = "<NAME>" __copyright__ = "Copyright 2021, Helium Edu" __version__ = "1.4.46" logger = logging.getLogger(__name__) class UserSettingsApiDetailView(HeliumAPIView): """ put: Update the authenticated user's settings. This endpoint only updates the fields given (i.e. no need to PATCH for partials data). For more details pertaining to choice field values, [see here](https://github.com/HeliumEdu/platform/wiki#choices). """ queryset = get_user_model().objects.all() serializer_class = UserSettingsSerializer permission_classes = (IsAuthenticated,) def get_object(self): return self.request.user def put(self, request, *args, **kwargs): user = self.get_object() serializer = self.get_serializer(user.settings, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() logger.info(f'Settings updated for user {user.get_username()}') return Response(serializer.data)
liyongquan/leetcode-project
src/test/java/com/liyongquan/dfs/NQueens2Test.java
package com.liyongquan.dfs; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class NQueens2Test { private NQueens2 nQueens2 = new NQueens2(); @Test public void totalNQueens() { int i = nQueens2.totalNQueens(4); Assert.assertEquals(2, i); } }
gyliug/isstech
entfrm-core/entfrm-data/src/main/java/com/entfrm/data/enums/DataTypeEnum.java
package com.entfrm.data.enums; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author yong * @date 2020/3/24 * @description 数据类型 */ @Getter @AllArgsConstructor public enum DataTypeEnum { /** * mysql */ MYSQL("mysql", "com.mysql.cj.jdbc.Driver"), /** * sqlserver */ SQLSERVER("sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver"), /** * oracle */ ORACLE("oracle", "oracle.jdbc.driver.OracleDriver"), /** * Postgresql */ POSTGRESQL("postgresql", "org.postgresql.Driver"), /** * sqlite */ SQLITE("sqlite", "org.sqlite.JDBC"); /** * 类型 */ private final String type; /** * 驱动 */ private final String driverClassName; }
dbartok/advent-of-code-cpp
src/AdventOfCode2018/Day10-TheStarsAlign/Day10-TheStarsAlign.cpp
#include "Day10-TheStarsAlign.h" #include "StarAligner.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include <regex> __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2018 { namespace Day10 { std::vector<Starlight> createMoons(const std::vector<std::string>& starlightLines) { std::vector<Starlight> starlights; for (const auto& line : starlightLines) { std::regex coordinatesRegex(R"(position=<\s*(-?[0-9]+),\s*(-?[0-9]+)>\s*velocity=<\s*(-?[0-9]+),\s*(-?[0-9]+)>)"); std::smatch coordinatesMatch; std::regex_match(line, coordinatesMatch, coordinatesRegex); CoordinateNumericType posX = std::stoi(coordinatesMatch[1].str()); CoordinateNumericType posY = std::stoi(coordinatesMatch[2].str()); CoordinateNumericType velocityX = std::stoi(coordinatesMatch[3].str()); CoordinateNumericType velocityY = std::stoi(coordinatesMatch[4].str()); starlights.emplace_back(Vector2D{posX, posY}, Vector2D{velocityX, velocityY}); } return starlights; } std::string serializedMessageWhenAligned(const std::vector<std::string>& starlightLines) { std::vector<Starlight> starlights = createMoons(starlightLines); StarAligner starAligner{std::move(starlights)}; starAligner.align(); return starAligner.getSerializedMessage(); } unsigned timeTakenUntilAligned(const std::vector<std::string>& starlightLines) { std::vector<Starlight> starlights = createMoons(starlightLines); StarAligner starAligner{std::move(starlights)}; starAligner.align(); return starAligner.getTimeUnitsElapsed(); } } } }
bradchesney79/illacceptanything
linux/tools/perf/util/tsc.h
#ifndef __PERF_TSC_H #define __PERF_TSC_H #include <linux/types.h> #include "../arch/x86/util/tsc.h" u64 perf_time_to_tsc(u64 ns, struct perf_tsc_conversion *tc); u64 tsc_to_perf_time(u64 cyc, struct perf_tsc_conversion *tc); u64 rdtsc(void); #endif
ZHANGTIANYAO1/H-60
addons/UH60/config/MFD/FDLeft.hpp
class FDLeft:FDRight { topLeft="FDLeft_LT"; topRight="FDLeft_RT"; bottomLeft="FDLeft_LD"; };
npocmaka/Windows-Server-2003
net/dhcp/server/mm/oclassdl.c
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100 //================================================================================ // Copyright (C) 1997 Microsoft Corporation // Author: RameshV // Description: implements the basic structures for storing complete option configuration info // ThreadSafe: no // Locks: none // Please read stdinfo.txt for programming style. //================================================================================ #include <mm.h> #include <array.h> #include <optdefl.h> #include "oclassdl.h" #include "server\uniqid.h" //BeginExport(function) DWORD MemOptClassDefListFindOptDefList( IN OUT PM_OPTCLASSDEFLIST OptClassDefList, IN DWORD ClassId, IN DWORD VendorId, OUT PM_OPTDEFLIST *OptDefList ) //EndExport(function) { ARRAY_LOCATION Location; DWORD Error; PM_OPTCLASSDEFL_ONE OneClassDefList; AssertRet(OptClassDefList && OptDefList, ERROR_INVALID_PARAMETER); *OptDefList = NULL; for( Error = MemArrayInitLoc(&OptClassDefList->Array, &Location) ; ERROR_FILE_NOT_FOUND != Error ; Error = MemArrayNextLoc(&OptClassDefList->Array, &Location) ) { Require(ERROR_SUCCESS == Error ); Error = MemArrayGetElement( &OptClassDefList->Array, &Location, (LPVOID*)&OneClassDefList ); Require(ERROR_SUCCESS == Error && OneClassDefList); if( OneClassDefList->ClassId == ClassId && OneClassDefList->VendorId == VendorId ) { *OptDefList = &OneClassDefList->OptDefList; return ERROR_SUCCESS; } } return ERROR_FILE_NOT_FOUND; } //BeginExport(function) DWORD MemOptClassDefListAddOptDef( IN OUT PM_OPTCLASSDEFLIST OptClassDefList, IN DWORD ClassId, IN DWORD VendorId, IN DWORD OptId, IN DWORD Type, IN LPWSTR Name, IN LPWSTR Comment, IN LPBYTE OptVal, IN DWORD OptLen, IN ULONG UniqId ) //EndExport(function) { DWORD Error; PM_OPTCLASSDEFL_ONE OneClassDefList; PM_OPTDEFLIST OptDefList; AssertRet(OptClassDefList, ERROR_INVALID_PARAMETER); OneClassDefList = NULL; Error = MemOptClassDefListFindOptDefList( OptClassDefList, ClassId, VendorId, &OptDefList ); if( ERROR_SUCCESS != Error ) { Require(ERROR_FILE_NOT_FOUND == Error); OneClassDefList = MemAlloc(sizeof(*OneClassDefList)); if( NULL == OneClassDefList) return ERROR_NOT_ENOUGH_MEMORY; // RefCount on ClassId needs to be bumped up? OneClassDefList->ClassId = ClassId; OneClassDefList->VendorId = VendorId; Error = MemOptDefListInit(&OneClassDefList->OptDefList); if( ERROR_SUCCESS != Error ) { MemFree(OneClassDefList); return Error; } Error = MemArrayAddElement(&OptClassDefList->Array, OneClassDefList); if( ERROR_SUCCESS != Error) { MemFree(OneClassDefList); return Error; } OptDefList = &OneClassDefList->OptDefList; } Error = MemOptDefListAddOptDef( OptDefList, OptId, Type, Name, Comment, OptVal, OptLen, UniqId ); return Error; } // MemOptDefListAddOptDef() //================================================================================ // end of file //================================================================================
btihen/shared_schedule
spec/models/user_interest_spec.rb
require 'rails_helper' RSpec.describe UserInterest, type: :model do describe "factory functions" do it "generates a valid user" do model = FactoryBot.build :user_interest expect(model.valid?).to be true end end describe "relationships" do it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:category) } end describe "destroy records - check dependents" do let(:tenant) { FactoryBot.create :tenant } let(:category) { FactoryBot.create :category, tenant: tenant } let(:user_1) { FactoryBot.create :user, interests: [category], tenant: tenant } let(:user_2) { FactoryBot.create :user, interests: [category], tenant: tenant } it "#destroy_all" do expect(user_1).to be expect(user_2).to be described_class.destroy_all expect(User.all).to eq [user_1, user_2] expect(Category.all).to eq [category] expect(Tenant.all).to eq [tenant] expect(UserInterest.all).to eq [] end it "#destroy" do expect(user_1).to be expect(user_2).to be user_1.destroy expect(User.all).to eq [user_2] expect(Category.all).to eq [category] expect(Tenant.all).to eq [tenant] expect(UserInterest.all.pluck(:user_id)).to eq UserInterest.where(user: user_2).all.pluck(:user_id) end end describe "validations" do it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:category) } end describe "DB settings" do it { have_db_index(:user) } it { have_db_index(:category) } end # describe "model methods" end
Biirra/Leaflet_Playground
Models/Property.js
class Property{ } class Car extends Property{ _brand; }
ovatacms/ovata-content-repository
ovata-cr-api/src/main/java/ch/ovata/cr/spi/store/StoreCollection.java
/* * $Id: StoreCollection.java 679 2017-02-25 10:28:00Z dani $ * Created on 12.01.2017, 19:00:00 * * Copyright (c) 2017 by Ovata GmbH, * All rights reserved. * * This software is the confidential and proprietary information * of Ovata GmbH ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Ovata GmbH. */ package ch.ovata.cr.spi.store; import java.util.Collection; /** * * @author dani */ public interface StoreCollection extends StoreDocumentFactory { /** * Insert single document into this collection * @param document the document to insert */ void init( StoreDocument document); /** * Insert a set of documents in bulk into this collection * @param trx the currently active transaction * @param documents the documents to insert */ void insertMany( Transaction trx, Collection<StoreDocument> documents); /** * Find single document representing a node by primary key and revision * @param nodeId the primary key of the node * @param revision the revision to pick * @return the node document */ StoreDocument findById( String nodeId, long revision); /** * Find a child node's document by name and revision * @param parentId the primary key of the parent node * @param name the child node's name * @param revision the revision to pick * @return the node document */ StoreDocument findByParentIdAndName( String parentId, String name, long revision); /** * Find all child nodes by parent id and revision * @param parentId the primary key of the parent node * @param revision the revision to pick * @return the collection of node documents */ StoreDocumentIterable findByParentId( String parentId, long revision); }
UNSW-CFRC/online-whatif
src/main/java/au/org/aurin/wif/model/reports/demand/DemandAnalysisReport.java
<filename>src/main/java/au/org/aurin/wif/model/reports/demand/DemandAnalysisReport.java /** * */ package au.org.aurin.wif.model.reports.demand; import java.util.ArrayList; import java.util.List; import au.org.aurin.wif.model.demand.AreaRequirement; import au.org.aurin.wif.model.reports.ScenarioReport; /** * The Class SuitabilityAnalysisReport. In summary, to perform a demand scenario * analysis you must have the following setup (see What if demand assumptions * report) : - What If suitability setup complete. - Current demographic data * (2005), global to the project. - Need to have a demographic trend with * demographic data (population, current density etc) for the projection years, * in this case there is information only for 2010 and 2015. This information is * global to the project. - Projected data specific to each scenario (like * future breakdown of all units and future density). You can differentiate this * information from the global information, because in the What If desktop * program, it is grayed out and you cannot modify it when you are in the demand * scenario specific screen! - This analysis will create an area requirement for * each land use in each future projection year. * * @author <NAME> */ public class DemandAnalysisReport extends ScenarioReport { /** The Constant serialVersionUID. */ private static final long serialVersionUID = -2793636824302358781L; private List<AreaRequirement> outcome; /** * */ public DemandAnalysisReport() { super(); outcome = new ArrayList<AreaRequirement>(); } /** * @return the outcome */ public List<AreaRequirement> getOutcome() { return outcome; } /** * @param outcome * the outcome to set */ public void setOutcome(List<AreaRequirement> outcome) { this.outcome = outcome; } }
egotter/egotter
app/lib/dynamo_db/tweet.rb
# -*- SkipSchemaAnnotations module DynamoDB class Tweet extend ::DynamoDB::Util attr_reader :raw_attrs_text def initialize(tweet) @raw_attrs_text = tweet[:raw_attrs_text] end class << self def table_name raise NotImplementedError end def partition_key 'uid' end def array_from(tweets) tweets.map { |t| new(t) } end def find_by(uid) item = client.read(uid).item tweets = item && item['json'] ? parse_json(decompress(item['json'])) : nil tweets ? array_from(tweets[:tweets]) : [] rescue => e Rails.logger.warn "#{self}##{__method__} failed #{e.inspect}" [] end def delete_by(uid) client.delete(uid) end def import_from(uid, tweets) payload = {tweets: tweets} item = { uid: uid, json: compress(payload.to_json), expiration_time: TABLE_TTL.since.to_i } client.write(uid, item) end private def client @client ||= ::DynamoDB::Client.new(self, table_name, partition_key) end end end end
pingjuiliao/cb-multios
challenges/Shipgame/cb_3/lib/cgc_mylibc.h
#ifndef MY_LIB_C_H #define MY_LIB_C_H #include "cgc_inttypes.h" #include "cgc_string.h" #include "cgc_printf.h" //reads in a new line and returns the number of characters cgc_read // Returns the number of characters cgc_read otherwise it will return 0 // or an errno on error // errno can be // The errno from fdwait or receive // it can also be -EINVAL if buf is NULL. cgc_ssize_t cgc_readLine(int fd, char* buf, cgc_size_t len); #endif//MY_LIB_C_H
iamacup/sliips-web
src/content/components/Navigation/LeftComponents/companyProfile.js
<reponame>iamacup/sliips-web import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; const LeftComponents = ({ companyName }) => ( <ul className="nav navbar-nav navbar-left"> <li> <Link className="navbar-company-title" to="/company-list" href="/company-list" > {companyName} </Link> </li> </ul> ); LeftComponents.propTypes = { companyName: PropTypes.string.isRequired, }; export default LeftComponents;
softicar/platform
platform-emf/src/main/java/com/softicar/platform/emf/permission/finder/EmfStaticPermissionFieldFinder.java
<gh_stars>1-10 package com.softicar.platform.emf.permission.finder; import com.softicar.platform.common.code.java.reflection.DeclaredFieldFinder; import com.softicar.platform.common.code.java.reflection.TypeParameterAnalyzer; import com.softicar.platform.common.core.utils.ReflectionUtils; import com.softicar.platform.emf.permission.statik.IEmfStaticPermission; import com.softicar.platform.emf.table.IEmfTable; import java.lang.reflect.Field; public class EmfStaticPermissionFieldFinder extends DeclaredFieldFinder { private final IEmfTable<?, ?, ?> table; public EmfStaticPermissionFieldFinder(IEmfTable<?, ?, ?> table) { super(table.getClass()); this.table = table; setFilter(this::isStaticPermissionField); } private boolean isStaticPermissionField(Field field) { return ReflectionUtils.isPublicStaticFinal(field)// && ReflectionUtils.isDeclaredType(field, IEmfStaticPermission.class)// && isExpectedGenericType(table, field); } private boolean isExpectedGenericType(IEmfTable<?, ?, ?> table, Field permissionField) { return new TypeParameterAnalyzer(permissionField).hasExpectedTypeParameter(table.getValueClass()); } }
UXSoc/jta-gatsby
src/components/HeroDescription/HeroDescription.js
<gh_stars>0 import React from 'react'; import PropTypes from 'prop-types'; const HeroDescription = props => ( <section className="section"> <div className="container"> {props.title.length > 0 && <h4 className="title is-4">{props.title}</h4>} <p>{props.description}</p> </div> </section> ); HeroDescription.propTypes = { title: PropTypes.string, description: PropTypes.string, }; export default HeroDescription;
2283533702/mianshiya-public
cloudfunctions/comment/addComment/index.js
<gh_stars>1-10 const cloud = require('@cloudbase/node-sdk'); const app = cloud.init({ env: cloud.SYMBOL_CURRENT_ENV, }); const db = app.database(); const _ = db.command; const xss = require('xss'); const cheerio = require('cheerio'); /** * 创建回答 * @param event * @param context * @return {Promise<*|boolean>} */ exports.main = async (event, context) => { let { content, questionId } = event; if (!content || !questionId) { return false; } // 如果不包含任何文本 if (!cheerio.load(content).text().trim()) { return false; } // 防止 XSS 攻击 content = xss(content); // 获取当前登录用户 const { userInfo } = app.auth().getEndUserInfo(); if (!userInfo || !userInfo.customUserId) { return false; } const currentUser = await db .collection('user') .where({ unionId: userInfo.customUserId, isDelete: false, }) .limit(1) .get() .then(({ data }) => data[0]); if (!currentUser || !currentUser._id) { return false; } const transaction = await db.startTransaction(); try { const id = await db .collection('comment') .add({ userId: currentUser._id, questionId, content, priority: 0, thumbNum: 0, reviewStatus: 1, // 默认审核通过 _createTime: new Date(), _updateTime: new Date(), isDelete: false, }) .then((res) => { console.log('addComment succeed', res); return res.id; }); // 题目评论数 +1 await updateQuestionCommentNum(transaction, questionId, 1); await transaction.commit(); return id; } catch (e) { console.error('addComment error', e); await transaction.rollback(); return -1; } }; /** * 更新题目回答数 * @param transaction * @param questionId * @param num * @return {*} */ function updateQuestionCommentNum(transaction, questionId, num) { return transaction .collection('question') .doc(questionId) .update({ commentNum: _.inc(num), _updateTime: new Date(), }); }
gurfinkel/codeSignal
tournaments/regexMatching/regexMatching.js
function regexMatching(pattern, test) { return !!~test.indexOf(pattern.replace(/\^|\$/, '')); }
Trisk3lion/mapa
cobol/src/CharDataWrapper.java
<reponame>Trisk3lion/mapa import java.util.*; import java.lang.reflect.*; import org.antlr.v4.runtime.tree.*; /** CharDataKeywordWrapper, CharDataLineWrapper, CharDataWrapper, CobolWordWrapper (not to be confused with CobolWord), DirectoryPhrase, FilenameWrapper, LiteralWrapper, and PseudoTextWrapper are all in service to the preprocessing that resolves COPY REPLACING and REPLACE statements. Their primary purpose is to create a collection of TerminalNodeWrapper instances which are used in CopyReplaceParent::applyReplacingPhrase(). */ class CharDataWrapper { private String myName = this.getClass().getName(); private CobolPreprocessorParser.CharDataContext ctx = null; private ArrayList<CharDataLineWrapper> charData = null; private ArrayList<TerminalNodeWrapper> tnwList = new ArrayList<>(); private Boolean leading = false; private Boolean trailing = false; public CharDataWrapper(CobolPreprocessorParser.CharDataContext ctx) { this.ctx = ctx; if (this.ctx.NEWLINE() != null && this.ctx.NEWLINE().size() > 0) { this.tnwList.addAll(TerminalNodeWrapper.bunchOfThese(this.ctx.NEWLINE())); } if (this.ctx.charDataLine() != null && this.ctx.charDataLine().size() > 0) { this.charData = CharDataLineWrapper.bunchOfThese(this.ctx.charDataLine()); for (CharDataLineWrapper w: this.charData) { this.tnwList.addAll(w.getTerminalNodeWrappers()); } } this.tnwList.sort(Comparator.comparingLong(TerminalNodeWrapper::getSortKey)); } public CharDataWrapper(CobolPreprocessorParser.CharDataContext ctx, Boolean leading, Boolean trailing) { this.ctx = ctx; this.leading = leading; this.trailing = trailing; if (this.ctx.NEWLINE() != null && this.ctx.NEWLINE().size() > 0) { this.tnwList.addAll(TerminalNodeWrapper.bunchOfThese(this.ctx.NEWLINE(), this.leading, this.trailing)); } if (this.ctx.charDataLine() != null && this.ctx.charDataLine().size() > 0) { this.charData = CharDataLineWrapper.bunchOfThese(this.ctx.charDataLine(), this.leading, this.trailing); for (CharDataLineWrapper w: this.charData) { this.tnwList.addAll(w.getTerminalNodeWrappers()); } } this.tnwList.sort(Comparator.comparingLong(TerminalNodeWrapper::getSortKey)); } public ArrayList<TerminalNodeWrapper> getTerminalNodeWrappers() { return this.tnwList; } }
uniqueck/a4ad
domain/src/main/java/com/github/a4ad/domain/manage/Artifact.java
package com.github.a4ad.domain.manage; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Value; import java.util.Optional; @AllArgsConstructor(access = AccessLevel.PRIVATE) public class Artifact { private final ArtifactId id; public static Artifact withId(ArtifactId id) { return new Artifact(id); } public static Artifact withoutId() { return new Artifact(null); } public Optional<ArtifactId> getId() {return Optional.ofNullable(id);} @Value public static class ArtifactId { private Long value; } }
adinkwok/android_frameworks_support
samples/SupportLeanbackDemos/src/main/java/com/example/android/leanback/PlaybackSeekDataProviderSample.java
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.leanback; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; /** * Sample PlaybackSeekDataProvider render time label as thumb. */ class PlaybackSeekDataProviderSample extends PlaybackSeekAsyncDataProvider { Paint mPaint; PlaybackSeekDataProviderSample(long duration, long interval) { int size = (int) (duration / interval) + 1; long[] pos = new long[size]; for (int i = 0; i < pos.length; i++) { pos[i] = i * duration / pos.length; } setSeekPositions(pos); mPaint = new Paint(); mPaint.setTextSize(16); mPaint.setColor(Color.BLUE); } protected Bitmap doInBackground(Object task, int index, long position) { try { Thread.sleep(100); } catch (InterruptedException ex) { // Thread might be interrupted by cancel() call. } if (isCancelled(task)) { return null; } Bitmap bmp = Bitmap.createBitmap(160, 160, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); canvas.drawColor(Color.YELLOW); canvas.drawText(formatTime(position), 10, 80, mPaint); canvas.drawText(Integer.toString(index), 10, 150, mPaint); return bmp; } String formatTime(long ms) { long seconds = ms / 1000; float seconds2 = (ms - seconds * 1000) / 1000f; long minutes = seconds / 60; long hours = minutes / 60; seconds -= minutes * 60; minutes -= hours * 60; StringBuilder b = new StringBuilder(); if (hours > 0) { b.append(hours).append(':'); if (minutes < 10) { b.append('0'); } } b.append(minutes).append(':'); if (seconds < 10) { b.append('0'); } b.append(String.format("%.2f", ((float) seconds + seconds2))); return b.toString(); } }
Maastro-CDS-Imaging-Group/SQLite4Radiomics
radiomicsfeatureextractionpipeline/backend/src/bootstrapper/radiomic_feature_extraction_pipeline_bootstrapper.py
""" This module is used for booting up the Radiomic Feature Extraction Pipeline tool It will also start the correct tool depending on the given input while calling the script. Currently we have 3 different programs available: 1. GUI 2. ROIPrioritySetter 3. Extraction Pipeline ToDo: Explain programs """ import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import importlib.util import inspect import logging import sys from importlib._bootstrap import ModuleSpec from typing import Any, Optional from cli.radiomic_feature_extraction_pipeline_cli import CLI from configuration_service.config_file_reader import ConfigFileReader from configuration_service.configuration_service import ConfigurationService from dal.data_access_layer import DataAccessLayer from dal.database_connector import DatabaseConnector from dal.image_repository import ImageRepository from dal.patient_repository import PatientRepository from dal.radiomic_feature_repository import RadiomicFeatureRepository from dal.roi_repository import ROIRepository from dal.series_repository import SeriesRepository from dal.sqlite.database_connector_sqlite import DatabaseConnectorSqlite from dal.sqlite.image_repository_sqlite import ImageRepositorySqlite from dal.sqlite.patient_repository_sqlite import PatientRepositorySqlite from dal.sqlite.radiomic_feature_repository_sqlite import RadiomicFeatureRepositorySqlite from dal.sqlite.roi_repository_sqlite import ROIRepositorySqlite from dal.sqlite.series_repository_sqlite import SeriesRepositorySqlite from dal.sqlite.study_repository_sqlite import StudyRepositorySqlite from dal.study_repository import StudyRepository from gui.radiomic_feature_extraction_pipeline_gui import GUI from logic.binary_mask_and_3d_image_generator.binary_mask_and_3d_image_generator import \ BinaryMaskAnd3DImageGenerator from logic.dicom_file_reader.dicom_file_reader import DicomFileReader from logic.feature_extractor.feature_calculator import FeatureCalculator from logic.logic import Logic from logic.roi_selector.roi_selector import ROISelector from logic.roi_selector.roi_selector_properties import \ ROISelectorProperties from logic.utils.logging_utils import setup_logging logger: logging.Logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) setup_logging(filename='logs/bootstrapper.log', name=__name__, use_stdout=False) class Bootstrapper: """ This class is used for instantiating the other software components of the tool. It will also start the correct tool depending on the given input while calling the script. """ def __init__(self) -> None: """ Constructor of the Bootstrapper. Creates instances off all necessary software components that the tool needs. """ # An instance of the ConfigurationService will be created which will handle the reading of and writing to the # conquest dicom.ini file. self.config_file_reader_conquest: ConfigFileReader = ConfigFileReader(r'..\Conquest\dicom.ini') self.conquest_settings: ConfigurationService = ConfigurationService(self.config_file_reader_conquest) # An instance of the ConfigurationService will be created which will handle the reading of and writing to the # conquest dicom.ini file. self.config_file_reader_feature_extraction: ConfigFileReader = ConfigFileReader(r"resources\config.ini") self.feature_extraction_settings: ConfigurationService = ConfigurationService( self.config_file_reader_feature_extraction) # The bootstrapper asks the feature extraction configuration file reader what type of database it should # connect to. database_type: str = self.feature_extraction_settings.load_database_type() # Empty field creation. These fields will later be used to store an instance of the DataAccessLayer, the GUI # and the CLI. self.data_access_layer: DataAccessLayer self.gui: Optional[GUI] = None self.cli: Optional[CLI] = None # If the database type is sqlite then the create_sqlite_data_access_layer method will be called. if database_type.lower() == 'sqlite': self.data_access_layer = self.create_sqlite_data_access_layer() # Loads the file path of the parameter file for PyRadiomics. pyradiomics_settings: str = self.feature_extraction_settings.load_radiomics_params_file() # Loads all the properties from the configuration-file that will be used by the ROISelectors. roi_selector_properties: ROISelectorProperties = ROISelectorProperties( self.feature_extraction_settings.load_roi_selector_properties()) # Loads the selected ROISelector from the file path that is defined in the configuration-file. roi_selector: ROISelector = self.load_strategies_from_configuration_file( 'Region of interest selector', ROISelector, self.data_access_layer.get_roi_repos(), roi_selector_properties) # Loads the selected BinaryMaskAnd3DImageGenerator from the file path that is defined in the configuration-file. binary_mask_and_3d_image_generator: BinaryMaskAnd3DImageGenerator = \ self.load_strategies_from_configuration_file('Binary mask and 3d image generator', BinaryMaskAnd3DImageGenerator) # Loads the selected DicomFileReader from the file path that is defined in the configuration-file. dicom_file_reader: DicomFileReader = self.load_strategies_from_configuration_file( 'Dicom file reader', DicomFileReader, self.conquest_settings.load_data_directory()) # Loads the selected FeatureCalculator from the file path that is defined in the configuration-file. feature_calculator: FeatureCalculator = self.load_strategies_from_configuration_file( 'Feature calculator', FeatureCalculator, self.data_access_layer.get_radiomic_feature_repos(), pyradiomics_settings) # Creates an instance of the Logic class. self.logic: Logic = Logic(self.data_access_layer, self.conquest_settings, self.feature_extraction_settings, roi_selector, binary_mask_and_3d_image_generator, dicom_file_reader, feature_calculator) def main(self) -> None: """ This main method starts the GUI, Priority setter or extraction pipeline depending on the system arguments. - If **-gui** is passed, the gui module is booted up. - If **-priority-setter** is passed, the priority_setter program is booted up. - If **-extraction-pipeline** *sop_instance_rtstruct* is passed, the extraction pipeline is booted up for the given sop-instance_rtstruct. """ # This if statement checks if no argument was given. if len(sys.argv) == 1: self.show_warning_no_or_wrong_arguments_were_passed() return # This if statement checks if the -gui parameter was given while calling the script. if sys.argv[1].lower() == '-gui': print('Booting up the gui...') # Creates an instance of the GUI (Graphical User Interface). self.gui = GUI(self.logic) # Starts the GUI self.gui.start() #Makes sure the GUI keeps running after it has been started. self.gui.mainloop() print('Boot up complete') return # An instance of the CLI (Command Line Interface) will be created since -gui was not passed as an argument. self.cli: CLI = CLI(self.logic) # This if statement checks if the -priority-setter parameter was given while calling the script. if sys.argv[1].lower() == '-priority-setter': # Starts the priority setter tool. self.cli.start_priority_setter() return # This if statement checks if the -extraction-pipeline parameter was given while calling the script. if sys.argv[1].lower() == '-extraction-pipeline': # Checks if a second argument was passed with the call for the script and checks if the parameter was valid. if len(sys.argv) == 2: # Displays error for missing sop-instance. print("The sop instance parameter was missing.") print("Please call script using the following parameters:") print("python -m bootstrapper -extraction-pipeline 'SOP-instance of RTSTRUCT'") return # Starts the extraction pipeline tool. self.cli.start_extraction_pipeline(sys.argv[2]) return # No options match the given argument. The argument was incorrect. self.show_warning_no_or_wrong_arguments_were_passed() @staticmethod def show_warning_no_or_wrong_arguments_were_passed() -> None: """ If the second argument wasn't given or was incorrect a warning will be returned! """ print('The expected arguments were missing or incorrect!') print("To start the GUI program use the '-gui' argument") print("To start the Priority Setter Program use the '-priority-setter' argument") print("To start the Extraction Pipeline Program use the '-extraction-pipeline' argument followed by a " "SOP-instance of an RTSTRUCT") def load_strategies_from_configuration_file(self, strategy_type: str, parent_class: Any, *args, **kwargs) -> Any: """ Loads the selected strategies for the given strategy type with the correct parameters. :param strategy_type: The name of the configuration files section where the selected strategy can be found. :param parent_class: The class that the strategy should inherit from. :param args: A series of non-named arguments that will be passed to the constructor of the selected strategy. :param kwargs: A series of named arguments that will be passed to the constructor of the selected strategy. :return: An instance of the selected strategy. """ # Loads the string that tells the program which strategy to select. selected_strategy: str = self.feature_extraction_settings.load_strategy_selection(strategy_type) # Loads the script location of the strategy that was selected. script_location: str = self.feature_extraction_settings.load_strategy(strategy_type, selected_strategy) # Loads the strategy itself using the static load_class_dynamically method. return self.load_class_dynamically(script_location, selected_strategy, parent_class, *args, **kwargs) def create_sqlite_data_access_layer(self) -> DataAccessLayer: """ Initialises an instance of the Data Access Layer which will store an instance of all data repositories. :return: An instance of the Data Access Layer. """ # Loads the saving method from the configuration-file type_of_save: str = self.feature_extraction_settings.load_save_type() # Sets the file location for the sqlite queries. queries_file_location: str = r"resources\queries\sqlite" # Creates an instance of the DatabaseConnectorSqlite which will be used to talk with the SQLite database. database_connector: DatabaseConnector = DatabaseConnectorSqlite( self.conquest_settings.load_database_settings()) # Creates an instance of the PatientRepository which will manage the saving of patient data to and # loading patient data from the database. patient_repos: PatientRepository = PatientRepositorySqlite(database_connector, queries_file_location) # Creates an instance of the StudyRepository which will manage the saving of study data to and # loading study data from the database. study_repos: StudyRepository = StudyRepositorySqlite(database_connector, queries_file_location) # Creates an instance of the SeriesRepository which will manage the saving of series data to and # loading series data from the database. series_repos: SeriesRepository = SeriesRepositorySqlite(database_connector, queries_file_location) # Creates an instance of the ImageRepository which will manage the saving of image data to and # loading image data from the database. image_repos: ImageRepository = ImageRepositorySqlite(database_connector, series_repos, patient_repos, study_repos, queries_file_location) # Creates an instance of the ROIRepository which will manage the saving of region of interest data to and # loading region of interest data from the database. roi_repos: ROIRepository = ROIRepositorySqlite(database_connector, series_repos, queries_file_location) # Creates an instance of the RadiomicFeatureRepository which will manage the saving of radiomic feature data # to and loading radiomic feature data from the database. radiomic_feature_repos: RadiomicFeatureRepository = RadiomicFeatureRepositorySqlite( database_connector, patient_repos, series_repos, queries_file_location, type_of_save) # Creates an instance of the DataAccessLayer. return DataAccessLayer(image_repos, patient_repos, radiomic_feature_repos, roi_repos, series_repos, study_repos) @staticmethod def load_class_dynamically(file_path: str, module_name: str, parent_class: Any, *args, **kwargs) -> None: """ Loads python script from file path. :param file_path: File path to the script to load. :param module_name: Name for the model of the script. :param parent_class: The parent class of the class that will be loaded. :param args: A series of non-named arguments that will be passed to the constructor of the selected strategy. :param kwargs: A series of named arguments that will be passed to the constructor of the selected strategy. :return: Instance of the loaded class. """ # Loads module from script. spec: ModuleSpec = importlib.util.spec_from_file_location(module_name, file_path) module: ModuleSpec = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) name: str obj: type # Loops through all objects that were found. for name, obj in inspect.getmembers(module): # Checks if object is not a class. if not inspect.isclass(obj): continue # Checks if class is not a subclass of the given parent_class. if not issubclass(obj, parent_class): continue # Checks if class is instance parent_class. if name == parent_class.__name__: continue # The correct class was found. Instantiate class and return instance. return obj(*args, **kwargs) # Checks whether the script was called by the Python interpreter directly or by another script. if __name__ == "__main__": # If script was called by the Python interpreter, create an instance of the Bootstrapper bootstrapper = Bootstrapper() # Start the tool bootstrapper.main()
isra-fel/STL
tests/std/tests/P0896R4_ranges_alg_generate/test.cpp
<filename>tests/std/tests/P0896R4_ranges_alg_generate/test.cpp // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <algorithm> #include <cassert> #include <concepts> #include <ranges> #include <range_algorithm_support.hpp> using namespace std; constexpr auto iota_gen = [val = 0]() mutable { return val++; }; // Validate dangling story STATIC_ASSERT(same_as<decltype(ranges::generate(borrowed<false>{}, iota_gen)), ranges::dangling>); STATIC_ASSERT(same_as<decltype(ranges::generate(borrowed<true>{}, iota_gen)), int*>); struct instantiator { template <ranges::output_range<const int&> Out> static constexpr void call() { using ranges::generate, ranges::iterator_t; { int output[] = {13, 42, 1367}; Out out_wrapper{output}; auto result = generate(out_wrapper, iota_gen); STATIC_ASSERT(same_as<decltype(result), iterator_t<Out>>); assert(result == out_wrapper.end()); for (int i = 0; i < 3; ++i) { assert(i == output[i]); } } { int output[] = {13, 42, 1367}; Out out_wrapper{output}; auto result = generate(out_wrapper.begin(), out_wrapper.end(), iota_gen); STATIC_ASSERT(same_as<decltype(result), iterator_t<Out>>); assert(result == out_wrapper.end()); for (int i = 0; i < 3; ++i) { assert(i == output[i]); } } } }; int main() { STATIC_ASSERT((test_out<instantiator, int>(), true)); test_out<instantiator, int>(); }
MicrohexHQ/nacl_contracts
tests/ripple_ledger/return_payment.cc
/* * Ripple "contract" that returns XRP or USD payments. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/fcntl.h> #include <string.h> #include <unistd.h> #include <json/reader.h> #include "native_client/src/public/imc_syscalls.h" #include "native_client/src/public/name_service.h" #include "native_client/src/shared/srpc/nacl_srpc.h" #include "native_client/src/public/ripple_ledger_service.h" NaClSrpcChannel ns_channel; //Insert real values here. const char *ACCOUNT = "DummyContractAddress"; const char *SECRET = "DummyContractSecret"; const char *USD_ISSUER = "DummyUSDIssuer"; int ConnectToRippleLedgerService (NaClSrpcChannel* ledger_channel) { int ledger; int status; if (NACL_SRPC_RESULT_OK != NaClSrpcInvokeBySignature(&ns_channel, NACL_NAME_SERVICE_LOOKUP, "RippleLedgerService", O_RDWR, &status, &ledger)) { fprintf(stderr, "nameservice lookup RPC failed\n"); } if (-1 == ledger) { fprintf(stderr, "nameservice lookup failed: status %d\n", status); return 0; } int ledger_conn; ledger_conn = imc_connect(ledger); if (-1 == ledger_conn) { fprintf(stderr, "could not connect\n"); return 0; } if (!NaClSrpcClientCtor(ledger_channel, ledger_conn)) { fprintf(stderr, "could not build srpc client\n"); return 0; } close(ledger); return 1; } void HandleLedger(NaClSrpcRpc *rpc, NaClSrpcArg **in_args, NaClSrpcArg **out_args, NaClSrpcClosure *done) { const char *ledger_json = (const char*) in_args[0]->arrays.str; Json::Reader reader; Json::Value ledger_root; int ledger_index; NaClSrpcChannel ledger_channel; if ((!reader.parse(ledger_json, ledger_root))) { fprintf(stderr, "Error parsing ledger json.\n"); rpc->result = NACL_SRPC_RESULT_APP_ERROR; goto done; } ledger_index = ledger_root["ledger_index"].asInt(); if (!ConnectToRippleLedgerService(&ledger_channel)) { rpc->result = NACL_SRPC_RESULT_APP_ERROR; goto done; } if (NACL_SRPC_RESULT_OK != NaClSrpcInvokeBySignature(&ledger_channel, NACL_RIPPLE_LEDGER_SERVICE_GET_ACCOUNT_TXS, ACCOUNT, ledger_index, ledger_index, "new_transactions:s:")) { fprintf(stderr, "NACL_RIPPLE_LEDGER_SERVICE_GET_ACCOUNT_TXS failed\n"); rpc->result = NACL_SRPC_RESULT_APP_ERROR; goto done; } rpc->result = NACL_SRPC_RESULT_OK; done: done->Run(done); } void HandleTransactions(NaClSrpcRpc *rpc, NaClSrpcArg **in_args, NaClSrpcArg **out_args, NaClSrpcClosure *done) { NaClSrpcChannel ledger_channel; const std::string transactions_json = in_args[0]->arrays.str; const char *dummy_callback = ""; Json::Reader reader; Json::Value txs_root; Json::Value tx; const char *amount; const char *currency; const char *issuer; rpc->result = NACL_SRPC_RESULT_OK; /* Reciprocate payment transactions sent to the contract account. */ if ((!reader.parse(transactions_json, txs_root))) { fprintf(stderr, "Error parsing transaction json.\n"); rpc->result = NACL_SRPC_RESULT_APP_ERROR; goto done; } if (!ConnectToRippleLedgerService(&ledger_channel)) { rpc->result = NACL_SRPC_RESULT_APP_ERROR; goto done; } for (uint i=0; i<txs_root.size(); ++i) { if (txs_root[i]["tx"].empty()) { continue; } tx = txs_root[i]["tx"]; /* Only handle "Payment" transactions to the contract account. */ if (!tx["TransactionType"].isString() || tx["TransactionType"].asString()!="Payment" || !tx["Destination"].isString() || strcmp(tx["Destination"].asCString(), ACCOUNT)!=0 || !tx["Account"].isString()) { continue; } /* For XRP payments, "Amount" is a single string. For payments in other currencies, "Amount" is an object with a currency, issuer, and value. */ if (tx["Amount"].empty()) { fprintf(stderr, "Missing transaction amount data.\n"); continue; } /* XRP transaction */ else if (tx["Amount"].isString()) { amount = tx["Amount"].asCString(); currency = ""; issuer = ""; } /* USD transaction */ else if (tx["Amount"]["currency"].isString() && tx["Amount"]["currency"].asString()=="USD") { if (!tx["Amount"]["value"].isString()) { fprintf(stderr, "Missing transaction amount data.\n"); rpc->result = NACL_SRPC_RESULT_APP_ERROR; } amount = tx["Amount"]["value"].asCString(); currency = "USD"; issuer = USD_ISSUER; } else { continue; } if (NACL_SRPC_RESULT_OK != NaClSrpcInvokeBySignature(&ledger_channel, NACL_RIPPLE_LEDGER_SERVICE_SUBMIT_PAYMENT_TX, ACCOUNT, SECRET, tx["Account"].asCString(), amount, currency, issuer, dummy_callback)) { fprintf(stderr, "NACL_RIPPLE_LEDGER_SERVICE_SUBMIT_PAYMENT_TX failed\n"); rpc->result = NACL_SRPC_RESULT_APP_ERROR; } } done: done->Run(done); } const struct NaClSrpcHandlerDesc srpc_methods[] = { { "new_ledger:s:", HandleLedger }, { "new_transactions:s:", HandleTransactions }, { NULL, NULL }, }; int main(void) { int ns; int connected_socket; if (!NaClSrpcModuleInit()) { return 1; } ns = -1; nacl_nameservice(&ns); if (ns==-1) { fprintf(stderr, "Nameservice retrieval failed\n"); return 1; } connected_socket = imc_connect(ns); if (!NaClSrpcClientCtor(&ns_channel, connected_socket)) { fprintf(stderr, "Srpc client channel ctor failed\n"); return 1; } close(ns); if (!NaClSrpcAcceptClientConnection(srpc_methods)) { return 1; } NaClSrpcModuleFini(); return 0; }
CalvinMT/litiengine
src/de/gurkenlabs/litiengine/IGameLoop.java
package de.gurkenlabs.litiengine; public interface IGameLoop extends ILoop { public int perform(int delay, Runnable action); public void updateExecutionTime(int index, long ticks); public float getTimeScale(); public int getUpdateRate(); public void setTimeScale(float timeScale); }
CallumJohnson/FactionsBridge
Factions_MassiveCoreFactions/src/main/java/massivecorefactions/MassiveCoreFactionsClaim.java
<gh_stars>1-10 package massivecorefactions; import cc.javajobs.factionsbridge.bridge.infrastructure.AbstractClaim; import cc.javajobs.factionsbridge.bridge.infrastructure.struct.Claim; import cc.javajobs.factionsbridge.bridge.infrastructure.struct.Faction; import com.massivecraft.factions.entity.BoardColl; import com.massivecraft.massivecore.ps.PS; import org.bukkit.Chunk; import org.jetbrains.annotations.NotNull; /** * MassiveCore implementation of {@link Claim}. * Object Target: {@link PS}. * * @author <NAME> * @since 26/02/2021 - 15:11 */ public class MassiveCoreFactionsClaim extends AbstractClaim<PS> { /** * Constructor to create an AbstractClaim. * <p> * This class will be used to create each implementation of a 'Claim'. * </p> * * @param claim object which will be bridged using the FactionsBridge. */ public MassiveCoreFactionsClaim(@NotNull PS claim) { super(claim); } /** * Method to obtain the Chunk related to the Claim. * * @return {@link Chunk} represented by the 'Claim'. */ @NotNull @Override public Chunk getChunk() { return claim.asBukkitChunk(); } /** * Method to get the X of the Chunk. * * @return x coordinate. */ @Override public int getX() { return claim.getChunkX(); } /** * Method to get the Z of the Chunk. * * @return z coordinate. */ @Override public int getZ() { return claim.getChunkZ(); } /** * Method to get the Faction linked to the Chunk. * * @return IFaction linked to the IClaim. */ @Override public Faction getFaction() { return new MassiveCoreFactionsFaction(BoardColl.get().getFactionAt(claim)); } /** * Method to determine if the Claim has a Faction related to it. * <p> * If the claim is owned by 'Wilderness' or the equivalent Faction, this method will return {@code false}. * </p> * * @return {@code true} if a Faction owns this land (not Wilderness) * @see Faction#isWilderness() */ @Override public boolean isClaimed() { return BoardColl.get().getFactionAt(claim) != null; } }
3dhater/Racer
src/libs/qlib/qdxsound.cpp
/* * QDXSound - DirectX sound abstraction * 25-09-00: Created! (Win32) * FUTURE: * - Select/enumerate audio devices * NOTES: * - Stubbed on anything !Win32 (to fail) * (C) MarketGraph/<NAME> */ #include <qlib/dxsound.h> #include <qlib/app.h> #include <qlib/debug.h> // SDL support for Linux sound (for example) #ifdef Q_USE_SDL #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #endif DEBUG_ENABLE QDXSound *qDXSound; QDXSound::QDXSound() { // There can be only one if(qDXSound) { qerr("QDXSound: multiple objects created"); delete qDXSound; } qDXSound=this; #ifdef WIN32 ds=0; listener=0; #endif // Defaults frequency=22050; channels=2; bits=16; #ifdef Q_USE_SDL // No 3D support in SDL (?) flags=0; #else flags=USE3D; #endif } QDXSound::~QDXSound() { if(IsOpen()) Close(); } bool QDXSound::Open() // Returns TRUE if DirectSound could be opened with the given settings { #ifdef WIN32 HRESULT hr; LPDIRECTSOUNDBUFFER sbPrimary; // Initialize COM if(hr=CoInitialize(NULL)) { qerr("QDXSound:Open(); can't initialize COM (%s)",Error2Str(hr)); return FALSE; } // Use default device if(FAILED(hr=DirectSoundCreate(NULL,&ds,NULL))) { qerr("QDXSound:Open(); Can't create DirectSound (%s)",Error2Str(hr)); return FALSE; } // Set cooperative level if(FAILED(hr=ds->SetCooperativeLevel(QSHELL->GetQXWindow()->GetHWND(),DSSCL_PRIORITY))) { qerr("QDXSound:Open(); can't set DSSCL_PRIORITY cooperative level, hr=0x%x",hr); return FALSE; } // Obtain primary buffer DSBUFFERDESC dbd; ZeroMemory(&dbd,sizeof(dbd)); dbd.dwSize=sizeof(DSBUFFERDESC); dbd.dwFlags=DSBCAPS_PRIMARYBUFFER; if(flags&USE3D) { //qlog(QLOG_INFO,"3D primary buffer"); dbd.dwFlags|=DSBCAPS_CTRL3D; } if(FAILED(hr=ds->CreateSoundBuffer(&dbd,&sbPrimary,NULL))) { qerr("QDXSound:Open(); Can't create primary sound buffer (%s)",Error2Str(hr)); return FALSE; } // Get 3D listener if(FAILED(hr=sbPrimary->QueryInterface(IID_IDirectSound3DListener,(void**)&listener))) { qerr("QDXSound:Open(); Can't query interface for 3D listener, hr=0x%x",hr); return FALSE; } // Get listener params listenerParams.dwSize=sizeof(DS3DLISTENER); listener->GetAllParameters(&listenerParams); // Set primary buffer format (frequency, bits etc) WAVEFORMATEX wfx; ZeroMemory(&wfx,sizeof(wfx)); wfx.wFormatTag=WAVE_FORMAT_PCM; wfx.nChannels=channels; wfx.nSamplesPerSec=frequency; wfx.wBitsPerSample=bits; wfx.nBlockAlign=wfx.wBitsPerSample/8*wfx.nChannels; wfx.nAvgBytesPerSec=wfx.nSamplesPerSec*wfx.nBlockAlign; if(FAILED(hr=sbPrimary->SetFormat(&wfx))) { qerr("QDXSound:Open(); Can't set format of primary sound buffer, hr=0x%x",hr); return FALSE; } // Release primary buffer (not needed anymore, it seems) if(sbPrimary) { sbPrimary->Release(); sbPrimary=0; } // Phew, we've come through! return TRUE; #else // Other OS'es return FALSE; #endif } void QDXSound::Close() { #ifdef WIN32 qlog(QLOG_INFO,"QDXSound:Close(); closing DirectSound/COM\n"); if(listener)listener->Release(); if(ds)ds->Release(); // Uninit COM CoUninitialize(); #endif } bool QDXSound::IsOpen() { #ifdef WIN32 if(ds)return TRUE; #endif return FALSE; } /**************** * ERROR STRINGS * ****************/ cstring QDXSound::Error2Str(int hr) { static char buf[40]; #ifdef WIN32 switch(hr) { case DSERR_ACCESSDENIED: return "DSERR_ACCESSDENIED"; case DSERR_ALLOCATED: return "DSERR_ALLOCATED"; case DSERR_ALREADYINITIALIZED: return "DSERR_ALREADYINITIALIZED"; case DSERR_BADFORMAT: return "DSERR_BADFORMAT"; case DSERR_BUFFERLOST: return "DSERR_BUFFERLOST"; case DSERR_CONTROLUNAVAIL: return "DSERR_CONTROLUNAVAIL"; case DSERR_GENERIC: return "DSERR_GENERIC"; // Newer .h files? //case DSERR_HWUNAVAIL: return "DSERR_HWUNAVAIL"; case DSERR_INVALIDCALL: return "DSERR_INVALIDCALL"; case DSERR_INVALIDPARAM: return "DSERR_INVALIDPARAM"; case DSERR_NOAGGREGATION: return "DSERR_NOAGGREGATION"; case DSERR_NODRIVER: return "DSERR_NODRIVER"; case DSERR_NOINTERFACE: return "DSERR_NOINTERFACE"; case DSERR_OTHERAPPHASPRIO: return "DSERR_OTHERAPPHASPRIO"; case DSERR_OUTOFMEMORY: return "DSERR_OUTOFMEMORY"; case DSERR_PRIOLEVELNEEDED: return "DSERR_PRIOLEVELNEEDED"; case DSERR_UNINITIALIZED: return "DSERR_UNINITIALIZED"; case DSERR_UNSUPPORTED: return "DSERR_UNSUPPORTED"; default: sprintf(buf,"DSERR 0x%x",hr); return buf; } #else // Non-Win32 return "DSERR not supported on this OS"; #endif }
LiUSemWeb/HeFQUIN
src/main/java/se/liu/ida/hefquin/engine/datastructures/impl/cache/CacheEntryFactory.java
package se.liu.ida.hefquin.engine.datastructures.impl.cache; /** * Creates EntryType objects that wrap ObjectType objects. */ public interface CacheEntryFactory<EntryType extends CacheEntry<ObjectType>, ObjectType> { /** * Creates and returns a new EntryType object that wraps the given object. */ EntryType createCacheEntry(ObjectType obj); }
DigitalCoin1/L2SPERO
gameserver/head-src/com/l2jfrozen/gameserver/thread/LoginServerThread.java
<reponame>DigitalCoin1/L2SPERO<gh_stars>0 /* * L2jFrozen Project - www.l2jfrozen.com * * 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, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package com.l2jfrozen.gameserver.thread; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.Socket; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAKeyGenParameterSpec; import java.security.spec.RSAPublicKeySpec; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.l2jfrozen.Config; import com.l2jfrozen.crypt.NewCrypt; import com.l2jfrozen.gameserver.GameServer; import com.l2jfrozen.gameserver.controllers.GameTimeController; import com.l2jfrozen.gameserver.model.L2World; import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance; import com.l2jfrozen.gameserver.network.L2GameClient; import com.l2jfrozen.gameserver.network.L2GameClient.GameClientState; import com.l2jfrozen.gameserver.network.gameserverpackets.AuthRequest; import com.l2jfrozen.gameserver.network.gameserverpackets.BlowFishKey; import com.l2jfrozen.gameserver.network.gameserverpackets.ChangeAccessLevel; import com.l2jfrozen.gameserver.network.gameserverpackets.GameServerBasePacket; import com.l2jfrozen.gameserver.network.gameserverpackets.PlayerAuthRequest; import com.l2jfrozen.gameserver.network.gameserverpackets.PlayerInGame; import com.l2jfrozen.gameserver.network.gameserverpackets.PlayerLogout; import com.l2jfrozen.gameserver.network.gameserverpackets.ServerStatus; import com.l2jfrozen.gameserver.network.loginserverpackets.AuthResponse; import com.l2jfrozen.gameserver.network.loginserverpackets.InitLS; import com.l2jfrozen.gameserver.network.loginserverpackets.KickPlayer; import com.l2jfrozen.gameserver.network.loginserverpackets.LoginServerFail; import com.l2jfrozen.gameserver.network.loginserverpackets.PlayerAuthResponse; import com.l2jfrozen.gameserver.network.serverpackets.AuthLoginFail; import com.l2jfrozen.gameserver.network.serverpackets.CharSelectInfo; import com.l2jfrozen.util.Util; import com.l2jfrozen.util.random.Rnd; import javolution.util.FastList; import javolution.util.FastMap; public class LoginServerThread extends Thread { protected static final Logger LOGGER = Logger.getLogger(LoginServerThread.class); /** The LoginServerThread singleton */ private static LoginServerThread _instance; private static final int REVISION = 0x0102; private RSAPublicKey _publicKey; private final String _hostname; private final int _port; private final int _gamePort; private Socket _loginSocket; private InputStream _in; private OutputStream _out; /** * The BlowFish engine used to encrypt packets<br> * It is first initialized with a unified key:<br> * "_;v.]05-31!|+-%xT!^[$\00"<br> * <br> * and then after handshake, with a new key sent by<br> * loginserver during the handshake. This new key is stored<br> * in {@link #_blowfishKey} */ private NewCrypt _blowfish; private byte[] _blowfishKey; private byte[] _hexID; private final boolean _acceptAlternate; private int _requestID; private int _serverID; private final boolean _reserveHost; private int _maxPlayer; private final List<WaitingClient> _waitingClients; private final Map<String, L2GameClient> _accountsInGameServer; private int _status; private String _serverName; private final String _gameExternalHost; private final String _gameInternalHost; public LoginServerThread() { super("LoginServerThread"); _port = Config.GAME_SERVER_LOGIN_PORT; _gamePort = Config.PORT_GAME; _hostname = Config.GAME_SERVER_LOGIN_HOST; _hexID = Config.HEX_ID; if (_hexID == null) { _requestID = Config.REQUEST_ID; _hexID = generateHex(16); } else { _requestID = Config.SERVER_ID; } _acceptAlternate = Config.ACCEPT_ALTERNATE_ID; _reserveHost = Config.RESERVE_HOST_ON_LOGIN; _gameExternalHost = Config.EXTERNAL_HOSTNAME; _gameInternalHost = Config.INTERNAL_HOSTNAME; _waitingClients = new FastList<>(); _accountsInGameServer = new FastMap<String, L2GameClient>().shared(); _maxPlayer = Config.MAXIMUM_ONLINE_USERS; } public static LoginServerThread getInstance() { if (_instance == null) { _instance = new LoginServerThread(); } return _instance; } @Override public void run() { while (!_interrupted) { int lengthHi = 0; int lengthLo = 0; int length = 0; boolean checksumOk = false; try { // Connection LOGGER.info("Connecting to login on " + _hostname + ":" + _port); _loginSocket = new Socket(_hostname, _port); _in = _loginSocket.getInputStream(); if (_out != null) synchronized (_out) // avoids tow threads writing in the mean time { _out = new BufferedOutputStream(_loginSocket.getOutputStream()); } else _out = new BufferedOutputStream(_loginSocket.getOutputStream()); // init Blowfish _blowfishKey = generateHex(40); _blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00"); while (!_interrupted) { lengthLo = _in.read(); lengthHi = _in.read(); length = lengthHi * 256 + lengthLo; if (lengthHi < 0) { LOGGER.info("LoginServerThread: Login terminated the connection."); break; } final byte[] incoming = new byte[length]; incoming[0] = (byte) lengthLo; incoming[1] = (byte) lengthHi; int receivedBytes = 0; int newBytes = 0; while (newBytes != -1 && receivedBytes < length - 2) { newBytes = _in.read(incoming, 2, length - 2); receivedBytes = receivedBytes + newBytes; } if (receivedBytes != length - 2) { LOGGER.warn("Incomplete Packet is sent to the server, closing connection.(LS)"); break; } byte[] decrypt = new byte[length - 2]; System.arraycopy(incoming, 2, decrypt, 0, decrypt.length); // decrypt if we have a key decrypt = _blowfish.decrypt(decrypt); checksumOk = NewCrypt.verifyChecksum(decrypt); if (!checksumOk) { LOGGER.warn("Incorrect packet checksum, ignoring packet (LS)"); break; } if (Config.DEBUG) { LOGGER.warn("[C]\n" + Util.printData(decrypt)); } final int packetType = decrypt[0] & 0xff; switch (packetType) { case 00: final InitLS init = new InitLS(decrypt); if (Config.DEBUG) { LOGGER.info("Init received"); } if (init.getRevision() != REVISION) { // TODO: revision mismatch LOGGER.warn("/!\\ Revision mismatch between LS and GS /!\\"); break; } try { final KeyFactory kfac = KeyFactory.getInstance("RSA"); final BigInteger modulus = new BigInteger(init.getRSAKey()); final RSAPublicKeySpec kspec1 = new RSAPublicKeySpec(modulus, RSAKeyGenParameterSpec.F4); _publicKey = (RSAPublicKey) kfac.generatePublic(kspec1); if (Config.DEBUG) { LOGGER.info("RSA key set up"); } } catch (final GeneralSecurityException e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); LOGGER.warn("Troubles while init the public key send by login"); break; } // send the blowfish key through the rsa encryption final BlowFishKey bfk = new BlowFishKey(_blowfishKey, _publicKey); sendPacket(bfk); if (Config.DEBUG) { LOGGER.info("Sent new blowfish key"); } // now, only accept paket with the new encryption _blowfish = new NewCrypt(_blowfishKey); if (Config.DEBUG) { LOGGER.info("Changed blowfish key"); } final AuthRequest ar = new AuthRequest(_requestID, _acceptAlternate, _hexID, _gameExternalHost, _gameInternalHost, _gamePort, _reserveHost, _maxPlayer); sendPacket(ar); if (Config.DEBUG) { LOGGER.info("Sent AuthRequest to login"); } break; case 01: final LoginServerFail lsf = new LoginServerFail(decrypt); LOGGER.info("Damn! Registeration Failed: " + lsf.getReasonString()); // login will close the connection here break; case 02: final AuthResponse aresp = new AuthResponse(decrypt); _serverID = aresp.getServerId(); _serverName = aresp.getServerName(); Config.saveHexid(_serverID, hexToString(_hexID)); LOGGER.info("Registered on login as Server " + _serverID + " : " + _serverName); final ServerStatus st = new ServerStatus(); if (Config.SERVER_LIST_BRACKET) { st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET, ServerStatus.ON); } else { st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET, ServerStatus.OFF); } if (Config.SERVER_LIST_CLOCK) { st.addAttribute(ServerStatus.SERVER_LIST_CLOCK, ServerStatus.ON); } else { st.addAttribute(ServerStatus.SERVER_LIST_CLOCK, ServerStatus.OFF); } if (Config.SERVER_LIST_TESTSERVER) { st.addAttribute(ServerStatus.TEST_SERVER, ServerStatus.ON); } else { st.addAttribute(ServerStatus.TEST_SERVER, ServerStatus.OFF); } if (Config.SERVER_GMONLY) { st.addAttribute(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_GM_ONLY); } else { st.addAttribute(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_AUTO); } sendPacket(st); if (L2World.getAllPlayersCount() > 0) { final FastList<String> playerList = new FastList<>(); for (final L2PcInstance player : L2World.getInstance().getAllPlayers()) { playerList.add(player.getAccountName()); } final PlayerInGame pig = new PlayerInGame(playerList); sendPacket(pig); } break; case 03: final PlayerAuthResponse par = new PlayerAuthResponse(decrypt); final String account = par.getAccount(); WaitingClient wcToRemove = null; synchronized (_waitingClients) { for (final WaitingClient wc : _waitingClients) { if (wc.account.equals(account)) { wcToRemove = wc; } } } if (wcToRemove != null) { if (par.isAuthed()) { if (Config.DEBUG) { LOGGER.info("Login accepted player " + wcToRemove.account + " waited(" + (GameTimeController.getGameTicks() - wcToRemove.timestamp) + "ms)"); } PlayerInGame pig = new PlayerInGame(par.getAccount()); sendPacket(pig); pig = null; wcToRemove.gameClient.setState(GameClientState.AUTHED); wcToRemove.gameClient.setSessionId(wcToRemove.session); // before the char selection, check shutdown status if (GameServer.getSelectorThread().isShutdown()) { wcToRemove.gameClient.getConnection().sendPacket(new AuthLoginFail(1)); wcToRemove.gameClient.closeNow(); } else { CharSelectInfo cl = new CharSelectInfo(wcToRemove.account, wcToRemove.gameClient.getSessionId().playOkID1); wcToRemove.gameClient.getConnection().sendPacket(cl); wcToRemove.gameClient.setCharSelection(cl.getCharInfo()); cl = null; } } else { LOGGER.warn("Session key is not correct. Closing connection for account " + wcToRemove.account + "."); wcToRemove.gameClient.getConnection().sendPacket(new AuthLoginFail(1)); wcToRemove.gameClient.closeNow(); } _waitingClients.remove(wcToRemove); } break; case 04: KickPlayer kp = new KickPlayer(decrypt); doKickPlayer(kp.getAccount()); kp = null; break; } } } catch (final UnknownHostException e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); LOGGER.info("Deconnected from Login, Trying to reconnect:"); LOGGER.info(e.toString()); } catch (final IOException e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); LOGGER.info("Deconnected from Login, Trying to reconnect.."); // LOGGER.info(e.toString()); } finally { if (_out != null) synchronized (_out) // avoids tow threads writing in the mean time { try { _loginSocket.close(); } catch (final Exception e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); } } else try { _loginSocket.close(); } catch (final Exception e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); } } try { Thread.sleep(5000); // 5 seconds } catch (final InterruptedException e) { // no need exception LOGGER } } } public void addWaitingClientAndSendRequest(final String acc, final L2GameClient client, final SessionKey key) { if (Config.DEBUG) { LOGGER.info(key); } final WaitingClient wc = new WaitingClient(acc, client, key); synchronized (_waitingClients) { _waitingClients.add(wc); } PlayerAuthRequest par = new PlayerAuthRequest(acc, key); try { sendPacket(par); } catch (final IOException e) { LOGGER.warn("Error while sending player auth request"); if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); } par = null; } public void removeWaitingClient(final L2GameClient client) { WaitingClient toRemove = null; synchronized (_waitingClients) { for (final WaitingClient c : _waitingClients) { if (c.gameClient == client) { toRemove = c; } } if (toRemove != null) { _waitingClients.remove(toRemove); } } toRemove = null; } public void sendLogout(final String account) { if (account == null) return; PlayerLogout pl = new PlayerLogout(account); try { sendPacket(pl); } catch (final IOException e) { LOGGER.warn("Error while sending logout packet to login"); e.printStackTrace(); } pl = null; } /* * public void addGameServerLogin(String account, L2GameClient client) { _accountsInGameServer.put(account, client); } */ public boolean addGameServerLogin(final String account, final L2GameClient client) { final L2GameClient savedClient = _accountsInGameServer.get(account); if (savedClient != null) { if (savedClient.isDetached()) { if (Config.DEBUG) LOGGER.info("Old Client was disconnected: Offline or OfflineMode --> Login Again"); _accountsInGameServer.put(account, client); return true; } if (Config.DEBUG) LOGGER.info("Old Client was online --> Close Old Client Connection"); savedClient.closeNow(); _accountsInGameServer.remove(account); return false; } if (Config.DEBUG) LOGGER.info("Client was not online --> New Client Connection"); _accountsInGameServer.put(account, client); return true; } public void sendAccessLevel(final String account, final int level) { ChangeAccessLevel cal = new ChangeAccessLevel(account, level); try { sendPacket(cal); } catch (final IOException e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); } cal = null; } private String hexToString(final byte[] hex) { return new BigInteger(hex).toString(16); } public void doKickPlayer(final String account) { if (_accountsInGameServer.get(account) != null) { _accountsInGameServer.get(account).closeNow(); LoginServerThread.getInstance().sendLogout(account); if (Config.DEBUG) LOGGER.debug("called [doKickPlayer], closing connection"); } } public static byte[] generateHex(final int size) { final byte[] array = new byte[size]; Rnd.nextBytes(array); if (Config.DEBUG) { LOGGER.debug("Generated random String: \"" + array + "\""); } return array; } /** * @param sl * @throws IOException */ private void sendPacket(final GameServerBasePacket sl) throws IOException { if (_interrupted) { return; } byte[] data = sl.getContent(); NewCrypt.appendChecksum(data); if (Config.DEBUG) { LOGGER.debug("[S]\n" + Util.printData(data)); } data = _blowfish.crypt(data); final int len = data.length + 2; if (_out != null && !_loginSocket.isClosed() && _loginSocket.isConnected()) synchronized (_out) // avoids tow threads writing in the mean time { _out.write(len & 0xff); _out.write(len >> 8 & 0xff); _out.write(data); _out.flush(); } } /** * @param maxPlayer The maxPlayer to set. */ public void setMaxPlayer(final int maxPlayer) { sendServerStatus(ServerStatus.MAX_PLAYERS, maxPlayer); _maxPlayer = maxPlayer; } /** * @return Returns the maxPlayer. */ public int getMaxPlayer() { return _maxPlayer; } /** * @param id * @param value */ public void sendServerStatus(final int id, final int value) { ServerStatus ss = new ServerStatus(); ss.addAttribute(id, value); try { sendPacket(ss); } catch (final IOException e) { if (Config.ENABLE_ALL_EXCEPTIONS) e.printStackTrace(); } ss = null; } /** * @return */ public String getStatusString() { return ServerStatus.STATUS_STRING[_status]; } /** * @return */ public boolean isClockShown() { return Config.SERVER_LIST_CLOCK; } /** * @return */ public boolean isBracketShown() { return Config.SERVER_LIST_BRACKET; } /** * @return Returns the serverName. */ public String getServerName() { return _serverName; } public void setServerStatus(final int status) { switch (status) { case ServerStatus.STATUS_AUTO: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_AUTO); _status = status; break; case ServerStatus.STATUS_DOWN: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_DOWN); _status = status; break; case ServerStatus.STATUS_FULL: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_FULL); _status = status; break; case ServerStatus.STATUS_GM_ONLY: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_GM_ONLY); _status = status; break; case ServerStatus.STATUS_GOOD: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_GOOD); _status = status; break; case ServerStatus.STATUS_NORMAL: sendServerStatus(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_NORMAL); _status = status; break; default: throw new IllegalArgumentException("Status does not exists:" + status); } } public static class SessionKey { public int playOkID1; public int playOkID2; public int loginOkID1; public int loginOkID2; public int clientKey = -1; // by Azagthtot public SessionKey(final int loginOK1, final int loginOK2, final int playOK1, final int playOK2) { playOkID1 = playOK1; playOkID2 = playOK2; loginOkID1 = loginOK1; loginOkID2 = loginOK2; } @Override public String toString() { return "PlayOk: " + playOkID1 + " " + playOkID2 + " LoginOk:" + loginOkID1 + " " + loginOkID2; } } private class WaitingClient { public int timestamp; public String account; public L2GameClient gameClient; public SessionKey session; public WaitingClient(final String acc, final L2GameClient client, final SessionKey key) { account = acc; timestamp = GameTimeController.getGameTicks(); gameClient = client; session = key; } } private boolean _interrupted = false; @Override public void interrupt() { _interrupted = true; super.interrupt(); } @Override public boolean isInterrupted() { return _interrupted; } }
wraydev/rltos
docs/doxy/generated/html/group___rltos__queue__api.js
<reponame>wraydev/rltos var group___rltos__queue__api = [ [ "Queue Private", "group___rltos__queue__prv.html", "group___rltos__queue__prv" ] ];
FunTimeCoding/python-utility
python_utility/git_observer.py
# TODO: Fetch master branch of a repository repeatedly and detect merges # into master. # TODO: Detect tag creation. # TODO: Detect feature branch creation. # http://gitpython.readthedocs.io/en/stable/tutorial.html#meet-the-repo-type
reels-research/iOS-Private-Frameworks
PassKitCore.framework/PKPaymentSetupFieldPicker.h
<reponame>reels-research/iOS-Private-Frameworks /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/PassKitCore.framework/PassKitCore */ @interface PKPaymentSetupFieldPicker : PKPaymentSetupField { NSArray * _pickerItems; } @property (nonatomic, copy) PKPaymentSetupFieldPickerItem *currentValue; @property (nonatomic, copy) NSArray *pickerItems; - (void).cxx_destruct; - (void)_commonUpdate; - (id)_submissionStringForValue:(id)arg1; - (id)currentValue; - (id)displayString; - (unsigned long long)fieldType; - (id)pickerItems; - (void)setCurrentValue:(id)arg1; - (void)setPickerItems:(id)arg1; - (bool)submissionStringMeetsAllRequirements; - (void)updateWithAttribute:(id)arg1; - (void)updateWithConfiguration:(id)arg1; @end
RodneyFernandes17/fontedward
IGRP-Template/src/main/java/nosi/webapps/sistema_de_avaliacao_igrpweb/pages/lista_avaliacao_semanal/Lista_avaliacao_semanalController.java
package nosi.webapps.sistema_de_avaliacao_igrpweb.pages.lista_avaliacao_semanal; import nosi.core.webapp.Controller;// import nosi.core.webapp.databse.helpers.ResultSet;// import nosi.core.webapp.databse.helpers.QueryInterface;// import java.io.IOException;// import nosi.core.webapp.Core;// import nosi.core.webapp.Response;// /* Start-Code-Block (import) */ import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.AvaliadoTbl; //block import /* End-Code-Block */ /*----#start-code(packages_import)----*/ import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.AvaliadoTbl; import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.SemanalTbl; import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.TemaTbl; import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.TesteTbl; import nosi.core.webapp.Report; import java.util.ArrayList; import java.util.List; import java.time.LocalDate; import java.util.Map; /*----#end-code----*/ public class Lista_avaliacao_semanalController extends Controller { public Response actionIndex() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); Lista_avaliacao_semanalView view = new Lista_avaliacao_semanalView(); view.id_teste.setParam(true); view.id_avaliado.setParam(true); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. model.loadTable_1(Core.query(null,"SELECT '../images/IGRP/IGRP2.3/assets/img/jon_doe.jpg' as foto,'Labore officia unde mollit vol' as nome,'Sit magna doloremque stract ut' as edicao,'Natus laudantium sed sit rem' as area,'Omnis iste mollit dolor omnis' as mentor,'hidden-e2e6_48c0' as id_teste,'hidden-2b7b_e626' as id_avaliado,'hidden-ec12_99bb' as id_utilizador ")); ----#gen-example */ /*----#start-code(index)----*/ try { AvaliadoTbl testetblfilter = new AvaliadoTbl().find(); List<AvaliadoTbl> testetblList = testetblfilter.orderByAsc("nome").all(); List<Lista_avaliacao_semanal.Table_1> testetblTable = new ArrayList<>(); if (testetblList != null) { for (AvaliadoTbl avaliado : testetblList) { Lista_avaliacao_semanal.Table_1 row = new Lista_avaliacao_semanal.Table_1(); row.setId_avaliado(avaliado.getIdAvaliado() + ""); row.setFoto(avaliado.getIdFoto() != null ? Core.getLinkFileByUuid(avaliado.getIdFoto()) : null); row.setNome(avaliado.getNome()); row.setArea(avaliado.getIdMentorFk() != null ? avaliado.getIdMentorFk().getIdAreaFk().getAreaDesc() : null); row.setMentor(avaliado.getIdMentorFk() != null ? avaliado.getIdMentorFk().getNome() : null); row.setEdicao(Core.findDomainDescByKey("edicao", avaliado.getEdicao() != null ? avaliado.getEdicao() : null)); SemanalTbl data = new SemanalTbl().find() .andWhere("idAvaliador", "=", Core.getCurrentUser().getId()) .andWhere("idAvaliadoFk", "=", avaliado.getIdAvaliado()) .andWhere("idTemaFk.nrSemana.atual", "=", true).one(); if (Core.isNotNull(data)) { row.hiddenButton(view.btn_avaliacao_semanal); } TemaTbl tema = new TemaTbl().find().andWhere("idAvaliadoFk", "=", avaliado.getIdAvaliado()) .andWhere("nrSemana.atual", "=", true).one(); if (Core.isNotNull(tema)) { row.hiddenButton(view.btn_inserir_tema); } if (Core.isNull(tema)) { row.hiddenButton(view.btn_avaliacao_semanal); } if (!avaliado.getIdUtilizador().equals(Core.getCurrentUser().getId()) && Core.getCurrentProfileCode().equals("avaliado.sistema_de_avaliacao_igrpweb")) { row.hiddenButton(view.btn_avaliacao_semanal); row.hiddenButton(view.btn_historico_de_avaliacoes); row.hiddenButton(view.btn_inserir_tema); } testetblTable.add(row); } } model.setTable_1(testetblTable); } catch (Exception e) { e.printStackTrace(); } /*----#end-code----*/ view.setModel(model); return this.renderView(view); } public Response actionVer() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. this.addQueryString("p_id","12"); //to send a query string in the URL this.addQueryString("p_id_teste",Core.getParam("p_id_teste")); this.addQueryString("p_id_avaliado",Core.getParam("p_id_avaliado")); return this.forward("sistema_de_avaliacao_igrpweb","Formulario_de_inscricao","index",this.queryString()); //if submit, loads the values Use model.validate() to validate your model ----#gen-example */ /*----#start-code(ver)----*/ this.addQueryString("isEdit", "true"); this.addQueryString("p_id_avaliado", Core.getParam("p_id_avaliado")); /*----#end-code----*/ return this.redirect("sistema_de_avaliacao_igrpweb","Formulario_de_inscricao","index", this.queryString()); } public Response actionAvaliacao_semanal() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. this.addQueryString("p_id","12"); //to send a query string in the URL this.addQueryString("p_id_teste",Core.getParam("p_id_teste")); this.addQueryString("p_id_avaliado",Core.getParam("p_id_avaliado")); return this.forward("sistema_de_avaliacao_igrpweb","Formulario_avaliacao_semanal","index",this.queryString()); //if submit, loads the values Use model.validate() to validate your model ----#gen-example */ /*----#start-code(avaliacao_semanal)----*/ this.addQueryString("p_id_avaliado", Core.getParam("p_id_avaliado")); /*----#end-code----*/ return this.redirect("sistema_de_avaliacao_igrpweb","Formulario_avaliacao_semanal","index", this.queryString()); } public Response actionInserir_tema() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. this.addQueryString("p_id","12"); //to send a query string in the URL this.addQueryString("p_id_teste",Core.getParam("p_id_teste")); this.addQueryString("p_id_avaliado",Core.getParam("p_id_avaliado")); return this.forward("sistema_de_avaliacao_igrpweb","Tema_semanal","index",this.queryString()); //if submit, loads the values Use model.validate() to validate your model ----#gen-example */ /*----#start-code(inserir_tema)----*/ this.addQueryString("p_id_avaliado", Core.getParam("p_id_avaliado")); /*----#end-code----*/ return this.redirect("sistema_de_avaliacao_igrpweb","Tema_semanal","index", this.queryString()); } public Response actionHistorico_de_avaliacoes() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. this.addQueryString("p_id","12"); //to send a query string in the URL this.addQueryString("p_id_teste",Core.getParam("p_id_teste")); this.addQueryString("p_id_avaliado",Core.getParam("p_id_avaliado")); return this.forward("sistema_de_avaliacao_igrpweb","Historico_de_avaliacao","index",this.queryString()); //if submit, loads the values Use model.validate() to validate your model ----#gen-example */ /*----#start-code(historico_de_avaliacoes)----*/ this.addQueryString("p_id_avaliado", Core.getParam("p_id_avaliado")); /*----#end-code----*/ return this.redirect("sistema_de_avaliacao_igrpweb","Historico_de_avaliacao","index", this.queryString()); } public Response actionEliminar() throws IOException, IllegalArgumentException, IllegalAccessException{ Lista_avaliacao_semanal model = new Lista_avaliacao_semanal(); model.load(); /*----#gen-example EXAMPLES COPY/PASTE: INFO: Core.query(null,... change 'null' to your db connection name, added in Application Builder. this.addQueryString("p_id","12"); //to send a query string in the URL this.addQueryString("p_id_teste",Core.getParam("p_id_teste")); this.addQueryString("p_id_avaliado",Core.getParam("p_id_avaliado")); return this.forward("sistema_de_avaliacao_igrpweb","Formulario_de_inscricao","index",this.queryString()); //if submit, loads the values Use model.validate() to validate your model ----#gen-example */ /*----#start-code(eliminar)----*/ AvaliadoTbl avaliadotbl = new AvaliadoTbl().findOne(Core.getParamInt("p_id_avaliado")); if (avaliadotbl != null && !avaliadotbl.hasError()) { boolean del = avaliadotbl.delete(avaliadotbl.getIdAvaliado()); if (del == true) Core.setMessageSuccess("Deleted from DB successfully!"); else Core.setMessageError("Error deleting person from DB!"); } else { Core.setMessageError(avaliadotbl.getError().toString()); } /*----#end-code----*/ return this.redirect("sistema_de_avaliacao_igrpweb","Formulario_de_inscricao","index", this.queryString()); } /*----#start-code(custom_actions)----*/ /*----#end-code----*/ }
Samyakk123/ThreatExchange
python-threatexchange/threatexchange/fetcher/fetch_state.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Base classes for passing data between SignalExchangeAPIs and other interfaces. Many implementations will choose to extend these to add additional metadata needed to power API features. """ from dataclasses import dataclass from enum import IntEnum from functools import reduce import typing as t from threatexchange.fetcher.collab_config import CollaborationConfigBase from threatexchange.signal_type.signal_base import SignalType Self = t.TypeVar("Self") @dataclass class FetchCheckpointBase: """ If you need to store checkpoint information, this is the place to do it """ def is_stale(self) -> bool: """ For some APIs, stored state may become invalid if stored too long. Return true if the old data should be deleted and fetched from scratch. """ return False # Default, assume checkpoints never expire def get_progress_timestamp(self) -> t.Optional[int]: """If the checkpoint can, give the time it corresponds to""" return None class SignalOpinionCategory(IntEnum): """ What the opinion on a signal is. Some APIs may not support all of these, but each of these should influence what action you might take as a result of matching, otherwise it might make more sense as a tag """ FALSE_POSITIVE = 0 # Signal generates false positives WORTH_INVESTIGATING = 1 # Indirect indicator TRUE_POSITIVE = 2 # Confirmed meets category @dataclass class SignalOpinion: """ The metadata of a single signal upload. Certain APIs won't have any concept of owner, category, or tags, in which case owner=0, category=TRUE_POSITIVE, tags=[] is reasonable default. Some implementations may extend this to store additional API-specific data @see threatexchange.fetch_api.SignalExchangeAPI """ owner: int category: SignalOpinionCategory tags: t.Set[str] @classmethod def get_trivial(cls): return cls(0, SignalOpinionCategory.WORTH_INVESTIGATING, []) class AggregateSignalOpinionCategory(IntEnum): """ Represent multiple opinions as one. Keep in Sync with SignalOpinionCategory """ FALSE_POSITIVE = 0 # Signal generates false positives WORTH_INVESTIGATING = 1 # Indirect indicator TRUE_POSITIVE = 2 # Confirmed meets category DISPUTED = 3 # Some positive, some negative @classmethod def from_opinion_categories( cls, opinion_categories: t.Iterable[SignalOpinionCategory] ) -> "AggregateSignalOpinionCategory": aggregate_opinion = None for category in opinion_categories: aggregate_opinion = cls.aggregate(aggregate_opinion, category) assert aggregate_opinion is not None return aggregate_opinion @classmethod def aggregate( cls, old: t.Optional["AggregateSignalOpinionCategory"], new: t.Union["AggregateSignalOpinionCategory", SignalOpinionCategory], ) -> "AggregateSignalOpinionCategory": """ Combine signal opinions into an aggregate opinion. In general, take the highest confidence/severity of true positives, unless you have both a true + false positive, in which case the result is disputed. """ new = AggregateSignalOpinionCategory(new) if old is None: return new lo = min(old, new) hi = max(old, new) if lo == hi: return hi return cls.DISPUTED if lo == cls.FALSE_POSITIVE else hi @dataclass class AggregateSignalOpinion: category: AggregateSignalOpinionCategory tags: t.Set[str] @classmethod def from_opinions(cls, opinions: t.List[SignalOpinion]) -> "AggregateSignalOpinion": assert opinions return cls( tags={t for o in opinions for t in o.tags}, category=AggregateSignalOpinionCategory.from_opinion_categories( o.category for o in opinions ), ) @dataclass class FetchedSignalMetadata: """ Metadata to make decisions on matches and power feedback on the fetch API. You likely need to extend this for your API to include enough context for SignalExchangeAPI.report_seen() and others. If your API supports multiple databases or collections, you likely will need to store that here. """ def get_as_opinions(self) -> t.List[SignalOpinion]: return [SignalOpinion.get_trivial()] @classmethod def merge_metadata(cls: t.Type[Self], _older: Self, newer: Self) -> Self: """ The merge strategy when tailing a stream of updates. Simple strategies might be: 1. Replace - newer records for the same signal complete replace old ones 2. Merge - new records are combined with old ones """ return newer # Default is replace def get_as_aggregate_opinion(self) -> AggregateSignalOpinion: return AggregateSignalOpinion.from_opinions(self.get_as_opinions()) def __str__(self) -> str: agg = self.get_as_aggregate_opinion() if not agg.tags: return agg.category.name return f"{agg.category.name} {','.join(agg.tags)}" class FetchDelta: """ Contains the result of a fetch. You'll need to extend this, but it only to be interpretable by your API's version of FetchedState """ def record_count(self) -> int: """Helper for --limit""" return 1 def next_checkpoint(self) -> FetchCheckpointBase: """A serializable checkpoint for fetch.""" raise NotImplementedError def has_more(self) -> bool: """ Returns true if the API has no more data at this time. """ raise NotImplementedError class FetchDeltaWithUpdateStream(FetchDelta): """ For most APIs, they can represented in a simple update stream. This allows naive implementations for storage. """ def get_as_update_dict( self, ) -> t.Mapping[t.Tuple[str, str], t.Optional[FetchedSignalMetadata]]: """ Returns the contents of the delta as (signal_type, signal_str) => record If the record is set to None, this indicates the record should be deleted if it exists. """ raise NotImplementedError # TODO t.Generic[TFetchDeltaBase, TFetchedSignalDataBase, FetchCheckpointBase] # to help keep track of the expected subclasses for an impl class FetchedStateStoreBase: """ An interface to previously fetched or persisted state. You will need to extend this for your API, but even worse, there might need to be multiple versions for a single API if it's being used by Hasher-Matcher-Actioner, since that might want to specialcase for AWS components. = A Note on Metadata ID = It's assumed that the storage will be split into a scheme that allows addressing individual IDs. Depending on the implementation, you may have to invent IDs during merge() which will also need to be persisted, since they need to be consistent between instanciation """ def get_checkpoint( self, collab: CollaborationConfigBase ) -> t.Optional[FetchCheckpointBase]: """ Returns the last checkpoint passed to merge() after a flush() """ raise NotImplementedError def merge(self, collab: CollaborationConfigBase, delta: FetchDelta) -> None: """ Merge a FetchDelta into the state. At the implementation's discretion, it may call flush() or the equivalent work. """ raise NotImplementedError def flush(self) -> None: """ Finish writing the results of previous merges to persistant state. This should also persist the checkpoint. """ raise NotImplementedError def clear(self, collab: CollaborationConfigBase) -> None: """ Delete all the stored state for this collaboration. """ raise NotImplementedError def get_for_signal_type( self, collabs: t.List[CollaborationConfigBase], signal_type: t.Type[SignalType] ) -> t.Dict[str, t.Dict[str, FetchedSignalMetadata]]: """ Get as a map of CollabConfigBase.name() => {signal: Metadata} This is meant for simple storage and indexing solutions, but at scale, you likely want to store as IDs rather than the full metadata. TODO: This currently implies that you are going to load the entire dataset into memory, which once we start getting huge amounts of data, might not make sense. """ raise NotImplementedError
aanchal-jain/Python_Practice_Beginner
18.convert_base_2-9.py
<reponame>aanchal-jain/Python_Practice_Beginner number1=int(input("Insert number to convert: ")) base_number=int(input("Choose the base to convert to from 2 to 9: ")) if not(2<=base_number<=9): quit() number2='' while number1>0: number2=str(number1%base_number)+number2 number1//=base_number print(number2)
fieldenms/
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/factory/DefaultCompanionObjectFinderImpl.java
package ua.com.fielden.platform.entity.factory; import static java.lang.String.format; import org.apache.log4j.Logger; import com.google.inject.Inject; import com.google.inject.Injector; import ua.com.fielden.platform.companion.ICanReadUninstrumented; import ua.com.fielden.platform.companion.IEntityReader; import ua.com.fielden.platform.dao.IEntityDao; import ua.com.fielden.platform.dao.exceptions.EntityCompanionException; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.CompanionObject; /** * Default implementation for {@link ICompanionObjectFinder}, which utilises injector for creating controller instances. * * @author <NAME> * */ public class DefaultCompanionObjectFinderImpl implements ICompanionObjectFinder { private static final Logger LOGGER = Logger.getLogger(DefaultCompanionObjectFinderImpl.class); private final Injector injector; @Inject public DefaultCompanionObjectFinderImpl(final Injector injector) { this.injector = injector; } @Override public <T extends IEntityDao<E>, E extends AbstractEntity<?>> T find(final Class<E> type) { return find(type, false); } @Override public <T extends IEntityReader<E>, E extends AbstractEntity<?>> T findAsReader(final Class<E> type, final boolean uninstrumented) { return find(type, uninstrumented); } @Override public <T extends IEntityDao<E>, E extends AbstractEntity<?>> T find(final Class<E> type, final boolean uninstrumented) { if (type.isAnnotationPresent(CompanionObject.class)) { try { final Class<T> coType = (Class<T>) type.getAnnotation(CompanionObject.class).value(); final T co = injector.getInstance(coType); return decideUninstrumentation(uninstrumented, coType, co); } catch (final EntityCompanionException e) { throw e; } catch (final Exception e) { LOGGER.warn(format("Could not locate companion for type [%s].", type.getName()), e); // if controller could not be instantiated for whatever reason it can be considered non-existent // thus, returning null return null; } } return null; } /** * A helper method to decide whether the instantiated companion should read instrumented or uninstrumented entities. * * @param uninstrumented * @param coType * @param co * @return */ private <T extends IEntityDao<E>, E extends AbstractEntity<?>> T decideUninstrumentation(final boolean uninstrumented, final Class<T> coType, final T co) { if (uninstrumented) { if (co instanceof ICanReadUninstrumented) { ((ICanReadUninstrumented) co).readUninstrumented(); } else { throw new EntityCompanionException(format("Cannot produce uninstrumented companion of type [%s].", coType.getName())); } } return co; } }
jhtwong/Open-Quark
src/CAL_Platform/src/org/openquark/cal/internal/machine/g/NVal.java
<gh_stars>1-10 /* * Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Business Objects nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * NVal.java * Created: Oct 23, 2002 at 5:51:52 PM * By: <NAME> */ package org.openquark.cal.internal.machine.g; import java.util.Collection; import org.openquark.cal.runtime.CALExecutorException; import org.openquark.cal.runtime.CalValue; /** * This is the NVal class/interface * * Base class for different value node types. * Creation: Oct 23, 2002 at 5:51:52 PM * @author <NAME> */ abstract class NVal extends Node { /** * Return the value this object wraps. */ @Override public abstract Object getValue (); /* * Functions to perform state transitions. */ /** * Do the Eval state transition. */ @Override protected void i_eval (Executor e) throws CALExecutorException { // Do nothing, a value is already in WHNF. } @Override protected void i_unwind (Executor e) throws CALExecutorException { e.popDumpItem(); } /** * Print */ @Override protected void i_print (Executor e) throws CALExecutorException { e.printVal = e.printVal + ": " + getValue().toString(); e.stack.pop (); } /** * Do a split state transition. */ @Override protected void i_split(Executor e, int n) throws CALExecutorException { //value objects are like 0-arity data constructor with respect to //case expression unpacking. For example, we can think of //data Int = 0 | 1 | -1 | 2 | -2 | 3 ... e.stack.pop(); } @Override public void addChildren (Collection<Node> c) { } /** * Build an application of deepSeq */ @Override protected Node buildDeepSeqInternal(Node rhs) { return rhs; } /** * {@inheritDoc} */ @Override public final int debug_getNChildren() { //value nodes have no children return 0; } /** * {@inheritDoc} */ @Override public final CalValue debug_getChild(int childN) { throw new IndexOutOfBoundsException(); } /** * {@inheritDoc} */ @Override public abstract String debug_getNodeStartText(); /** * {@inheritDoc} */ @Override public final String debug_getNodeEndText() { return ""; } /** * {@inheritDoc} */ @Override public final String debug_getChildPrefixText(int childN) { throw new IndexOutOfBoundsException(); } }
HiltonRoscoe/exchangerxml
src/com/cladonia/xngreditor/actions/SignDocumentAction.java
<reponame>HiltonRoscoe/exchangerxml<filename>src/com/cladonia/xngreditor/actions/SignDocumentAction.java<gh_stars>1-10 /* * $Id: SignDocumentAction.java,v 1.15 2004/10/11 08:38:30 edankert Exp $ * * Copyright (C) 2002, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ package com.cladonia.xngreditor.actions; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URL; import javax.swing.AbstractAction; import org.w3c.dom.Document; import org.xml.sax.SAXParseException; import com.cladonia.security.signature.KeyBuilder; import com.cladonia.security.signature.SignDocumentDialog; import com.cladonia.security.signature.SignatureGenerator; import com.cladonia.xml.ExchangerDocument; import com.cladonia.xml.ExchangerOutputFormat; import com.cladonia.xml.XMLUtilities; import com.cladonia.xngreditor.ExchangerEditor; import com.cladonia.xngreditor.FileUtilities; import com.cladonia.xngreditor.MessageHandler; import com.cladonia.xngreditor.URLUtilities; import com.cladonia.xngreditor.properties.ConfigurationProperties; import com.cladonia.xngreditor.properties.SecurityPreferences; /** * An action that can be used Sign a document. * * @version $Revision: 1.15 $, $Date: 2004/10/11 08:38:30 $ * @author Dogsbay */ public class SignDocumentAction extends AbstractAction { private static final boolean DEBUG = false; private ConfigurationProperties properties = null; private ExchangerEditor parent = null; private SignDocumentDialog dialog = null; /** * The constructor for the action which signs a xml document. * * @param parent the parent frame. */ public SignDocumentAction( ExchangerEditor parent, ConfigurationProperties properties) { super( "Sign Document ..."); this.parent = parent; this.properties = properties; putValue( MNEMONIC_KEY, new Integer( 'S')); putValue( SHORT_DESCRIPTION, "Sign a XML Document"); } /** * The implementation of the sign document action. * * @param the action event. */ public void actionPerformed( ActionEvent e) { if ( dialog == null) { dialog = new SignDocumentDialog( parent,properties); } // make sure the document is up to date ExchangerDocument document = parent.getDocument(); Object current = null; if ( document != null) { current = parent.getView().getCurrentView(); parent.getView().updateModel(); } // set the keystore SecurityPreferences prefs = properties.getSecurityPreferences(); try{ KeyBuilder.setParams( prefs.getKeystoreType(), prefs.getKeystoreFile(), prefs.getKeystorePassword(), prefs.getPrivatekeyAlias(), prefs.getPrivatekeyPassword(), prefs.getCertificateAlias()); } catch ( Exception x) { MessageHandler.showError( "Could not find a valid private key.\nPlease make sure the private key settings are correct.", "Key Store Error"); return; } dialog.show( document); if ( !dialog.isCancelled()) { try{ Document input = null; ExchangerDocument currentDocument = document; if ( dialog.isInputCurrentDocument()) { input = currentDocument.getW3CDocument(); //System.out.println( input.toString()); } else if ( dialog.isEnvelope()){ URL url = null; try { url = URLUtilities.toURL( dialog.getInputLocation()); currentDocument = new ExchangerDocument( url); currentDocument.load(); input = currentDocument.getW3CDocument(); } catch (Exception x) { MessageHandler.showError( "Could not create XML Document \""+url.toString()+"\".", "XML Document Error"); //x.printStackTrace(); return; } } SignatureGenerator generator = null; if ( dialog.isEnvelope()) { generator = new SignatureGenerator( KeyBuilder.getPrivateKey(), KeyBuilder.getCertificate(), input); } else { if ( currentDocument != null) { generator = new SignatureGenerator( KeyBuilder.getPrivateKey(), KeyBuilder.getCertificate(), currentDocument.getURL().toString()); } else { generator = new SignatureGenerator( KeyBuilder.getPrivateKey(), KeyBuilder.getCertificate(), dialog.getInputLocation()); } } generator.setC14nAlgorithm( dialog.getC14NMethod()); generator.setId( dialog.getID()); generator.setXpath( dialog.getXPath()); Document doc = generator.sign(properties); String encoding = "UTF-8"; if ( currentDocument != null) { encoding = currentDocument.getEncoding(); } String text = XMLUtilities.serialise( doc, encoding); URL url = null; String systemId = null; if ( document != null) { document.getURL(); } if ( url != null) { systemId = url.toString(); } ExchangerOutputFormat format = new ExchangerOutputFormat(); format.setEncoding( encoding); if ( currentDocument != null) { if ( currentDocument.hasDeclaration()) { if ( currentDocument.getStandalone() != ExchangerDocument.STANDALONE_NONE) { format.setStandalone( currentDocument.getStandalone()); format.setOmitStandalone( false); } format.setOmitEncoding( !currentDocument.hasEncoding()); format.setVersion( currentDocument.getVersion()); format.setSuppressDeclaration( false); } else { format.setSuppressDeclaration( true); } } text = format( text, systemId, encoding, format); if ( dialog.isOutputToSameDocument()) { if ( dialog.isInputCurrentDocument()) { parent.switchToEditor(); parent.getView().getEditor().setText( text); parent.getView().updateModel(); } else { currentDocument.setText( text); parent.open( currentDocument, null); } } else { ExchangerDocument newDocument = FileUtilities.createDocument(); newDocument.setText( text); parent.open( newDocument, null); } } catch ( Exception x) { MessageHandler.showError( "Could not create Signature.\n"+x.getMessage(), "Signature Error"); x.printStackTrace(); return; } } } private String format( String text, String systemId, String encoding, ExchangerOutputFormat format) throws IOException, SAXParseException { String indent = ""; boolean newLines = false; boolean padText = false; boolean preserveMixed = false; boolean trim = false; int lineLength = -1; return XMLUtilities.format( text, systemId, encoding, "", false, false, -1, false, false, format); } }
kusakina0608/NHN_MovieSwan_web
src/main/java/com/nhn/rookie8/movieswanticketapp/dto/ScheduleDTO.java
<reponame>kusakina0608/NHN_MovieSwan_web package com.nhn.rookie8.movieswanticketapp.dto; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDate; import java.time.LocalTime; import java.util.List; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ScheduleDTO { private List<Detail> detail; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate date; @Data @Builder @AllArgsConstructor @NoArgsConstructor public static class Detail { @JsonFormat(pattern = "HH:mm") private LocalTime time; private String timeTableId; } }
enrignagna/PervasiveHealthcare
src/test/scala/domainmodel/medicalrecords/initialanalysis/TestInitialAnalysis.scala
/* * Copyright (c) 2021. <NAME>, <NAME>, <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 domainmodel.medicalrecords.initialanalysis import domainmodel.Familiars.Familiars import domainmodel.Remotes.Remotes import domainmodel._ import org.junit.runner.RunWith import org.scalatest.freespec.AnyFreeSpec import org.scalatestplus.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class TestInitialAnalysis extends AnyFreeSpec { val remote: Remote = Remote("first anamnesis") val remotes: Remotes = Remotes().addNewRemote(remote) val familiar: Familiar = Familiar("<NAME>", KinshipDegree.FATHER, PreviousPathologies(), "3387514876") val familiars: Familiars = Familiars().addNewFamiliar(familiar) val anamnesis: Anamnesis = Anamnesis(familiars, remotes, Physiologic("self conscious")) val initialAnalysis: InitialAnalysis = InitialAnalysis( Some(anamnesis), PhysicalExamination( HospitalizationMotivation("Hearth attack"), SystemsInvestigation("Electrocardiogram") ), StateEvaluation( Psychological("All OK"), Nutritional("All OK"), Educational("All OK"), Social("All OK") ) ) "An initial analysis should have" - { /*"an anamnesis" in { assert(initialAnalysis.anamensis != null) assert(initialAnalysis.anamensis.isInstanceOf[Anamnesis]) }*/ "a physical exaimnation" in { assert(initialAnalysis.physicalExamination != null) assert(initialAnalysis.physicalExamination.isInstanceOf[PhysicalExamination]) } "a state evaluation" in { assert(initialAnalysis.stateEvaluation != null) assert(initialAnalysis.stateEvaluation.isInstanceOf[StateEvaluation]) } } }
ryo-rm/expo
ios/versioned/sdk45/EXUpdates/EXUpdates/Update/ABI45_0_0EXUpdatesBareUpdate.h
// Copyright © 2019 650 Industries. All rights reserved. #import <ABI45_0_0EXUpdates/ABI45_0_0EXUpdatesUpdate.h> #import <ABI45_0_0EXManifests/ABI45_0_0EXManifestsBareManifest.h> NS_ASSUME_NONNULL_BEGIN @interface ABI45_0_0EXUpdatesBareUpdate : NSObject + (ABI45_0_0EXUpdatesUpdate *)updateWithBareManifest:(ABI45_0_0EXManifestsBareManifest *)manifest config:(ABI45_0_0EXUpdatesConfig *)config database:(ABI45_0_0EXUpdatesDatabase *)database; @end NS_ASSUME_NONNULL_END
abhirocks1211/litho
litho-processor/src/main/java/com/facebook/litho/specmodels/model/PureRenderValidation.java
/* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho.specmodels.model; import com.facebook.litho.annotations.ShouldUpdate; import java.util.ArrayList; import java.util.List; public class PureRenderValidation { static <S extends SpecModel & HasPureRender> List<SpecModelValidationError> validate( S specModel) { List<SpecModelValidationError> validationErrors = new ArrayList<>(); final SpecMethodModel<DelegateMethod, Void> shouldUpdateMethod = SpecModelUtils.getMethodModelWithAnnotation(specModel, ShouldUpdate.class); if (shouldUpdateMethod != null) { if (!specModel.isPureRender()) { validationErrors.add( new SpecModelValidationError( shouldUpdateMethod.representedObject, "Specs defining a method annotated with @ShouldUpdate should also set " + "isPureRender = true in the top-level spec annotation.")); } } return validationErrors; } }
snoic-boom/AnyMock
manager/web/src/main/java/com/dxm/anymock/manager/web/controller/HttpInterfaceController.java
package com.dxm.anymock.manager.web.controller; import com.dxm.anymock.common.base.ResultCodeTranslator; import com.dxm.anymock.common.base.enums.ResultCode; import com.dxm.anymock.common.dal.model.HttpInterfaceBO; import com.dxm.anymock.manager.biz.model.request.*; import com.dxm.anymock.manager.biz.model.response.PagingDataResponse; import com.dxm.anymock.manager.biz.model.response.dto.ConflictJudgementDTO; import com.dxm.anymock.manager.biz.model.response.dto.HttpInterfaceDTO; import com.dxm.anymock.manager.biz.service.HttpInterfaceService; import com.dxm.anymock.manager.biz.model.response.BaseResponse; import com.dxm.anymock.manager.biz.model.response.DataResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static com.dxm.anymock.manager.web.WebConstants.URL_PREFIX_API_V2; @Controller @RequestMapping(URL_PREFIX_API_V2) public class HttpInterfaceController { @Autowired private HttpInterfaceService httpInterfaceService; @Autowired private ResultCodeTranslator translator; @PostMapping("/interface_http/conflictDetection") @ResponseBody public DataResponse<ConflictJudgementDTO> conflictDetection( @Validated @RequestBody HttpInterfaceConflictDetectionRequest request ) { return new DataResponse<>( translator.translate(ResultCode.SUCCESS), httpInterfaceService.conflictDetection(request)); } @PostMapping("/interface_http/selectById") @ResponseBody public DataResponse<HttpInterfaceDTO> queryById( @Validated @RequestBody IdRequest idRequest ) { return new DataResponse<>( translator.translate(ResultCode.SUCCESS), httpInterfaceService.queryById(idRequest.getId())); } @PostMapping("/interface_http/selectBySpaceId") @ResponseBody public PagingDataResponse<HttpInterfaceDTO> queryBySpaceId( @Validated @RequestBody CriteriaPagingRequest<SpaceIdRequest> request ) { return new PagingDataResponse<>( translator.translate(ResultCode.SUCCESS), httpInterfaceService.queryBySpaceId(request)); } @PostMapping("/interface_http/selectAll") @ResponseBody public PagingDataResponse<HttpInterfaceDTO> queryAll(@Validated @RequestBody BasePagingRequest request) { return new PagingDataResponse<>( translator.translate(ResultCode.SUCCESS), httpInterfaceService.queryAll(request)); } @PostMapping("/interface_http/insert") @ResponseBody public DataResponse<HttpInterfaceDTO> create( @Validated(value = {HttpInterfaceBO.Insert.class}) @RequestBody HttpInterfaceBO httpInterfaceBO ) { return new DataResponse<>( translator.translate(ResultCode.SUCCESS_CREATE_HTTP_INTERFACE), httpInterfaceService.create(httpInterfaceBO)); } @PostMapping("/interface_http/update") @ResponseBody public BaseResponse update( @Validated(value = {HttpInterfaceBO.Update.class}) @RequestBody HttpInterfaceBO httpInterfaceBO ) { httpInterfaceService.update(httpInterfaceBO); return new BaseResponse(translator.translate(ResultCode.SUCCESS_UPDATE_HTTP_INTERFACE)); } @PostMapping("/interface_http/delete") @ResponseBody public BaseResponse delete(@Validated @RequestBody IdRequest idRequest) { httpInterfaceService.delete(idRequest.getId()); return new BaseResponse(translator.translate(ResultCode.SUCCESS_DELETE_HTTP_INTERFACE)); } }
potapuff/ssu-work-jar
src/edu/sumdu/dl/common/XNode.java
package edu.sumdu.dl.common; import java.util.*; import edu.sumdu.dl.parser.QDNode; public class XNode { private QDNode qdNode; private ArrayList children; public XNode() { qdNode = new QDNode(); children = new ArrayList(); } public XNode(QDNode n) { this(); qdNode = n; QDNode[] list = qdNode.getChildren(); for (int i = 0; i < list.length; i++) { addChild(list[i]); } } public static String ridSpace(String s) { String t = s.replaceAll("\\s+", " "); if (t.equals(" ")) { return ""; } else { return t; } } public void addChild(QDNode node) { children.add(new XNode(node)); } public XNode[] getChildren() { if (children.size() == 0) { return new XNode[0]; } XNode[] ar = new XNode[children.size()]; for (int i = 0; i < children.size(); i++) { ar[i] = (XNode) children.get(i); } return ar; } public XNode getChild(int i) { return (XNode) children.get(i); } public Enumeration getAttrs() { return qdNode.getAttributes().keys(); } public String getContent() { return qdNode.getContent(); } public String getAttr(String s) { return qdNode.getAttr(s); } public String getName() { return qdNode.getName(); } public boolean hasAttributes() { return qdNode.getAttributes().size() > 0; } public boolean hasChildNodes() { return children.size() > 0; } public String toString() { return XNParser.dump(this, 0); } }
krcooke/treadmill
lib/python/treadmill/tests/api/authz/group_test.py
"""Group Authz API tests. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple import unittest import mock import treadmill.tests.treadmill_test_skip_windows # pylint: disable=W0611 from treadmill.api.authz import group _MockGrp = namedtuple('grp', ['gr_mem']) class GroupAuthzTest(unittest.TestCase): """treadmill.api.authz.group tests.""" def setUp(self): pass def tearDown(self): pass @mock.patch('grp.getgrnam') def test_authorize(self, mock_getgrnam): """Dummy test for treadmill.api.cell.get()""" # set templates directly. grp_authz = group.API( groups=['treadmill.{proid}'], exclude=['*:get', '*:list', 'r2:create'] ) mock_getgrnam.return_value = _MockGrp(['u1']) authorized, _ = grp_authz.authorize( 'u1@realm', 'get', 'r1', {'pk': 'proidX.a'} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u2@realm', 'get', 'r1', {'pk': 'proidX.a'} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u1@realm', 'list', 'r1', {} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u2@realm', 'list', 'r1', {} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u1@realm', 'create', 'r2', {'pk': 'proidX.a'} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u2@realm', 'create', 'r2', {'pk': 'proidX.a'} ) self.assertTrue(authorized) mock_getgrnam.assert_not_called() authorized, _ = grp_authz.authorize( 'u1@realm', 'create', 'r1', {'pk': 'proidX.a'} ) self.assertTrue(authorized) mock_getgrnam.assert_called_with('treadmill.proidX') authorized, _ = grp_authz.authorize( 'u1@realm', 'bulk_delete', 'r1', {'pk': 'proidX', 'rsrc': '[whatever]'} ) self.assertTrue(authorized) mock_getgrnam.assert_called_with('treadmill.proidX') authorized, _ = grp_authz.authorize( 'u2@realm', 'create', 'r1', {'pk': 'proidX.a'} ) self.assertFalse(authorized) if __name__ == '__main__': unittest.main()
Ashindustry007/competitive-programming
codechef/sept18a/magichf.cc
// https://www.codechef.com/SEPT18A/problems/MAGICHF #include <iostream> using namespace std; int t,n,x,s,a,b; int main() { cin >> t; while (t--) { cin >> n >> x >> s; for (int i = 0; i < s; i++) { cin >> a >> b; if (x == a) x = b; else if (x == b) x = a; } cout << x << endl; } }
leodelmiro/orange-talents-02-template-ecommerce
src/main/java/com/leodelmiro/mercadolivre/fakeendpoints/NewPurchaseInvoiceRequest.java
<filename>src/main/java/com/leodelmiro/mercadolivre/fakeendpoints/NewPurchaseInvoiceRequest.java package com.leodelmiro.mercadolivre.fakeendpoints; import javax.validation.constraints.NotNull; public class NewPurchaseInvoiceRequest { @NotNull private Long purchaseId; @NotNull private Long purchaserId; public NewPurchaseInvoiceRequest(@NotNull Long purchaseId, @NotNull Long purchaserId) { this.purchaseId = purchaseId; this.purchaserId = purchaserId; } public Long getPurchaseId() { return purchaseId; } public Long getPurchaserId() { return purchaserId; } }
onezens/QQTweak
qqtw/qqheaders7.2/QZLayoutManager.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @interface QZLayoutManager : NSObject { } + (id)layoutTagEventSummary:(id)arg1 font:(id)arg2 maxWidth:(double)arg3; + (id)layout_HeadIcon:(id)arg1 rect:(struct CGRect)arg2; + (_Bool)privacyCanTouch:(long long)arg1; + (id)privacyIconByType:(long long)arg1; + (id)shareInstance; + (id)truncateString:(id)arg1 font:(id)arg2 width:(double)arg3 tailCount:(long long)arg4; - (id)addQzoneFeedPortraitWithBound:(id)arg1 info:(id)arg2 user:(id)arg3 handleTouch:(_Bool)arg4 centerY:(double)arg5 portraitWidth:(double)arg6 portraitIndex:(long long)arg7 rect:(struct CGRect)arg8 boundsColor:(id)arg9 boundsWidth:(double)arg10; - (void)adjustSummaryMaxLine:(id)arg1 textWrapper:(id)arg2; - (id)basicOperationButtonWithRect:(struct CGRect)arg1 inset:(struct UIEdgeInsets)arg2 tag:(long long)arg3 label:(id)arg4 imageParam:(id)arg5 title:(id)arg6; - (struct CGSize)calcVideoDisplaySize:(struct CGSize)arg1 screenWidth:(double)arg2 isPGCVideo:(_Bool)arg3; - (float)calculateNickWidthWithModel:(id)arg1 currentNickWidth:(float)arg2; - (double)concernButtonOffset:(id)arg1; - (_Bool)displayDownloadButton:(id)arg1; - (_Bool)displayFollowButton:(id)arg1; - (_Bool)displayNickOnly:(id)arg1; - (void)doExtraLayoutForDynamicAlbum:(id)arg1 useFullColumn:(_Bool)arg2; - (id)drawRecommActionButton:(id)arg1 info:(id)arg2 params:(id)arg3; - (id)formatDisplayCount:(long long)arg1; - (void)generatNotLoadSuccFontDic:(id)arg1 withText:(id)arg2 type:(long long)arg3; - (id)generateCommentButton:(long long)arg1 rect:(struct CGRect)arg2 inset:(struct UIEdgeInsets)arg3 title:(id)arg4; - (id)generateCommonRecommActionButton:(id)arg1 buttonStyle:(long long)arg2 tag:(long long)arg3 iconRect:(struct CGRect)arg4; - (id)generateHighlighteLink:(id)arg1; - (void)generateMoodCommentTitleHeader:(id)arg1 info:(id)arg2 commentType:(long long)arg3 needDisplayFlowButton:(_Bool)arg4; - (void)generateOtherCommentTitleHeader:(id)arg1 info:(id)arg2 commentType:(long long)arg3 needDisplayFlowButton:(_Bool)arg4; - (id)generateOutlineOfRect:(struct CGRect)arg1 color:(id)arg2 lineWidth:(float)arg3 mask:(int)arg4; - (id)generatePraiseButton:(long long)arg1 rect:(struct CGRect)arg2 inset:(struct UIEdgeInsets)arg3 title:(id)arg4; - (id)generateQzoneFeedCellAppReferItem:(id)arg1 maxWidth:(double)arg2 info:(id)arg3; - (id)generateQzoneFeedCellDropDownMenuItem:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (_Bool)generateQzoneFeedCellPermissionInfoUseDescPosition:(id)arg1 model:(id)arg2; - (void)generateQzoneFeedCellSperetorLine:(id)arg1 rect:(struct CGRect)arg2; - (id)generateQzoneFeedCellStarItem:(id)arg1 x:(long long)arg2 y:(long long)arg3; - (void)generateQzoneFont:(id)arg1 andExtendInfo:(id)arg2 withText:(id)arg3; - (void)generateQzoneFontAndSparkleWord:(id)arg1 andComment:(id)arg2 withText:(id)arg3; - (void)generateQzoneFontAndSparkleWord:(id)arg1 andReply:(id)arg2 withText:(id)arg3; - (id)generateQzoneFontAndSparkleWord:(id)arg1 andShareThumb:(id)arg2 withText:(id)arg3; - (void)generateQzoneFontAndSparkleWord:(id)arg1 andSummary:(id)arg2 withText:(id)arg3; - (id)generateQzoneLabelItem:(id)arg1 textColor:(id)arg2 font:(id)arg3 maxRect:(struct CGRect)arg4; - (id)generateQzoneRichTextLabel:(id)arg1 withSparkleWord:(id)arg2; - (id)generateQzoneShimmeringLabelItem:(id)arg1 textColor:(id)arg2 font:(id)arg3 shimmeringCount:(double)arg4 shimmeringColor:(id)arg5 maxRect:(struct CGRect)arg6; - (id)generateQzoneSparkleWord:(id)arg1 andSparkleWord:(id)arg2 andExtendInfo:(id)arg3; - (id)generateRichTextLabelItem_blackStyle:(id)arg1 textColor:(id)arg2 shadowColor:(id)arg3 font:(id)arg4 maxRect:(struct CGRect)arg5; - (id)generateUserAddFriendsButtonItemWithTag:(long long)arg1 hasAddFriend:(_Bool)arg2 info:(id)arg3; - (id)generateUserFollowButtonItemWithTag:(long long)arg1 isConcernFamousFeed:(_Bool)arg2 info:(id)arg3 isFrdLikeFamousFeed:(_Bool)arg4 feed:(id)arg5; - (id)generateUserFollowButtonItemWithTag:(long long)arg1 isConcernFamousFeed:(_Bool)arg2 info:(id)arg3 isFrdLikeFamousFeed:(_Bool)arg4 normalBackground:(id)arg5 pressedBackground:(id)arg6 feed:(id)arg7; - (long long)getMaxCharCount:(id)arg1 maxWidth:(double)arg2 font:(id)arg3; - (id)getPureNumber:(long long)arg1 digit:(long long)arg2; - (id)getTextOfNumber:(long long)arg1 frontText:(id)arg2 uintText:(id)arg3 actionText:(id)arg4; - (_Bool)hasCommentButton:(id)arg1; - (_Bool)hasLikeButton:(id)arg1; - (_Bool)hasLikeLayoutView:(id)arg1; - (void)insertBgItem:(id)arg1 offsetY:(double)arg2 borderWidth:(double)arg3; - (_Bool)isCommentHasMore:(id)arg1; - (_Bool)isLayoutGift:(id)arg1 isForward:(_Bool)arg2; - (void)layoutAllButtonSeperator:(id)arg1 info:(id)arg2 revealSep:(_Bool)arg3 force:(_Bool)arg4 increase:(_Bool)arg5; - (id)layoutCommentWithFeedModel:(id)arg1 layoutInfo:(id)arg2 param:(id)arg3; - (id)layoutContentWithFeedModel:(id)arg1 layoutInfo:(id)arg2 param:(id)arg3; - (id)layoutContentWithVideoFeedModel:(id)arg1 param:(id)arg2; - (id)layoutDetailContentWithFeedModel:(id)arg1 layoutInfo:(id)arg2; - (id)layoutGroupCellTopBarContentCell:(id)arg1; - (void)layoutGroupFeedForSubFeedModel:(id)arg1 withMainFeedModel:(id)arg2; - (void)layoutGroupFeedModel:(id)arg1 isDetail:(_Bool)arg2; - (id)layoutLikeWithFeedModel:(id)arg1 layoutInfo:(id)arg2 param:(id)arg3; - (void)layoutMemorySealOff:(id)arg1 withFeedModel:(id)arg2 isFeed:(_Bool)arg3; - (id)layoutMultiAdvFoot:(id)arg1 info:(id)arg2; - (id)layoutNewVideoSummaryWithVideoFeedModel:(id)arg1 param:(id)arg2; - (void)layoutNoPicTextImage:(id)arg1; - (void)layoutNoPicTextImage:(id)arg1 needForwardBackground:(_Bool)arg2; - (void)layoutPicList:(id)arg1 model:(id)arg2 sizeDict:(id)arg3 info:(id)arg4; - (id)layoutSecretWithFeedModel:(id)arg1 layoutInfo:(id)arg2; - (id)layoutWithNewFeedModel:(id)arg1; - (id)layoutWithNewFeedModel:(id)arg1 param:(id)arg2; - (void)layout_ActiveFeedNickAndTitle:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3 faceItemCenterY:(double)arg4; - (void)layout_CommentHeaderButton:(id)arg1 title:(id)arg2 info:(id)arg3 needDisplayFlowButton:(_Bool)arg4; - (void)layout_CommentNumber:(id)arg1 info:(id)arg2; - (void)layout_CommentVerifyTips:(id)arg1 info:(id)arg2; - (void)layout_DifferentTypeComment:(id)arg1 info:(id)arg2 index:(long long)arg3 isFamousZone:(_Bool)arg4 commentType:(long long)arg5 isInVideoCommentView:(_Bool)arg6 isInCommentDetailView:(_Bool)arg7; - (void)layout_FeedCustomBtn:(id)arg1 info:(id)arg2; - (id)layout_LodingItemWithText:(id)arg1 isLoading:(_Bool)arg2 info:(id)arg3; - (void)layout_PassiveFeedNickAndTitle:(id)arg1 info:(id)arg2 faceItemCenterY:(double)arg3; - (void)layout_QZoneFeedInterest:(id)arg1 info:(id)arg2; - (void)layout_QzoneEmptyFeed:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedBack:(id)arg1 info:(id)arg2 centerY:(double)arg3; - (id)layout_QzoneFeedCellAdvContainerAttach:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellAudio:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellBottomLine_blackStyle:(id)arg1 info:(id)arg2 param:(id)arg3; - (void)layout_QzoneFeedCellBottomRecomm:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4 isVideoFeed:(_Bool)arg5; - (void)layout_QzoneFeedCellButton_blackStyle:(id)arg1 info:(id)arg2 param:(id)arg3 isDetail:(_Bool)arg4; - (id)layout_QzoneFeedCellCanvasBottom:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellComment:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellFollowGuide:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellForward:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellFrdList:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellGiftItems:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellGuiding:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellLbs:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellLike:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellLuckyMoneyList:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellMusic:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4 music:(id)arg5; - (id)layout_QzoneFeedCellPeopleYouMayKnow:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellPicText:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellPicture:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4 picture:(id)arg5; - (void)layout_QzoneFeedCellPlayTimes_blackStyle:(id)arg1 info:(id)arg2 param:(id)arg3 isDetail:(_Bool)arg4; - (id)layout_QzoneFeedCellRecommAction:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (id)layout_QzoneFeedCellRecommAction_blackStyle:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellRecommHeader:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellReferAndPermissionInfo:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellRemark:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellRemarkShotLocation:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellRewardList:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (id)layout_QzoneFeedCellSchoolFollow:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellSearchInfo:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellSeparator:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellSetTopFeedHeader:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellShareThumb:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellSpecialBirthGift:(id)arg1 info:(id)arg2; - (id)layout_QzoneFeedCellSpecialCare:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellSpecialMoreFriendCell:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedCellSummary:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellSummary_blackStyle:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellSummary_blackStyle_v2:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellTitle:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellTitleAndSummary:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedCellUser:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellUserIcon:(id)arg1 info:(id)arg2 nickItemRect:(struct CGRect)arg3 maxY:(double)arg4 adx:(double *)arg5 isBlog:(_Bool)arg6; - (void)layout_QzoneFeedCellUser_blackStyle:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedCellVideo:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4 video:(id)arg5; - (void)layout_QzoneFeedCellVideo_blackStyle:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedDetailContent:(id)arg1 info:(id)arg2 index:(long long)arg3 isForward:(_Bool)arg4; - (void)layout_QzoneFeedDetailJumpCell:(id)arg1; - (void)layout_QzoneFeedFaceList:(id)arg1 info:(id)arg2 left:(double)arg3 width:(double)arg4; - (void)layout_QzoneFeedMainPageShare:(id)arg1 info:(id)arg2 isForward:(_Bool)arg3 isDetail:(_Bool)arg4; - (void)layout_QzoneFeedMutiUserPortrait:(id)arg1 model:(id)arg2 info:(id)arg3 rightX:(double)arg4 centerY:(double)arg5 padding:(double)arg6 portraitWith:(double)arg7 maxCount:(long long)arg8 userCount:(long long)arg9 fontSize:(id)arg10 portraitBoundsWith:(double)arg11 handleTouch:(_Bool)arg12; - (void)layout_QzoneFeedUserList:(id)arg1 icon:(id)arg2 frontText:(id)arg3 finalText:(id)arg4 rect:(struct CGRect)arg5 info:(id)arg6 interactType:(long long)arg7; - (void)layout_QzoneFeedUserListInDetailComment:(id)arg1 icon:(id)arg2 frontText:(id)arg3 finalText:(id)arg4 selfNickName:(id)arg5 rect:(struct CGRect)arg6 info:(id)arg7 interactType:(long long)arg8; - (void)layout_QzoneFeedVideoTags_blackStyle:(id)arg1 info:(id)arg2; - (void)layout_QzoneFeedVisitors:(id)arg1 info:(id)arg2 isDetail:(_Bool)arg3; - (void)layout_QzoneFeedVisitors_blackStyle:(id)arg1 info:(id)arg2; - (void)layout_QzoneQBossPsvAdv:(id)arg1 layoutInfo:(id)arg2; - (void)layout_QzoneRecomTag:(id)arg1 layoutInfo:(id)arg2; - (void)layout_RecomHotVideoInsideCell:(id)arg1 info:(id)arg2; - (void)layout_RecommandFeedTopHeader:(id)arg1 rect:(struct CGRect)arg2 info:(id)arg3; - (id)layout_RecommandUserFinalBoxWithInfo:(id)arg1 param:(id)arg2; - (id)layout_RecommandUserWithInfo:(id)arg1 param:(id)arg2; - (void)layout_VideoFeedNick_blackStyle:(id)arg1 info:(id)arg2 faceItemCenterY:(double)arg3 isNickNameCenter:(_Bool)arg4; - (void)layout_homePageNoFeedsRemindCell:(id)arg1 info:(id)arg2; - (id)makeOldVersion:(id)arg1 andUin:(long long)arg2; - (struct CGSize)mediaBoxWithFixWidth:(double)arg1 FixHeight:(double)arg2 picWidth:(double)arg3 picHeight:(double)arg4 enlargeRate:(double)arg5; - (struct CGSize)minSizeWithPicture:(double)arg1 picHeight:(double)arg2; - (id)parseQzoneDescStr:(id)arg1 andUin:(long long)arg2 andModel:(id)arg3; - (id)qzoneDesc:(id)arg1; - (id)removeTitlePrefixandSuffix:(id)arg1; - (double)screenHeight; - (double)screenWidth; - (id)subChar:(id)arg1 withCount:(long long)arg2; - (id)summaryText:(id)arg1 isForward:(_Bool)arg2; - (void)textWrapperLayoutFinishAndAdd:(id)arg1 textWrapper:(id)arg2 needVoiceOver:(_Bool)arg3; @end
fossabot/kombustion
pkg/parsers/properties/UserPoolDeviceConfiguration.go
<reponame>fossabot/kombustion<gh_stars>0 package properties // DO NOT EDIT: This file is autogenerated by running 'go generate' // It's generated by "github.com/KablamoOSS/kombustion/generate" // UserPoolDeviceConfiguration Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-deviceconfiguration.html type UserPoolDeviceConfiguration struct { ChallengeRequiredOnNewDevice interface{} `yaml:"ChallengeRequiredOnNewDevice,omitempty"` DeviceOnlyRememberedOnUserPrompt interface{} `yaml:"DeviceOnlyRememberedOnUserPrompt,omitempty"` } // UserPoolDeviceConfiguration validation func (resource UserPoolDeviceConfiguration) Validate() []error { errs := []error{} return errs }
lslll0302/Planner-Carrier
planners/PRP/src/search/landmarks/landmark_count_heuristic.cc
<reponame>lslll0302/Planner-Carrier #include "landmark_count_heuristic.h" #include "../plugin.h" #include "../successor_generator.h" #include "../policy-repair/deadend.h" #include <cmath> #include <ext/hash_map> #include <limits> using namespace std; using namespace __gnu_cxx; LandmarkCountHeuristic::LandmarkCountHeuristic(const Options &opts) : Heuristic(opts), lgraph(*opts.get<LandmarkGraph *>("lm_graph")), exploration(lgraph.get_exploration()), lm_status_manager(lgraph) { if (!g_silent_planning) cout << "Initializing landmarks count heuristic..." << endl; use_preferred_operators = opts.get<bool>("pref"); lookahead = numeric_limits<int>::max(); // When generating preferred operators, we plan towards // non-disjunctive landmarks only ff_search_disjunctive_lms = false; if (opts.get<bool>("admissible")) { use_cost_sharing = true; if (lgraph.is_using_reasonable_orderings()) { cerr << "Reasonable orderings should not be used for admissible heuristics" << endl; exit_with(EXIT_INPUT_ERROR); } if (!g_axioms.empty()) { cerr << "cost partitioning does not support axioms" << endl; exit_with(EXIT_UNSUPPORTED); } if (opts.get<bool>("optimal")) { #ifdef USE_LP lm_cost_assignment = new LandmarkEfficientOptimalSharedCostAssignment(lgraph, OperatorCost(opts.get_enum("cost_type"))); #else cerr << "You must build the planner with the USE_LP symbol defined." << endl << "If you already did, try \"make clean\" before rebuilding with USE_LP=1." << endl; exit_with(EXIT_INPUT_ERROR); #endif } else { lm_cost_assignment = new LandmarkUniformSharedCostAssignment(lgraph, opts.get<bool>("alm"), OperatorCost(opts.get_enum("cost_type"))); } } else { use_cost_sharing = false; lm_cost_assignment = 0; } lm_status_manager.set_landmarks_for_initial_state(); } void LandmarkCountHeuristic::set_exploration_goals(const State &state) { assert(exploration != 0); // Set additional goals for FF exploration vector<pair<int, int> > lm_leaves; LandmarkSet result; const vector<bool> &reached_lms_v = lm_status_manager.get_reached_landmarks(state); convert_lms(result, reached_lms_v); collect_lm_leaves(ff_search_disjunctive_lms, result, lm_leaves); exploration->set_additional_goals(lm_leaves); } int LandmarkCountHeuristic::get_heuristic_value(const State &state) { double epsilon = 0.01; // Need explicit test to see if state is a goal state. The landmark // heuristic may compute h != 0 for a goal state if landmarks are // achieved before their parents in the landmarks graph (because // they do not get counted as reached in that case). However, we // must return 0 for a goal state. bool dead_end = lm_status_manager.update_lm_status(state); if (dead_end) { return DEAD_END; } int h = -1; if (use_cost_sharing) { double h_val = lm_cost_assignment->cost_sharing_h_value(); h = ceil(h_val - epsilon); } else { lgraph.count_costs(); int total_cost = lgraph.cost_of_landmarks(); int reached_cost = lgraph.get_reached_cost(); int needed_cost = lgraph.get_needed_cost(); h = total_cost - reached_cost + needed_cost; } // Two plausibility tests in debug mode. assert(h >= 0); return h; } int LandmarkCountHeuristic::compute_heuristic(const State &state) { bool goal_reached = test_goal(state); if (goal_reached) return 0; int h = get_heuristic_value(state); // no (need for) helpful actions, return if (!use_preferred_operators) { return h; } // Try generating helpful actions (those that lead to new leaf LM in the // next step). If all LMs have been reached before or no new ones can be // reached within next step, helpful actions are those occuring in a plan // to achieve one of the LM leaves. LandmarkSet reached_lms; vector<bool> &reached_lms_v = lm_status_manager.get_reached_landmarks(state); convert_lms(reached_lms, reached_lms_v); if (reached_lms.size() == lgraph.number_of_landmarks() || !generate_helpful_actions(state, reached_lms)) { assert(exploration != NULL); set_exploration_goals(state); // Use FF to plan to a landmark leaf vector<pair<int, int> > leaves; collect_lm_leaves(ff_search_disjunctive_lms, reached_lms, leaves); if (!exploration->plan_for_disj(leaves, state)) { exploration->exported_ops.clear(); return DEAD_END; } for (int i = 0; i < exploration->exported_ops.size(); i++) { set_preferred(exploration->exported_ops[i]); } exploration->exported_ops.clear(); } return h; } void LandmarkCountHeuristic::collect_lm_leaves(bool disjunctive_lms, LandmarkSet &reached_lms, vector<pair<int, int> > &leaves) { set<LandmarkNode *>::const_iterator it; for (it = lgraph.get_nodes().begin(); it != lgraph.get_nodes().end(); it++) { LandmarkNode *node_p = *it; if (!disjunctive_lms && node_p->disjunctive) continue; if (reached_lms.find(node_p) == reached_lms.end() && !check_node_orders_disobeyed(*node_p, reached_lms)) { for (int i = 0; i < node_p->vars.size(); i++) { pair<int, int> node_prop = make_pair(node_p->vars[i], node_p->vals[i]); leaves.push_back(node_prop); } } } } bool LandmarkCountHeuristic::check_node_orders_disobeyed(LandmarkNode &node, const LandmarkSet &reached) const { const hash_map<LandmarkNode *, edge_type, hash_pointer> &parents = node.parents; for (hash_map<LandmarkNode *, edge_type, hash_pointer>::const_iterator parent_it = parents.begin(); parent_it != parents.end(); parent_it++) { LandmarkNode &parent = *(parent_it->first); if (reached.find(&parent) == reached.end()) { return true; } } return false; } bool LandmarkCountHeuristic::generate_helpful_actions(const State &state, const LandmarkSet &reached) { /* Find actions that achieve new landmark leaves. If no such action exist, return false. If a simple landmark can be achieved, return only operators that achieve simple landmarks, else return operators that achieve disjunctive landmarks */ vector<const Operator *> all_operators; g_successor_generator->generate_applicable_ops(state, all_operators); vector<const Operator *> ha_simple; vector<const Operator *> ha_disj; for (int i = 0; i < all_operators.size(); i++) { const vector<PrePost> &prepost = all_operators[i]->get_pre_post(); for (int j = 0; j < prepost.size(); j++) { if (!prepost[j].does_fire(state)) continue; const pair<int, int> varval = make_pair(prepost[j].var, prepost[j].post); LandmarkNode *lm_p = lgraph.get_landmark(varval); if (lm_p != 0 && landmark_is_interesting(state, reached, *lm_p)) { if (lm_p->disjunctive) { ha_disj.push_back(all_operators[i]); } else ha_simple.push_back(all_operators[i]); } } } if (ha_disj.empty() && ha_simple.empty()) return false; if (ha_simple.empty()) { for (int i = 0; i < ha_disj.size(); i++) { set_preferred(ha_disj[i]); } } else { for (int i = 0; i < ha_simple.size(); i++) { set_preferred(ha_simple[i]); } } return true; } bool LandmarkCountHeuristic::landmark_is_interesting(const State &s, const LandmarkSet &reached, LandmarkNode &lm) const { /* A landmark is interesting if it hasn't been reached before and its parents have all been reached, or if all landmarks have been reached before, the LM is a goal, and it's not true at moment */ if (lgraph.number_of_landmarks() != reached.size()) { if (reached.find(&lm) != reached.end()) return false; else return !check_node_orders_disobeyed(lm, reached); } return lm.is_goal() && !lm.is_true_in_state(s); } bool LandmarkCountHeuristic::reach_state(const State &parent_state, const Operator &op, const State &state) { lm_status_manager.update_reached_lms(parent_state, op, state); /* TODO: The return value "true" signals that the LM set of this state has changed and the h value should be recomputed. It's not wrong to always return true, but it may be more efficient to check that the LM set has actually changed. */ return true; } void LandmarkCountHeuristic::convert_lms(LandmarkSet &lms_set, const vector<bool> &lms_vec) { // This function exists purely so we don't have to change all the // functions in this class that use LandmarkSets for the reached LMs // (HACK). for (int i = 0; i < lms_vec.size(); i++) if (lms_vec[i]) lms_set.insert(lgraph.get_lm_for_index(i)); } static Heuristic *_parse(OptionParser &parser) { parser.document_synopsis("Landmark-count heuristic", "See also Synergy"); parser.document_note( "Note", "to use `optimal=true`, you must build the planner with USE_LP=1. " "See LPBuildInstructions."); parser.document_note( "Optimal search", "when using landmarks for optimal search (`admissible=true`), " "you probably also want to enable the mpd option of the A* algorithm " "to improve heuristic estimates"); parser.document_note( "cost_type parameter", "only used when `admissible=true` (see LandmarkGraph)"); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional_effects", "supported if `admissible=false`"); parser.document_language_support( "axioms", "supported if `admissible=false` (but may behave stupidly and lead to an unsafe heuristic)"); parser.document_property( "admissible", "yes if `admissible=true` and there are neither conditional effects " "nor axioms"); parser.document_property("consistent", "no"); parser.document_property( "safe", "yes (except maybe on tasks with axioms or when " "using `admissible=true` on tasks with conditional effects)"); parser.document_property("preferred operators", "yes (if enabled; see `pref` option)"); parser.add_option<LandmarkGraph *>( "lm_graph", "the set of landmarks to use for this heuristic. " "The set of landmarks can be specified here, " "or predefined (see LandmarkGraph)."); parser.add_option<bool>("admissible", "get admissible estimate", "false"); parser.add_option<bool>( "optimal", "use optimal (LP-based) cost sharing " "(only makes sense with `admissible=true`)", "false"); parser.add_option<bool>("pref", "identify preferred operators " "(see OptionCaveats#Using_preferred_operators_" "with_the_lmcount_heuristic)", "false"); parser.add_option<bool>("alm", "use action landmarks", "true"); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (!parser.dry_run() && opts.get<LandmarkGraph *>("lm_graph") == 0) parser.error("landmark graph could not be constructed"); if (parser.dry_run()) return 0; else return new LandmarkCountHeuristic(opts); } static Plugin<Heuristic> _plugin( "lmcount", _parse);
yssource/build2
build2/types.hxx
<reponame>yssource/build2 // file : build2/types.hxx -*- C++ -*- // copyright : Copyright (c) 2014-2019 Code Synthesis Ltd // license : MIT; see accompanying LICENSE file #ifndef BUILD2_TYPES_HXX #define BUILD2_TYPES_HXX // Include unprocessed file during bootstrap. See config.hxx.in for details. // #ifdef BUILD2_BOOTSTRAP # include <build2/config.hxx.in> #else # include <build2/config.hxx> #endif #include <array> #include <tuple> #include <vector> #include <string> #include <memory> // unique_ptr, shared_ptr #include <utility> // pair, move() #include <cstddef> // size_t, nullptr_t #include <cstdint> // uint{8,16,32,64}_t, *_MIN, *_MAX #include <istream> #include <ostream> #include <functional> // hash, function, reference_wrapper #include <initializer_list> #include <mutex> #include <atomic> #include <thread> #include <condition_variable> #include <libbutl/ft/shared_mutex.hxx> #if defined(__cpp_lib_shared_mutex) || defined(__cpp_lib_shared_timed_mutex) # include <shared_mutex> #endif #include <ios> // ios_base::failure #include <exception> // exception #include <stdexcept> // logic_error, invalid_argument, runtime_error #include <system_error> #include <libbutl/path.mxx> #include <libbutl/sha256.mxx> #include <libbutl/process.mxx> #include <libbutl/fdstream.mxx> #include <libbutl/optional.mxx> #include <libbutl/const-ptr.mxx> #include <libbutl/timestamp.mxx> #include <libbutl/vector-view.mxx> #include <libbutl/small-vector.mxx> #include <libbutl/project-name.mxx> #include <libbutl/target-triplet.mxx> #include <libbutl/semantic-version.mxx> #include <libbutl/standard-version.mxx> namespace build2 { // Commonly-used types. // using std::uint8_t; using std::uint16_t; using std::uint32_t; using std::uint64_t; using std::uintptr_t; using uint64s = std::vector<uint64_t>; using std::size_t; using std::nullptr_t; using std::pair; using std::tuple; using std::string; using std::function; using std::reference_wrapper; using strings = std::vector<string>; using cstrings = std::vector<const char*>; using std::hash; using std::initializer_list; using std::unique_ptr; using std::shared_ptr; using std::weak_ptr; using std::array; using std::vector; using butl::vector_view; // <libbutl/vector-view.mxx> using butl::small_vector; // <libbutl/small-vector.mxx> using std::istream; using std::ostream; using std::endl; // Concurrency. // using std::atomic; using std::memory_order; using std::memory_order_relaxed; using std::memory_order_consume; using std::memory_order_acquire; using std::memory_order_release; using std::memory_order_acq_rel; using std::memory_order_seq_cst; using atomic_count = atomic<size_t>; // Matches scheduler::atomic_count. // Like std::atomic except implicit conversion and assignment use relaxed // memory ordering. // template <typename T> struct relaxed_atomic: atomic<T> { using atomic<T>::atomic; // Delegate. relaxed_atomic (const relaxed_atomic& a) noexcept : atomic<T> (a.load (memory_order_relaxed)) {} operator T () const noexcept {return this->load (memory_order_relaxed);} T operator= (T v) noexcept { this->store (v, memory_order_relaxed); return v;} T operator= (const relaxed_atomic& a) noexcept { return *this = a.load (memory_order_relaxed);} }; template <typename T> struct relaxed_atomic<T*>: atomic<T*> { using atomic<T*>::atomic; // Delegate. relaxed_atomic (const relaxed_atomic& a) noexcept : atomic<T*> (a.load (memory_order_relaxed)) {} operator T* () const noexcept {return this->load (memory_order_relaxed);} T& operator* () const noexcept {return *this->load (memory_order_relaxed);} T* operator-> () const noexcept {return this->load (memory_order_relaxed);} T* operator= (T* v) noexcept { this->store (v, memory_order_relaxed); return v;} T* operator= (const relaxed_atomic& a) noexcept { return *this = a.load (memory_order_relaxed);} }; // VC 14 has issues. // #if defined(_MSC_VER) && _MSC_VER <= 1900 template <typename T, typename P> inline bool operator== (const relaxed_atomic<T*>& x, const P& y) { return static_cast<T*> (x) == y; } template <typename T, typename P> inline bool operator!= (const relaxed_atomic<T*>& x, const P& y) { return static_cast<T*> (x) != y; } #endif using std::mutex; using mlock = std::unique_lock<mutex>; using std::condition_variable; #if defined(__cpp_lib_shared_mutex) using shared_mutex = std::shared_mutex; using ulock = std::unique_lock<shared_mutex>; using slock = std::shared_lock<shared_mutex>; #elif defined(__cpp_lib_shared_timed_mutex) using shared_mutex = std::shared_timed_mutex; using ulock = std::unique_lock<shared_mutex>; using slock = std::shared_lock<shared_mutex>; #else // Because we have this fallback, we need to be careful not to create // multiple shared locks in the same thread. // struct shared_mutex: mutex { using mutex::mutex; void lock_shared () { lock (); } void try_lock_shared () { try_lock (); } void unlock_shared () { unlock (); } }; using ulock = std::unique_lock<shared_mutex>; using slock = ulock; #endif using std::defer_lock; using std::adopt_lock; using std::thread; namespace this_thread = std::this_thread; // Exceptions. // // While <exception> is included, there is no using for std::exception -- // use qualified. // using std::logic_error; using std::invalid_argument; using std::runtime_error; using std::system_error; using io_error = std::ios_base::failure; // <libbutl/optional.mxx> // using butl::optional; using butl::nullopt; // <libbutl/const-ptr.mxx> // using butl::const_ptr; // <libbutl/path.mxx> // using butl::path; using butl::dir_path; using butl::basic_path; using butl::invalid_path; using butl::path_cast; // Absolute directory path. Note that for now we don't do any checking that // the path is in fact absolute. // // The idea is to have a different type that we automatically complete when // a (variable) value of this type gets initialized from untyped names. See // value_type<abs_dir_path> for details. // // Note that currently we also normalize and actualize the path. And we // leave empty path as is. // struct abs_dir_path: dir_path { using dir_path::dir_path; explicit abs_dir_path (dir_path d): dir_path (std::move (d)) {} abs_dir_path () = default; }; using paths = std::vector<path>; using dir_paths = std::vector<dir_path>; // <libbutl/timestamp.mxx> // using butl::system_clock; using butl::timestamp; using butl::duration; using butl::timestamp_unknown; using butl::timestamp_unknown_rep; using butl::timestamp_nonexistent; using butl::to_string; using butl::operator<<; // <libbutl/sha256.mxx> // using butl::sha256; // <libbutl/process.mxx> // <libbutl/fdstream.mxx> // using butl::process; using butl::process_env; using butl::process_path; using butl::process_error; using butl::auto_fd; using butl::ifdstream; using butl::ofdstream; using butl::fdopen_mode; using butl::fdstream_mode; // <libbutl/target-triplet.mxx> // using butl::target_triplet; // <libbutl/semantic-version.mxx> // using butl::semantic_version; using butl::parse_semantic_version; // <libbutl/standard-version.mxx> // using butl::standard_version; using butl::standard_version_constraint; // <libbutl/project-name.mxx> // using butl::project_name; // Diagnostics location. // class location { public: // Note that location maintains a shallow reference to path. Zero lines // or columns are not printed. // explicit location (const path* f = nullptr, uint64_t l = 0, uint64_t c = 0) : file (f), line (l), column (c) {} bool empty () const {return file == nullptr;} const path* file; uint64_t line; uint64_t column; }; // See context. // enum class run_phase {load, match, execute}; ostream& operator<< (ostream&, run_phase); // utility.cxx extern run_phase phase; } // In order to be found (via ADL) these have to be either in std:: or in // butl::. The latter is a bad idea since libbutl includes the default // implementation. They are defined in utility.cxx. // namespace std { // Path printing with trailing slash for directories. // ostream& operator<< (ostream&, const ::butl::path&); // Print as recall[@effect]. // ostream& operator<< (ostream&, const ::butl::process_path&); } // <build2/name.hxx> // #include <build2/name.hxx> #endif // BUILD2_TYPES_HXX
antopen/alipay-sdk-java-all
src/main/java/com/alipay/api/domain/AlipayFincoreComplianceCrossborderMerchantBatchqueryModel.java
package com.alipay.api.domain; import java.util.List; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; /** * 跨境商户等级批量查询 * * @author auto create * @since 1.0, 2021-08-18 10:31:37 */ public class AlipayFincoreComplianceCrossborderMerchantBatchqueryModel extends AlipayObject { private static final long serialVersionUID = 4148592928239693259L; /** * 业务来源,由合规平台分配,如:CHYISHE */ @ApiField("biz_source") private String bizSource; /** * 跨境商户基础信息List */ @ApiListField("org_list") @ApiField("base_crossborder_merchant_info") private List<BaseCrossborderMerchantInfo> orgList; /** * 外部业务号:20210701WF001 */ @ApiField("out_biz_no") private String outBizNo; /** * 批次查询总条数 */ @ApiField("total") private Long total; public String getBizSource() { return this.bizSource; } public void setBizSource(String bizSource) { this.bizSource = bizSource; } public List<BaseCrossborderMerchantInfo> getOrgList() { return this.orgList; } public void setOrgList(List<BaseCrossborderMerchantInfo> orgList) { this.orgList = orgList; } public String getOutBizNo() { return this.outBizNo; } public void setOutBizNo(String outBizNo) { this.outBizNo = outBizNo; } public Long getTotal() { return this.total; } public void setTotal(Long total) { this.total = total; } }
madang01/gitcodda
codda2/project/sample_test/client_build/web_build/src/main/java/kr/pe/codda/weblib/jdf/AbstractMultipartServlet.java
<reponame>madang01/gitcodda package kr.pe.codda.weblib.jdf; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; import kr.pe.codda.weblib.common.AccessedUserInformation; public abstract class AbstractMultipartServlet extends AbstractServlet { private static final long serialVersionUID = -6436777887426672536L; protected void performPreTask(HttpServletRequest req, HttpServletResponse res) throws Exception { if (! ServletFileUpload.isMultipartContent(req)) { String errorMessage = "the request doesn't contain multipart content"; AccessedUserInformation accessedUserformation = getAccessedUserInformationFromSession(req); String userID = (null == accessedUserformation) ? "guest" : accessedUserformation.getUserID(); String debugMessage = new StringBuilder(errorMessage).append(", userID=") .append(userID) .append(", ip=") .append(req.getRemoteAddr()).toString(); log.warning(debugMessage); printErrorMessagePage(req, res, errorMessage, debugMessage); return; } /* * if (! isUserLoginedIn(req)) { String requestURI = req.getRequestURI(); * * ServerSessionkeyIF webServerSessionkey = null; try { ServerSessionkeyManager * serverSessionkeyManager = ServerSessionkeyManager.getInstance(); * webServerSessionkey = * serverSessionkeyManager.getMainProjectServerSessionkey(); } catch * (SymmetricException e) { * log.warn("ServerSessionkeyManger instance init error, errormessage=[{}]", * e.getMessage()); * * String errorMessage = "ServerSessionkeyManger instance init error"; String * debugMessage = * String.format("ServerSessionkeyManger instance init error, errormessage=[%s]" * , e.getMessage()); printErrorMessagePage(req, res, errorMessage, * debugMessage); return; } * * req.setAttribute("successURL", requestURI); * req.setAttribute(WebCommonStaticFinalVars. * REQUEST_KEY_NAME_OF_MODULUS_HEX_STRING, * webServerSessionkey.getModulusHexStrForWeb()); printJspPage(req, res, * JDF_USER_LOGIN_INPUT_PAGE); return; } */ super.performPreTask(req, res); } }
tgoprince/menthor-editor
net.menthor.ontouml2text/src/net/menthor/ontouml2text/descriptionSpace/descriptionCategories/Mixin.java
package net.menthor.ontouml2text.descriptionSpace.descriptionCategories; import net.menthor.ontouml2text.descriptionSpace.SemiRigidDescriptionCategory; public class Mixin extends SemiRigidDescriptionCategory { public Mixin(String label) { super(label); } }
xinlyun/DivTwo
app/src/main/java/com/lin/dlivkfragment/setting/IatSettings.java
<gh_stars>1-10 package com.lin.dlivkfragment.setting; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.view.Window; import com.lin.dlivkfragment.R; import com.lin.dlivkfragment.util.SettingTextWatcher; /** * 听写设置界面 */ public class IatSettings extends PreferenceActivity implements OnPreferenceChangeListener { public static final String PREFER_NAME = "com.iflytek.setting"; private EditTextPreference mVadbosPreference; private EditTextPreference mVadeosPreference; @SuppressWarnings("deprecation") public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName(PREFER_NAME); addPreferencesFromResource(R.xml.iat_setting); mVadbosPreference = (EditTextPreference)findPreference("iat_vadbos_preference"); mVadbosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this,mVadbosPreference,0,10000)); mVadeosPreference = (EditTextPreference)findPreference("iat_vadeos_preference"); mVadeosPreference.getEditText().addTextChangedListener(new SettingTextWatcher(IatSettings.this,mVadeosPreference,0,10000)); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { return true; } }
DatatransInformatika/beruang
build/es6/node_modules/@beruang/polar/polar-behavior.js
/** @license Copyright (c) 2019 The Beruang Project Authors. All rights reserved. This code may only be used under the BSD style license found at https://github.com/DatatransInformatika/beruang/blob/master/LICENSE.txt The complete set of authors may be found at https://github.com/DatatransInformatika/beruang/blob/master/AUTHORS.txt The complete set of contributors may be found at https://github.com/DatatransInformatika/beruang/blob/master/CONTRIBUTORS.txt */import{dedupingMixin}from"../../@polymer/polymer/lib/utils/mixin.js";import{FlattenedNodesObserver}from"../../@polymer/polymer/lib/utils/flattened-nodes-observer.js";/** `PolarBehavior` @polymerBehavior PolarBehavior */let internalPolarBehavior=base=>class extends base{static get properties(){return{/** Does not wrap child element overflows in main axis direction. @type{Boolean} */noWrap:{type:Boolean,value:!1,reflectToAttribute:!0},/** Shows overflowed child element portion in horizontal direction. @type{Boolean} */overflowXVisible:{type:Boolean,value:!1,reflectToAttribute:!0},/** Hides overflowed child element portion in horizontal direction. @type{Boolean} */overflowXHidden:{type:Boolean,value:!1,reflectToAttribute:!0},/** Always shows horizontal scroller. @type{Boolean} */overflowXScroll:{type:Boolean,value:!1,reflectToAttribute:!0},/** Only shows horizontal scroller when child element overflows. @type{Boolean} */overflowXAuto:{type:Boolean,value:!1,reflectToAttribute:!0},/** Shows overflowed child element portion in vertical direction. @type{Boolean} */overflowYVisible:{type:Boolean,value:!1,reflectToAttribute:!0},/** Hides overflowed child element portion in vertical direction. @type{Boolean} */overflowYHidden:{type:Boolean,value:!1,reflectToAttribute:!0},/** Always shows vertical scroller. @type{Boolean} */overflowYScroll:{type:Boolean,value:!1,reflectToAttribute:!0},/** Only shows vertical scroller when child element overflows. @type{Boolean} */overflowYAuto:{type:Boolean,value:!1,reflectToAttribute:!0}}}};export const PolarBehavior=dedupingMixin(internalPolarBehavior);
bkiac/lightning
lnd_responses/channel_edge_as_channel.js
<filename>lnd_responses/channel_edge_as_channel.js const {chanFormat} = require('bolt07'); const channelPolicyAsPolicy = require('./channel_policy_as_policy'); const separatorChar = ':'; /** Channel edge as channel { capacity: <Capacity Tokens String> chan_point: <Channel Funding Outpoint String> channel_id: <Numeric Channel Id String> node1_policy: { disabled: <Forwarding is Disabled Bool> fee_base_msat: <Base Fee Tokens String> fee_rate_milli_msat: <Fee Rate Number String> last_update: <Last Update Epoch Time Seconds Number> max_htlc_msat: <Maximum HTLC Millitokens String> min_htlc: <Minimum HTLC Millitokens String> time_lock_delta: <CLTV Delta Number> } node1_pub: <Lexical Order First Node Public Key Hex String> node2_policy: { disabled: <Forwarding is Disabled Bool> fee_base_msat: <Base Fee Tokens String> fee_rate_milli_msat: <Fee Rate Number String> last_update: <Last Update Epoch Time Seconds Number> max_htlc_msat: <Maximum HTLC Millitokens String> min_htlc: <Minimum HTLC Millitokens String> time_lock_delta: <CLTV Delta Number> } node2_pub: <Lexical Order Second Node Public Key Hex String> } @throws <Error> @returns { capacity: <Maximum Tokens Number> id: <Standard Format Channel Id String> policies: [{ [base_fee_mtokens]: <Base Fee Millitokens String> [cltv_delta]: <Locktime Delta Number> [fee_rate]: <Fees Charged in Millitokens Per Million Number> [is_disabled]: <Channel Is Disabled Bool> [max_htlc_mtokens]: <Maximum HTLC Millitokens Value String> [min_htlc_mtokens]: <Minimum HTLC Millitokens Value String> public_key: <Node Public Key String> [updated_at]: <Edge Last Updated At ISO 8601 Date String> }] transaction_id: <Transaction Id Hex String> transaction_vout: <Transaction Output Index Number> [updated_at]: <Channel Last Updated At ISO 8601 Date String> } */ module.exports = args => { if (!args.capacity) { throw new Error('ExpectedChannelCapacityInChannelEdgeResponse'); } if (!args.chan_point) { throw new Error('ExpectedChannelOutpointInChannelEdgeResponse'); } if (!args.channel_id) { throw new Error('ExpectedChannelIdInChannelEdgeResponse'); } try { chanFormat({number: args.channel_id}); } catch (err) { throw new Error('ExpectedNumericFormatChannelIdInChannelEdgeResponse'); } if (!args.node1_pub) { throw new Error('ExpectedChannelNode1PublicKey'); } if (!args.node2_pub) { throw new Error('ExpectedChannelNode2PublicKey'); } const [transactionId, vout] = args.chan_point.split(separatorChar); if (!transactionId) { throw new Error('ExpectedTransactionIdForChannelOutpoint'); } if (!vout) { throw new Error('ExpectedTransactionVoutForChannelOutpoint'); } const publicKeys = [args.node1_pub, args.node2_pub]; const policies = [args.node1_policy, args.node2_policy].map((policy, i) => { return channelPolicyAsPolicy({policy, public_key: publicKeys[i]}); }); const [node1Policy, node2Policy] = policies; const policiesUpdated = policies.map(n => n.updated_at).filter(n => !!n); const [updatedAt] = policiesUpdated.sort().reverse(); return { id: chanFormat({number: args.channel_id}).channel, capacity: Number(args.capacity), policies: [node1Policy, node2Policy], transaction_id: transactionId, transaction_vout: Number(vout), updated_at: updatedAt, }; };
alexshpunt/art_gear
Editor/Wrappers/Components/AGEComponent.cpp
<reponame>alexshpunt/art_gear #include "AGEComponent.h" #include "Editor/Wrappers/Components/AGEComponent.h" AGEComponent::AGEComponent( AGEGameObject* object ) : m_gameObject( object ) {} AGEComponent::~AGEComponent() {} AGEGameObject* AGEComponent::getGameObject() const { return m_gameObject; }
joaosoft/Go
78_master-go-programing/14 - packages and modules/3 - coding challenges/1/main.go
/* Consider this function: // Checks if a number is prime or not func IsPrime(num int) bool { for i := 2; i < int(num/2); i++ { if num%i == 0 { return false } } return true } Create a package called arithmetic in $GOPATH/packages/mypackages and paste the above function in a file of package. Create an executable Go application, import the package arithmetic and call the function IsPrime. */ package main
sampath419/ApplicationInsights-Ruby
test/application_insights/channel/contracts/test_envelope.rb
require_relative '../../../../lib/application_insights/channel/contracts/envelope' require 'test/unit' include ApplicationInsights::Channel class TestEnvelope < Test::Unit::TestCase def test_initialize item = Contracts::Envelope.new assert_not_nil item end def test_ver_works_as_expected expected = 80 item = Contracts::Envelope.new item.ver = expected actual = item.ver assert_equal expected, actual expected = 38 item.ver = expected actual = item.ver assert_equal expected, actual end def test_name_works_as_expected expected = 'adlchSLC' item = Contracts::Envelope.new item.name = expected actual = item.name assert_equal expected, actual expected = 'BoywoCzj' item.name = expected actual = item.name assert_equal expected, actual end def test_time_works_as_expected expected = 'rdfJJhQs' item = Contracts::Envelope.new item.time = expected actual = item.time assert_equal expected, actual expected = 'zotVaJNt' item.time = expected actual = item.time assert_equal expected, actual end def test_sample_rate_works_as_expected expected = 4.3706 item = Contracts::Envelope.new item.sample_rate = expected actual = item.sample_rate assert_equal expected, actual expected = 9.2301 item.sample_rate = expected actual = item.sample_rate assert_equal expected, actual end def test_seq_works_as_expected expected = 'rCitVJLQ' item = Contracts::Envelope.new item.seq = expected actual = item.seq assert_equal expected, actual expected = 'eTUUGRJV' item.seq = expected actual = item.seq assert_equal expected, actual end def test_i_key_works_as_expected expected = 'siOxfiva' item = Contracts::Envelope.new item.i_key = expected actual = item.i_key assert_equal expected, actual expected = 'mhrUZzEP' item.i_key = expected actual = item.i_key assert_equal expected, actual end def test_tags_works_as_expected item = Contracts::Envelope.new actual = item.tags assert_not_nil actual end def test_data_works_as_expected expected = { 'key' => 'value' } item = Contracts::Envelope.new item.data = expected actual = item.data assert_equal expected, actual expected = { 'key' => 'value' } item.data = expected actual = item.data assert_equal expected, actual end def test_to_json_works_as_expected item = Contracts::Envelope.new item.ver = 80 item.name = 'adlchSLC' item.time = 'rdfJJhQs' item.sample_rate = 4.3706 item.seq = 'rCitVJLQ' item.i_key = 'siOxfiva' { 'rMCx' => 'bZQsOeRE' }.each do |key, value| item.tags[key] = value end item.data = { 'key' => 'value' } actual = item.to_json expected = '{"ver":80,"name":"adlchSLC","time":"rdfJJhQs","sampleRate":4.3706,"seq":"rCitVJLQ","iKey":"siOxfiva","tags":{"rMCx":"bZQsOeRE"},"data":{"key":"value"}}' assert_equal expected, actual end end
bahanni/custom_rpi4
priv/farmware/measure-soil-height/calculate_multiple.py
#!/usr/bin/env python3.8 'Perform calculations on multiple stereo image sets.' import json from time import time import numpy as np import cv2 as cv from calculate import Calculate from plot import Plot def _abridged(histogram): low_label_mask = ['low' in h for h in histogram] high_label_mask = ['high' in h for h in histogram] if not any(low_label_mask) or not any(high_label_mask): return histogram low = low_label_mask.index(True) high = -high_label_mask[::-1].index(True) return histogram[low:high] def _best_fit(disparity, expected): coefficients = [] prev = None for param in zip(disparity, expected): if prev is None: prev = param continue disparities = [prev[0], param[0]] expecteds = [prev[1], param[1]] slope, intercept = np.polyfit(disparities, expecteds, 1) coefficients.append([round(slope, 4), round(intercept, 4)]) prev = param slopes = [c[0] for c in coefficients] intercepts = [c[1] for c in coefficients] if len(slopes) % 2 == 0: slopes.append(0) new_slope = np.median(slopes) new_intercept = intercepts[slopes.index(new_slope)] return new_slope, new_intercept class CalculateMultiple(): 'Calculate results for all stereo image sets.' def __init__(self, core, image_sets=None): self.core = core self.settings = core.settings.settings self.log = core.log self.results = core.results self.title = core.settings.title self.image_sets = image_sets self.set_results = None if image_sets is not None: self._after_load() def _after_load(self): self.set_results = [None] * len(self.image_sets) image = self.image_sets[0]['left'][0]['data'] recommended_search_depth = int(2 + image.size / 1000000 * 0.5) provided_search_depth = int(self.settings['disparity_search_depth']) if provided_search_depth < recommended_search_depth: msg = f'Increasing search depth from {provided_search_depth}' msg += f' to {recommended_search_depth}' self.log.debug(msg) self.settings['disparity_search_depth'] = recommended_search_depth self.results.save_config('disparity_search_depth') def load_images(self, image_set_data): 'Load image sets.' self.image_sets = [] for i, image_set in enumerate(image_set_data): self.image_sets.append({}) location = image_set.get('location') for stereo_id, images in image_set.items(): if stereo_id not in ['left', 'right']: continue self.image_sets[i][stereo_id] = [] for image in images: image['tag'] = stereo_id image['location'] = image.get('location', location) image['data'] = cv.imread(image['name']) if image['data'] is None: self.log.error(f"'{image['name']}' doesn't exist.") self.image_sets[i][stereo_id].append(image) self._after_load() def calculate_multiple(self): 'Run calculations for each image set.' if self.image_sets is None: self.log.error('No images provided.') for i, image_set in enumerate(self.image_sets): start = time() calculation = Calculate(self.core, image_set) details = calculation.calculate() if details is not None: disparity = calculation.images.output['disparity'].data.reduced histogram_data = disparity.get('histogram', []) details['histogram'] = _abridged(histogram_data) details['duration'] = round(time() - start, 2) self.set_results[i] = details if len(self.image_sets) > 1 and self.core.settings.images['plot']: self.plot() self.save_report() def plot(self): 'Plot all set values.' set_results = [r for r in self.set_results if r.get('values') is not None] if len(set_results) > 0: values = set_results[-1]['values'] measured_distance = values['measured_distance'] disparity_offset = values['disparity_offset'] factor = values['calibration_factor'] plot = Plot(self.core) plot.line(-factor, measured_distance + disparity_offset * factor) disparity = [r['values']['disparity'] for r in set_results] distance = [r['values']['calc_distance'] for r in set_results] expected = [r['values']['new_meas_dist'] for r in set_results] if len(set_results) > 1: self.adjust_calibration(plot, disparity, expected) plot.points(disparity, distance, size=10) plot.points(disparity, expected, thickness=2) plot.save('plot') def adjust_calibration(self, plot, disparity, expected): 'Use expected values to adjust calibration parameters.' values = self.set_results[-1]['values'] measured_distance = values['measured_distance'] disparity_offset = values['disparity_offset'] factor = values['calibration_factor'] if self.settings['adjust_calibration_parameters']: slope, intercept = _best_fit(disparity, expected) plot.line(slope, intercept, thickness=2) new_factor = -slope new_offset = round((intercept - measured_distance) / new_factor, 4) adjustments_string = f'{disparity_offset = } {new_offset = }' adjustments_string += f' {factor = } {new_factor = }' if factor != new_factor and disparity_offset != new_offset: self.log.debug(adjustments_string) self.settings['calibration_factor'] = new_factor self.settings['calibration_disparity_offset'] = new_offset self.results.save_calibration() def save_report(self): 'Save reduced data to file.' if self.core.settings.reports_enabled(): filename = f'{self.settings["images_dir"]}/{self.title}results.json' with open(filename, 'w') as results_file: results_file.write(json.dumps(self.set_results, indent=2))
eventualbuddha/encoder-tools
spec/cli/subtitles/offset_spec.rb
require 'spec_helper' RSpec.describe EncoderTools::CLI::Subtitles::Offset do include_context 'a CLI command' it "does nothing with an empty subtitle list" do options[:add] = '0' input.string = "" subject.run expect(output.string).to eq("") end it "does not alter a subtitle list with zero offset" do options[:add] = '0' input.string = subfile("kill-bill-vol-2") subject.run expect(output.string).to eq(subfile("kill-bill-vol-2")) end it "writes a file with positive offset" do options[:add] = '2' input.string = subfile("short-example") subject.run expect(output.string).to eq(subfile("short-example-offset-plus-2")) end it "writes a file with negative offset" do options[:subtract] = '2' input.string = subfile("short-example") subject.run expect(output.string).to eq(subfile("short-example-offset-minus-2")) end it "writes a file with absolute offset" do options[:set] = '2' input.string = subfile("short-example") subject.run expect(output.string).to eq(subfile("short-example-offset-2")) end it "parses an offset with a fractional part" do options[:set] = '12.34' expect(subject.send(:parse_offset, EncoderTools::Subtitles::List.new, options[:set])).to eq(BigDecimal(options[:set])) end it "parses an offset in hh:mm:ss format" do options[:set] = '1:02:03' expect(subject.send(:parse_offset, EncoderTools::Subtitles::List.new, options[:set])).to eq(3+(2+1*60)*60) end it "parses an offset in mm:ss format" do options[:set] = '2:03' expect(subject.send(:parse_offset, EncoderTools::Subtitles::List.new, options[:set])).to eq(3+2*60) end end
rherardi/xml-xalan-c-src_1_10_0
src/xalanc/XercesParserLiaison/Deprecated/XercesTreeWalker.hpp
/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(XERCESTREEWALKER_HEADER_GUARD_1357924680) #define XERCESTREEWALKER_HEADER_GUARD_1357924680 #include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp> #include <xalanc/XercesParserLiaison/Deprecated/XercesBridgeTypes.hpp> XALAN_CPP_NAMESPACE_BEGIN /** * This class is deprecated. * * @deprecated This class works with the deprecated Xerces DOM bridge. */ class XALAN_XERCESPARSERLIAISON_EXPORT XercesTreeWalker { public: /** * Constructor. */ XercesTreeWalker(); virtual ~XercesTreeWalker(); /** * Perform a pre-order traversal non-recursive style. */ virtual void traverse(const DOM_NodeType& pos); /** * Perform a pre-order traversal non-recursive style. */ virtual void traverse( const DOM_NodeType& pos, const DOM_NodeType& parent); protected: virtual void startNode(const DOM_NodeType& node) = 0; virtual void endNode(const DOM_NodeType& node) = 0; }; XALAN_CPP_NAMESPACE_END #endif // XERCESTREEWALKER_HEADER_GUARD_1357924680
threefishes/springCloudMainService
cloud-repository/src/main/java/cn/threefishes/cloudrepository/entity/LiveRoomSlider.java
package cn.threefishes.cloudrepository.entity; public class LiveRoomSlider { private Integer liveRoomSliderId; private String imageJson; public Integer getLiveRoomSliderId() { return liveRoomSliderId; } public void setLiveRoomSliderId(Integer liveRoomSliderId) { this.liveRoomSliderId = liveRoomSliderId; } public String getImageJson() { return imageJson; } public void setImageJson(String imageJson) { this.imageJson = imageJson == null ? null : imageJson.trim(); } }
windniw/just-for-fun
leetcode/83.py
<reponame>windniw/just-for-fun<filename>leetcode/83.py """ link: https://leetcode.com/problems/remove-duplicates-from-sorted-list problem: 删除链表中的重复项,使每项唯一 solution: 直接扫 """ class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: t = head while t: if t.next and t.next.val == t.val: t.next = t.next.next else: t = t.next return head
lczx/fdi2-exams
design-patterns/creational/factory/Pattern.java
<reponame>lczx/fdi2-exams import shapes.Shape; import shapes.ShapeFactory; public class Pattern { public static void main(String[] args) { ShapeFactory sf = new ShapeFactory(); Shape shape1 = sf.getShape("circle"); shape1.draw(); Shape shape2 = sf.getShape("rectangle"); shape2.draw(); Shape shape3 = sf.getShape("square"); shape3.draw(); } }
medismailben/llvm-project
clang/test/CodeGen/2005-07-26-UnionInitCrash.c
<reponame>medismailben/llvm-project // PR607 // RUN: %clang_cc1 %s -emit-llvm -o - union { char bytes[8]; double alignment; }EQ1 = {0,0,0,0,0,0,0,0};
pablotrinidad/icc
psets/P06/src/icc/clases/UsoCiudadano.java
<filename>psets/P06/src/icc/clases/UsoCiudadano.java package icc.clases; public class UsoCiudadano { public static void main(String[] args) { Ciudadano carmen = new Ciudadano("<NAME>", "de Costa Brava", "Cortez", "30/03/2001"); System.out.println("RFC: " + carmen.calculaRFC()); System.out.println(carmen.toString()); Ciudadano siqueiros = new Ciudadano("David", "Álfaro", "Siqueiros", "29/12/1896"); System.out.println("RFC: " + siqueiros.calculaRFC()); System.out.println(siqueiros.toString()); Ciudadano cantinflas = new Ciudadano("<NAME>", "Moreno", "Reyes", "12/08/1911"); System.out.println("RFC: " + cantinflas.calculaRFC()); System.out.println(cantinflas.toString()); } }
patham9/opennars_googlecode
nars_core_java/nars/inference/RuleTables.java
/* * The MIT License * * Copyright 2019 The OpenNARS authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package nars.inference; import nars.entity.*; import nars.language.*; import nars.storage.Memory; import nars.io.Symbols; /** * Table of inference rules, indexed by the TermLinks for the task and the * belief. Used in indirective processing of a task, to dispatch inference cases * to the relevant inference rules. */ public class RuleTables { /** * Entry point of the inference engine * * @param tLink The selected TaskLink, which will provide a task * @param bLink The selected TermLink, which may provide a belief * @param memory Reference to the memory */ public static void reason(TaskLink tLink, TermLink bLink, Memory memory) { Task task = memory.currentTask; Sentence taskSentence = task.getSentence(); Term taskTerm = (Term) taskSentence.getContent().clone(); // cloning for substitution Term beliefTerm = (Term) bLink.getTarget().clone(); // cloning for substitution Concept beliefConcept = memory.termToConcept(beliefTerm); Sentence belief = null; if (beliefConcept != null) { belief = beliefConcept.getBelief(task); } memory.currentBelief = belief; // may be null if (belief != null) { LocalRules.match(task, belief, memory); } if (!memory.noResult() && task.getSentence().isJudgment()) { return; } short tIndex = tLink.getIndex(0); short bIndex = bLink.getIndex(0); switch (tLink.getType()) { // dispatch first by TaskLink type case TermLink.SELF: switch (bLink.getType()) { case TermLink.COMPONENT: compoundAndSelf((CompoundTerm) taskTerm, beliefTerm, true, memory); break; case TermLink.COMPOUND: compoundAndSelf((CompoundTerm) beliefTerm, taskTerm, false, memory); break; case TermLink.COMPONENT_STATEMENT: if (belief != null) { SyllogisticRules.detachment(task.getSentence(), belief, bIndex, memory); } break; case TermLink.COMPOUND_STATEMENT: if (belief != null) { SyllogisticRules.detachment(belief, task.getSentence(), bIndex, memory); } break; case TermLink.COMPONENT_CONDITION: if (belief != null) { bIndex = bLink.getIndex(1); SyllogisticRules.conditionalDedInd((Implication) taskTerm, bIndex, beliefTerm, tIndex, memory); } break; case TermLink.COMPOUND_CONDITION: if (belief != null) { bIndex = bLink.getIndex(1); SyllogisticRules.conditionalDedInd((Implication) beliefTerm, bIndex, taskTerm, tIndex, memory); } break; } break; case TermLink.COMPOUND: switch (bLink.getType()) { case TermLink.COMPOUND: compoundAndCompound((CompoundTerm) taskTerm, (CompoundTerm) beliefTerm, memory); break; case TermLink.COMPOUND_STATEMENT: compoundAndStatement((CompoundTerm) taskTerm, tIndex, (Statement) beliefTerm, bIndex, beliefTerm, memory); break; case TermLink.COMPOUND_CONDITION: if (belief != null) { if (beliefTerm instanceof Implication) { if (Variable.unify(Symbols.VAR_INDEPENDENT, ((Implication) beliefTerm).getSubject(), taskTerm, beliefTerm, taskTerm)) { detachmentWithVar(belief, taskSentence, bIndex, memory); } else { SyllogisticRules.conditionalDedInd((Implication) beliefTerm, bIndex, taskTerm, -1, memory); } } else if (beliefTerm instanceof Equivalence) { SyllogisticRules.conditionalAna((Equivalence) beliefTerm, bIndex, taskTerm, -1, memory); } } break; } break; case TermLink.COMPOUND_STATEMENT: switch (bLink.getType()) { case TermLink.COMPONENT: componentAndStatement((CompoundTerm) memory.currentTerm, bIndex, (Statement) taskTerm, tIndex, memory); break; case TermLink.COMPOUND: compoundAndStatement((CompoundTerm) beliefTerm, bIndex, (Statement) taskTerm, tIndex, beliefTerm, memory); break; case TermLink.COMPOUND_STATEMENT: if (belief != null) { syllogisms(tLink, bLink, taskTerm, beliefTerm, memory); } break; case TermLink.COMPOUND_CONDITION: if (belief != null) { bIndex = bLink.getIndex(1); if (beliefTerm instanceof Implication) { conditionalDedIndWithVar((Implication) beliefTerm, bIndex, (Statement) taskTerm, tIndex, memory); } } break; } break; case TermLink.COMPOUND_CONDITION: switch (bLink.getType()) { case TermLink.COMPOUND: if (belief != null) { detachmentWithVar(taskSentence, belief, tIndex, memory); } break; case TermLink.COMPOUND_STATEMENT: if (belief != null) { if (taskTerm instanceof Implication) // TODO maybe put instanceof test within conditionalDedIndWithVar() { Term subj = ((Implication) taskTerm).getSubject(); if (subj instanceof Negation) { if (task.getSentence().isJudgment()) { componentAndStatement((CompoundTerm) subj, bIndex, (Statement) taskTerm, tIndex, memory); } else { componentAndStatement((CompoundTerm) subj, tIndex, (Statement) beliefTerm, bIndex, memory); } } else { conditionalDedIndWithVar((Implication) taskTerm, tIndex, (Statement) beliefTerm, bIndex, memory); } } break; } break; } } } /* ----- syllogistic inferences ----- */ /** * Meta-table of syllogistic rules, indexed by the content classes of the * taskSentence and the belief * * @param tLink The link to task * @param bLink The link to belief * @param taskTerm The content of task * @param beliefTerm The content of belief * @param memory Reference to the memory */ private static void syllogisms(TaskLink tLink, TermLink bLink, Term taskTerm, Term beliefTerm, Memory memory) { Sentence taskSentence = memory.currentTask.getSentence(); Sentence belief = memory.currentBelief; int figure; if (taskTerm instanceof Inheritance) { if (beliefTerm instanceof Inheritance) { figure = indexToFigure(tLink, bLink); asymmetricAsymmetric(taskSentence, belief, figure, memory); } else if (beliefTerm instanceof Similarity) { figure = indexToFigure(tLink, bLink); asymmetricSymmetric(taskSentence, belief, figure, memory); } else { detachmentWithVar(belief, taskSentence, bLink.getIndex(0), memory); } } else if (taskTerm instanceof Similarity) { if (beliefTerm instanceof Inheritance) { figure = indexToFigure(bLink, tLink); asymmetricSymmetric(belief, taskSentence, figure, memory); } else if (beliefTerm instanceof Similarity) { figure = indexToFigure(bLink, tLink); symmetricSymmetric(belief, taskSentence, figure, memory); } } else if (taskTerm instanceof Implication) { if (beliefTerm instanceof Implication) { figure = indexToFigure(tLink, bLink); asymmetricAsymmetric(taskSentence, belief, figure, memory); } else if (beliefTerm instanceof Equivalence) { figure = indexToFigure(tLink, bLink); asymmetricSymmetric(taskSentence, belief, figure, memory); } else if (beliefTerm instanceof Inheritance) { detachmentWithVar(taskSentence, belief, tLink.getIndex(0), memory); } } else if (taskTerm instanceof Equivalence) { if (beliefTerm instanceof Implication) { figure = indexToFigure(bLink, tLink); asymmetricSymmetric(belief, taskSentence, figure, memory); } else if (beliefTerm instanceof Equivalence) { figure = indexToFigure(bLink, tLink); symmetricSymmetric(belief, taskSentence, figure, memory); } else if (beliefTerm instanceof Inheritance) { detachmentWithVar(taskSentence, belief, tLink.getIndex(0), memory); } } } /** * Decide the figure of syllogism according to the locations of the common * term in the premises * * @param link1 The link to the first premise * @param link2 The link to the second premise * @return The figure of the syllogism, one of the four: 11, 12, 21, or 22 */ private static int indexToFigure(TermLink link1, TermLink link2) { return (link1.getIndex(0) + 1) * 10 + (link2.getIndex(0) + 1); } /** * Syllogistic rules whose both premises are on the same asymmetric relation * * @param sentence The taskSentence in the task * @param belief The judgment in the belief * @param figure The location of the shared term * @param memory Reference to the memory */ private static void asymmetricAsymmetric(Sentence sentence, Sentence belief, int figure, Memory memory) { Statement s1 = (Statement) sentence.cloneContent(); Statement s2 = (Statement) belief.cloneContent(); Term t1, t2; switch (figure) { case 11: // induction if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getSubject(), s2.getSubject(), s1, s2)) { if (s1.equals(s2)) { return; } t1 = s2.getPredicate(); t2 = s1.getPredicate(); CompositionalRules.composeCompound(s1, s2, 0, memory); SyllogisticRules.abdIndCom(t1, t2, sentence, belief, figure, memory); } break; case 12: // deduction if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getSubject(), s2.getPredicate(), s1, s2)) { if (s1.equals(s2)) { return; } t1 = s2.getSubject(); t2 = s1.getPredicate(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, s1, s2)) { LocalRules.matchReverse(memory); } else { SyllogisticRules.dedExe(t1, t2, sentence, belief, memory); } } break; case 21: // exemplification if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getPredicate(), s2.getSubject(), s1, s2)) { if (s1.equals(s2)) { return; } t1 = s1.getSubject(); t2 = s2.getPredicate(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, s1, s2)) { LocalRules.matchReverse(memory); } else { SyllogisticRules.dedExe(t1, t2, sentence, belief, memory); } } break; case 22: // abduction if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getPredicate(), s2.getPredicate(), s1, s2)) { if (s1.equals(s2)) { return; } t1 = s1.getSubject(); t2 = s2.getSubject(); if (!SyllogisticRules.conditionalAbd(t1, t2, s1, s2, memory)) { // if conditional abduction, skip the following CompositionalRules.composeCompound(s1, s2, 1, memory); SyllogisticRules.abdIndCom(t1, t2, sentence, belief, figure, memory); } } break; default: } } /** * Syllogistic rules whose first premise is on an asymmetric relation, and * the second on a symmetric relation * * @param asym The asymmetric premise * @param sym The symmetric premise * @param figure The location of the shared term * @param memory Reference to the memory */ private static void asymmetricSymmetric(Sentence asym, Sentence sym, int figure, Memory memory) { Statement asymSt = (Statement) asym.cloneContent(); Statement symSt = (Statement) sym.cloneContent(); Term t1, t2; switch (figure) { case 11: if (Variable.unify(Symbols.VAR_INDEPENDENT, asymSt.getSubject(), symSt.getSubject(), asymSt, symSt)) { t1 = asymSt.getPredicate(); t2 = symSt.getPredicate(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, asymSt, symSt)) { LocalRules.matchAsymSym(asym, sym, figure, memory); } else { SyllogisticRules.analogy(t2, t1, asym, sym, figure, memory); } } break; case 12: if (Variable.unify(Symbols.VAR_INDEPENDENT, asymSt.getSubject(), symSt.getPredicate(), asymSt, symSt)) { t1 = asymSt.getPredicate(); t2 = symSt.getSubject(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, asymSt, symSt)) { LocalRules.matchAsymSym(asym, sym, figure, memory); } else { SyllogisticRules.analogy(t2, t1, asym, sym, figure, memory); } } break; case 21: if (Variable.unify(Symbols.VAR_INDEPENDENT, asymSt.getPredicate(), symSt.getSubject(), asymSt, symSt)) { t1 = asymSt.getSubject(); t2 = symSt.getPredicate(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, asymSt, symSt)) { LocalRules.matchAsymSym(asym, sym, figure, memory); } else { SyllogisticRules.analogy(t1, t2, asym, sym, figure, memory); } } break; case 22: if (Variable.unify(Symbols.VAR_INDEPENDENT, asymSt.getPredicate(), symSt.getPredicate(), asymSt, symSt)) { t1 = asymSt.getSubject(); t2 = symSt.getSubject(); if (Variable.unify(Symbols.VAR_QUERY, t1, t2, asymSt, symSt)) { LocalRules.matchAsymSym(asym, sym, figure, memory); } else { SyllogisticRules.analogy(t1, t2, asym, sym, figure, memory); } } break; } } /** * Syllogistic rules whose both premises are on the same symmetric relation * * @param belief The premise that comes from a belief * @param taskSentence The premise that comes from a task * @param figure The location of the shared term * @param memory Reference to the memory */ private static void symmetricSymmetric(Sentence belief, Sentence taskSentence, int figure, Memory memory) { Statement s1 = (Statement) belief.cloneContent(); Statement s2 = (Statement) taskSentence.cloneContent(); switch (figure) { case 11: if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getSubject(), s2.getSubject(), s1, s2)) { SyllogisticRules.resemblance(s1.getPredicate(), s2.getPredicate(), belief, taskSentence, figure, memory); } break; case 12: if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getSubject(), s2.getPredicate(), s1, s2)) { SyllogisticRules.resemblance(s1.getPredicate(), s2.getSubject(), belief, taskSentence, figure, memory); } break; case 21: if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getPredicate(), s2.getSubject(), s1, s2)) { SyllogisticRules.resemblance(s1.getSubject(), s2.getPredicate(), belief, taskSentence, figure, memory); } break; case 22: if (Variable.unify(Symbols.VAR_INDEPENDENT, s1.getPredicate(), s2.getPredicate(), s1, s2)) { SyllogisticRules.resemblance(s1.getSubject(), s2.getSubject(), belief, taskSentence, figure, memory); } break; } } /* ----- conditional inferences ----- */ /** * The detachment rule, with variable unification * * @param originalMainSentence The premise that is an Implication or * Equivalence * @param subSentence The premise that is the subject or predicate of the * first one * @param index The location of the second premise in the first * @param memory Reference to the memory */ private static void detachmentWithVar(Sentence originalMainSentence, Sentence subSentence, int index, Memory memory) { Sentence mainSentence = (Sentence) originalMainSentence.clone(); // for substitution Statement statement = (Statement) mainSentence.getContent(); Term component = statement.componentAt(index); Term content = subSentence.getContent(); if (((component instanceof Inheritance) || (component instanceof Negation)) && (memory.currentBelief != null)) { if (component.isConstant()) { SyllogisticRules.detachment(mainSentence, subSentence, index, memory); } else if (Variable.unify(Symbols.VAR_INDEPENDENT, component, content, statement, content)) { SyllogisticRules.detachment(mainSentence, subSentence, index, memory); } else if ((statement instanceof Implication) && (statement.getPredicate() instanceof Statement) && (memory.currentTask.getSentence().isJudgment())) { Statement s2 = (Statement) statement.getPredicate(); if (s2.getSubject().equals(((Statement) content).getSubject())) { CompositionalRules.introVarInner((Statement) content, s2, statement, memory); } CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,memory); } else if ((statement instanceof Equivalence) && (statement.getPredicate() instanceof Statement) && (memory.currentTask.getSentence().isJudgment())) { CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,memory); } } } /** * Conditional deduction or induction, with variable unification * * @param conditional The premise that is an Implication with a Conjunction * as condition * @param index The location of the shared term in the condition * @param statement The second premise that is a statement * @param side The location of the shared term in the statement * @param memory Reference to the memory */ private static void conditionalDedIndWithVar(Implication conditional, short index, Statement statement, short side, Memory memory) { CompoundTerm condition = (CompoundTerm) conditional.getSubject(); Term component = condition.componentAt(index); Term component2 = null; if (statement instanceof Inheritance) { component2 = statement; side = -1; } else if (statement instanceof Implication) { component2 = statement.componentAt(side); } if (component2 != null) { boolean unifiable = Variable.unify(Symbols.VAR_INDEPENDENT, component, component2, conditional, statement); if (!unifiable) { unifiable = Variable.unify(Symbols.VAR_DEPENDENT, component, component2, conditional, statement); } if (unifiable) { SyllogisticRules.conditionalDedInd(conditional, index, statement, side, memory); } } } /* ----- structural inferences ----- */ /** * Inference between a compound term and a component of it * * @param compound The compound term * @param component The component term * @param compoundTask Whether the compound comes from the task * @param memory Reference to the memory */ private static void compoundAndSelf(CompoundTerm compound, Term component, boolean compoundTask, Memory memory) { if ((compound instanceof Conjunction) || (compound instanceof Disjunction)) { if (memory.currentBelief != null) { CompositionalRules.decomposeStatement(compound, component, compoundTask, memory); } else if (compound.containComponent(component)) { StructuralRules.structuralCompound(compound, component, compoundTask, memory); } // } else if ((compound instanceof Negation) && !memory.currentTask.isStructural()) { } else if (compound instanceof Negation) { if (compoundTask) { StructuralRules.transformNegation(((Negation) compound).componentAt(0), memory); } else { StructuralRules.transformNegation(compound, memory); } } } /** * Inference between two compound terms * * @param taskTerm The compound from the task * @param beliefTerm The compound from the belief * @param memory Reference to the memory */ private static void compoundAndCompound(CompoundTerm taskTerm, CompoundTerm beliefTerm, Memory memory) { if (taskTerm.getClass() == beliefTerm.getClass()) { if (taskTerm.size() > beliefTerm.size()) { compoundAndSelf(taskTerm, beliefTerm, true, memory); } else if (taskTerm.size() < beliefTerm.size()) { compoundAndSelf(beliefTerm, taskTerm, false, memory); } } } /** * Inference between a compound term and a statement * * @param compound The compound term * @param index The location of the current term in the compound * @param statement The statement * @param side The location of the current term in the statement * @param beliefTerm The content of the belief * @param memory Reference to the memory */ private static void compoundAndStatement(CompoundTerm compound, short index, Statement statement, short side, Term beliefTerm, Memory memory) { Term component = compound.componentAt(index); Task task = memory.currentTask; if (component.getClass() == statement.getClass()) { if ((compound instanceof Conjunction) && (memory.currentBelief != null)) { if (Variable.unify(Symbols.VAR_DEPENDENT, component, statement, compound, statement)) { SyllogisticRules.elimiVarDep(compound, component, statement.equals(beliefTerm), memory); } else if (task.getSentence().isJudgment()) { // && !compound.containComponent(component)) { CompositionalRules.introVarInner(statement, (Statement) component, compound, memory); } else if (Variable.unify(Symbols.VAR_QUERY, component, statement, compound, statement)) { CompositionalRules.decomposeStatement(compound, component, true, memory); } } } else { // if (!task.isStructural() && task.getSentence().isJudgment()) { if (task.getSentence().isJudgment()) { if (statement instanceof Inheritance) { StructuralRules.structuralCompose1(compound, index, statement, memory); // if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) { if (!(compound instanceof SetExt || compound instanceof SetInt || compound instanceof Negation)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A --> B, A @ (A&C)} |- (A&C) --> (B&C) } else if ((statement instanceof Similarity) && !(compound instanceof Conjunction)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A <-> B, A @ (A&C)} |- (A&C) <-> (B&C) } } } /** * Inference between a component term (of the current term) and a statement * * @param compound The compound term * @param index The location of the current term in the compound * @param statement The statement * @param side The location of the current term in the statement * @param memory Reference to the memory */ private static void componentAndStatement(CompoundTerm compound, short index, Statement statement, short side, Memory memory) { // if (!memory.currentTask.isStructural()) { if (statement instanceof Inheritance) { StructuralRules.structuralDecompose1(compound, index, statement, memory); if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) { StructuralRules.structuralDecompose2(statement, index, memory); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B } else { StructuralRules.transformSetRelation(compound, statement, side, memory); } } else if (statement instanceof Similarity) { StructuralRules.structuralDecompose2(statement, index, memory); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B if ((compound instanceof SetExt) || (compound instanceof SetInt)) { StructuralRules.transformSetRelation(compound, statement, side, memory); } } else if ((statement instanceof Implication) && (compound instanceof Negation)) { if (index == 0) { StructuralRules.contraposition(statement, memory.currentTask.getSentence(), memory); } else { StructuralRules.contraposition(statement, memory.currentBelief, memory); } } // } } /* ----- inference with one TaskLink only ----- */ /** * The TaskLink is of type TRANSFORM, and the conclusion is an equivalent * transformation * * @param tLink The task link * @param memory Reference to the memory */ public static void transformTask(TaskLink tLink, Memory memory) { CompoundTerm content = (CompoundTerm) memory.currentTask.getContent().clone(); short[] indices = tLink.getIndices(); Term inh = null; if ((indices.length == 2) || (content instanceof Inheritance)) { // <(*, term, #) --> #> inh = content; } else if (indices.length == 3) { // <<(*, term, #) --> #> ==> #> inh = content.componentAt(indices[0]); } else if (indices.length == 4) { // <(&&, <(*, term, #) --> #>, #) ==> #> Term component = content.componentAt(indices[0]); if ((component instanceof Conjunction) && (((content instanceof Implication) && (indices[0] == 0)) || (content instanceof Equivalence))) { inh = ((CompoundTerm) component).componentAt(indices[1]); } else { return; } } if (inh instanceof Inheritance) { StructuralRules.transformProductImage((Inheritance) inh, content, indices, memory); } } }
Dnmrk4/codewars-8kyu
Beginner - Reduce but Grow.js
<filename>Beginner - Reduce but Grow.js /* Description: Given a non-empty array of integers, return the result of multiplying the values together in order. Example: [1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24 */ const grow=x=> x.reduce((a,b) => a*b);
benravago/fx.html
testsuite/src/domts/level2/html/HTML_Table_Element_23_Test.java
<gh_stars>0 package domts.level2.html; import org.w3c.dom.*; import org.w3c.dom.html.*; import java.util.*; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; /** * The createTFoot() method creates a table footer row or returns * an existing one. * Try to create a new TFOOT element on the second TABLE element. * Since a TFOOT element already exists in the TABLE element a new * TFOOT element is not created and information from the already * existing TFOOT element is returned. * @author NIST * @author <NAME> * @see <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-8453710">http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-8453710</a> */ class HTML_Table_Element_23_Test extends domts.DOMTestCase { @BeforeEach void setup() { // check if loaded documents are supported for content type String contentType = getContentType(); preload(contentType, "table", true); } @Test @DisplayName("http://www.w3.org/2001/DOM_Test_Suite/level2/html/HTMLTableElement23") void run() throws Throwable { NodeList nodeList; Node testNode; HTMLTableSectionElement vsection; HTMLElement newFoot; String valign; Document doc; doc = (Document) load("table", true); nodeList = doc.getElementsByTagName("table"); assertTrue(equalsSize(3, nodeList), "Asize"); testNode = nodeList.item(1); newFoot = ((HTMLTableElement) /*Node */testNode).createTFoot(); vsection = ((HTMLTableElement) /*Node */testNode).getTFoot(); valign = vsection.getAlign(); assertEquals("center", valign, "alignLink"); } }
shin32125/chromium_webview
java/src/com/mogoweb/chrome/impl/WebBackForwardListChromium.java
// Copyright (c) 2013 mogoweb. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mogoweb.chrome.impl; import java.util.ArrayList; import java.util.List; import org.chromium.content.browser.NavigationHistory; import com.mogoweb.chrome.WebBackForwardList; import com.mogoweb.chrome.WebHistoryItem; /** * WebView Chromium implementation of WebBackForwardList. Simple immutable * wrapper around NavigationHistory. */ public class WebBackForwardListChromium extends WebBackForwardList { private List<WebHistoryItemChromium> mHistoryItemList; private int mCurrentIndex; public WebBackForwardListChromium(NavigationHistory nav_history) { mCurrentIndex = nav_history.getCurrentEntryIndex(); mHistoryItemList = new ArrayList<WebHistoryItemChromium>(nav_history.getEntryCount()); for (int i = 0; i < nav_history.getEntryCount(); ++i) { mHistoryItemList.add( new WebHistoryItemChromium(nav_history.getEntryAtIndex(i))); } } /** * See {@link android.webkit.WebBackForwardList#getCurrentItem}. */ @Override public synchronized WebHistoryItem getCurrentItem() { if (getSize() == 0) { return null; } else { return getItemAtIndex(getCurrentIndex()); } } /** * See {@link android.webkit.WebBackForwardList#getCurrentIndex}. */ @Override public synchronized int getCurrentIndex() { return mCurrentIndex; } /** * See {@link android.webkit.WebBackForwardList#getItemAtIndex}. */ @Override public synchronized WebHistoryItem getItemAtIndex(int index) { if (index < 0 || index >= getSize()) { return null; } else { return mHistoryItemList.get(index); } } /** * See {@link android.webkit.WebBackForwardList#getSize}. */ @Override public synchronized int getSize() { return mHistoryItemList.size(); } // Clone constructor. private WebBackForwardListChromium(List<WebHistoryItemChromium> list, int currentIndex) { mHistoryItemList = list; mCurrentIndex = currentIndex; } /** * See {@link android.webkit.WebBackForwardList#clone}. */ @Override public synchronized WebBackForwardList clone() { List<WebHistoryItemChromium> list = new ArrayList<WebHistoryItemChromium>(getSize()); for (int i = 0; i < getSize(); ++i) { list.add(mHistoryItemList.get(i).clone()); } return new WebBackForwardListChromium(list, mCurrentIndex); } }
aroundble/onap
catalog-be/src/test/java/org/openecomp/sdc/be/components/merge/resource/ResourceDataMergeBusinessLogicTest.java
package org.openecomp.sdc.be.components.merge.resource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.openecomp.sdc.be.components.merge.instance.ComponentsMergeCommand; import org.openecomp.sdc.be.components.utils.ObjectGenerator; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.Resource; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ResourceDataMergeBusinessLogicTest { @InjectMocks private ResourceDataMergeBusinessLogic testInstance; @Mock private ComponentsMergeCommand commandA; @Mock private ComponentsMergeCommand commandB; @Mock private ComponentsMergeCommand commandC; @Before public void setUp() throws Exception { testInstance = new ResourceDataMergeBusinessLogic(Arrays.asList(commandA, commandB, commandC)); } @Test public void mergeResources_allMergeClassesAreCalled() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); when(commandB.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); when(commandC.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.OK); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.OK, actionStatus); } @Test public void mergeResources_mergeCommandFailed_dontCallOtherMergeMethods() { Resource oldResource = ObjectGenerator.buildBasicResource(); Resource newResource = ObjectGenerator.buildBasicResource(); when(commandA.mergeComponents(oldResource, newResource)).thenReturn(ActionStatus.GENERAL_ERROR); ActionStatus actionStatus = testInstance.mergeResourceEntities(oldResource, newResource); assertEquals(ActionStatus.GENERAL_ERROR, actionStatus); verify(commandA).description(); verifyZeroInteractions(commandB, commandC); } }
lechium/iOS1351Headers
System/Library/PrivateFrameworks/NewsFoundation.framework/NFResolver.h
<filename>System/Library/PrivateFrameworks/NewsFoundation.framework/NFResolver.h /* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:37:40 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/NewsFoundation.framework/NewsFoundation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ @protocol NFResolver <NSObject> @required -(id)resolveProtocol:(id)arg1; -(id)resolveClass:(Class)arg1 name:(id)arg2; -(id)resolveProtocol:(id)arg1 name:(id)arg2; -(id)resolveForKey:(id)arg1; -(id)currentObjectGraphResolver:(unsigned long long)arg1; -(void)linkResolverWithLinkBlock:(/*^block*/id)arg1; -(id)resolveClass:(Class)arg1; -(id)resolveClass:(Class)arg1 contextBlock:(/*^block*/id)arg2; -(id)resolveClass:(Class)arg1 name:(id)arg2 contextBlock:(/*^block*/id)arg3; -(id)resolveProtocol:(id)arg1 contextBlock:(/*^block*/id)arg2; -(id)resolveProtocol:(id)arg1 name:(id)arg2 contextBlock:(/*^block*/id)arg3; -(id)resolveForKey:(id)arg1 context:(id)arg2; -(id)unsafeResolveForKey:(id)arg1 name:(id)arg2; -(id)unsafeResolveForKey:(id)arg1 name:(id)arg2 context:(id)arg3; @end
crowlogic/JPlotter
jplotter/src/main/java/hageldave/jplotter/color/ColorScheme.java
<filename>jplotter/src/main/java/hageldave/jplotter/color/ColorScheme.java package hageldave.jplotter.color; import java.awt.Color; /** * The ColorScheme is responsible for storing and providing color information, * which other components can use. This enables an easy way to distribute color * information to multiple components. There is the option to use one of the * predefined {@link DefaultColorScheme} or to define custom colors. The color * scheme contains five different color attributes, which can be accessed by the * respective components. * * @author lucareichmann */ public class ColorScheme { protected final int color1; protected final int color2; protected final int color3; protected final int color4; protected final int colorText; protected final int colorBackground; /** * Constructor for defining a new color scheme. * * @param primaryColor primary color of the color scheme * @param secondaryColor secondary color of the color scheme * @param tertiaryColor tertiary color of the color scheme * @param quaternaryColor quarternary color of the color scheme * @param textColor text color of the color scheme * @param backgroundColor the background color */ public ColorScheme(Color primaryColor, Color secondaryColor, Color tertiaryColor, Color quaternaryColor, Color textColor, Color backgroundColor) { this(primaryColor.getRGB(), secondaryColor.getRGB(), tertiaryColor.getRGB(), quaternaryColor.getRGB(), textColor.getRGB(), backgroundColor.getRGB()); } /** * Constructor for defining a new color scheme. * * @param primaryColor primary color of the color scheme (integer packed * ARGB) * @param secondaryColor secondary color of the color scheme (integer packed * ARGB) * @param tertiaryColor tertiary color of the color scheme (integer packed * ARGB) * @param quaternaryColor quarternary color of the color scheme (integer packed * ARGB) * @param textColor text color of the color scheme (integer packed ARGB) * @param backgroundColor the background color (integer packed ARGB) */ public ColorScheme(int primaryColor, int secondaryColor, int tertiaryColor, int quaternaryColor, int textColor, int backgroundColor) { this.color1 = primaryColor; this.color2 = secondaryColor; this.color3 = tertiaryColor; this.color4 = quaternaryColor; this.colorText = textColor; this.colorBackground = backgroundColor; } /** * @return primary color of the color scheme (integer packed ARGB) */ public int getColor1() { return this.color1; } /** * @return secondary color of the color scheme (integer packed ARGB) */ public int getColor2() { return this.color2; } /** * @return tertiary color of the color scheme (integer packed ARGB) */ public int getColor3() { return this.color3; } /** * @return fourth color of the color scheme (integer packed ARGB) */ public int getColor4() { return this.color4; } /** * @return text color of the color scheme (integer packed ARGB) */ public int getColorText() { return this.colorText; } /** * @return background color of the scheme (integer packed ARGB) */ public int getColorBackground() { return colorBackground; } }
pandboy/pingguopai
src/main/java/com/xfl/pingguopai/security/auth/AuthenticationFailureHandler.java
<filename>src/main/java/com/xfl/pingguopai/security/auth/AuthenticationFailureHandler.java package com.xfl.pingguopai.security.auth; import com.alibaba.fastjson.JSON; import com.xfl.pingguopai.common.Result; import com.xfl.pingguopai.common.ResultCode; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by timely */ @Component public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { Result result = new Result(); result.setCode(ResultCode.UNAUTHORIZED); String errorMesg = exception.getMessage(); if (exception instanceof BadCredentialsException) { errorMesg = "用户名或密码错误"; } result.setMessage(errorMesg); //response.sendError(401, ); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "application/json;charset=UTF-8"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try { response.getWriter().write(JSON.toJSONString(result)); } catch (IOException ex) { logger.error(ex.getMessage()); } //super.onAuthenticationFailure(request, response, exception); } }
krmao/lib_ios_base
LibIosBase/Classes/LibraryBase/STBaseViewController.h
<gh_stars>0 // // Created by krmao on 2020/5/26. // Copyright (c) 2020 smart. All rights reserved. // #import <Foundation/Foundation.h> @interface STBaseViewController : UIViewController @end
npocmaka/Windows-Server-2003
base/ntsetup/spsetup/runtime/log/sysprim.cpp
/*++ Copyright (c) 2001 Microsoft Corporation Abstract: Environment independed system functions implementation for Win32, Author: <NAME> (sourenag) 24-Sep-2001 Revision History: <alias> <date> <comments> --*/ #include "pch.h" #include "sysfunc.h" #include "functions.h" #include "windows.h" MY_OPENMUTEX g_OpenMutex = NULL; MY_CREATEMUTEX g_CreateMutex = NULL; MY_RELEASEMUTEX g_ReleaseMutex = NULL; MY_WAITFORSINGLEOBJECT g_WaitForSingleObject = NULL; MY_CLOSEHANDLE g_CloseHandle = NULL; MY_OPENSHAREDMEMORY g_OpenSharedMemory = NULL; MY_CREATESHAREDMEMORY g_CreateSharedMemory = NULL; MY_MAPSHAREDMEMORY g_MapSharedMemory = NULL; MY_UNMAPSHAREDMEMORY g_UnMapSharedMemory = NULL; MY_CREATESHAREDFILE g_CreateSharedFile = NULL; MY_SETFILEPOINTER g_SetFilePointer = NULL; MY_WRITEFILE g_WriteFile = NULL; MY_GETPROCESSORNUMBER g_GetProcessorsNumber = NULL; VOID ReleaseMutexWin32(HANDLE hObject) { ReleaseMutex(hObject); } DWORD WaitForSingleObjectWin32(HANDLE hObject, DWORD dwTimeout) { return WaitForSingleObject(hObject, dwTimeout); } VOID CloseHandleWin32(HANDLE hObject) { CloseHandle(hObject); } PVOID MapSharedMemoryWin32(HANDLE hObject) { return MapViewOfFile(hObject, FILE_MAP_ALL_ACCESS, 0, 0, 0); } BOOL UnMapSharedMemoryWin32(PVOID pSharedMemory) { return UnmapViewOfFile(pSharedMemory); } BOOL SetFilePointerWin32(HANDLE hObject, UINT uiOffset, DWORD dwMoveMethod) { return SetFilePointer(hObject, uiOffset, NULL, dwMoveMethod); } BOOL WriteFileWin32(HANDLE hObject, PVOID pBuffer, UINT uiNumberOfBytesToWrite, DWORD * pdwNumberOfBytesWritten) { return WriteFile(hObject, pBuffer, uiNumberOfBytesToWrite, pdwNumberOfBytesWritten, NULL); } // // Ansi version // HANDLE OpenMutexWin32A(PCWSTR pObjectName) { ASSERT(pObjectName); CBuffer buffer;buffer.Allocate(wcslen(pObjectName) + 2); PSTR pBuffer = (PSTR)buffer.GetBuffer(); sprintf(pBuffer, "%S", pObjectName); return OpenMutexA(MUTEX_ALL_ACCESS, FALSE, pBuffer); } HANDLE CreateMutexWin32A(PCWSTR pObjectName, BOOL bInitialOwnership) { ASSERT(pObjectName); CBuffer buffer;buffer.Allocate(wcslen(pObjectName) + 2); PSTR pBuffer = (PSTR)buffer.GetBuffer(); sprintf(pBuffer, "%S", pObjectName); return CreateMutexA(NULL, bInitialOwnership, pBuffer); } HANDLE OpenSharedMemoryWin32A(PCWSTR pObjectName) { ASSERT(pObjectName); CBuffer buffer;buffer.Allocate(wcslen(pObjectName) + 2); PSTR pBuffer = (PSTR)buffer.GetBuffer(); sprintf(pBuffer, "%S", pObjectName); return OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, pBuffer); } HANDLE CreateSharedMemoryWin32A(UINT uiInitialSizeOfMapView, PCWSTR pObjectName) { ASSERT(pObjectName); CBuffer buffer;buffer.Allocate(wcslen(pObjectName) + 2); PSTR pBuffer = (PSTR)buffer.GetBuffer(); sprintf(pBuffer, "%S", pObjectName); return CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT, 0, uiInitialSizeOfMapView, pBuffer); } HANDLE CreateSharedFileWin32A( IN PCWSTR pFilePath, IN DWORD dwShareMode, IN DWORD dwCreationDisposition, IN DWORD dwFlagsAndAttributes ) { ASSERT(pFilePath); CBuffer buffer;buffer.Allocate(wcslen(pFilePath) + 2); PSTR pAnsiFilePath = (PSTR)buffer.GetBuffer(); sprintf(pAnsiFilePath, "%S", pFilePath); return CreateFileA(pAnsiFilePath, GENERIC_WRITE | GENERIC_READ, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); } // // Unicode version // HANDLE OpenMutexWin32W(PCWSTR pObjectName) { ASSERT(pObjectName); return OpenMutexW(MUTEX_ALL_ACCESS, FALSE, pObjectName); } HANDLE CreateMutexWin32W(PCWSTR pObjectName, BOOL bInitialOwnership) { ASSERT(pObjectName); return CreateMutexW(NULL, bInitialOwnership, pObjectName); } HANDLE OpenSharedMemoryWin32W(PCWSTR pObjectName) { ASSERT(pObjectName); return OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, pObjectName); } HANDLE CreateSharedMemoryWin32W(UINT uiInitialSizeOfMapView, PCWSTR pObjectName) { ASSERT(pObjectName); return CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT, 0, uiInitialSizeOfMapView, pObjectName); } HANDLE CreateSharedFileWin32W( IN PCWSTR pFilePath, IN DWORD dwShareMode, IN DWORD dwCreationDisposition, IN DWORD dwFlagsAndAttributes ) { ASSERT(pFilePath); return CreateFileW(pFilePath, GENERIC_WRITE | GENERIC_READ, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); } BOOL IsSystemNT( VOID ) { static BOOL bSystemIsNT = FALSE; static BOOL bFirstTime = TRUE; if(bFirstTime){ bFirstTime = FALSE; bSystemIsNT = (GetVersion() < 0x80000000); } return bSystemIsNT; } UINT GetProcessorsNumberWin32( VOID ) { SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); return systemInfo.dwNumberOfProcessors; } BOOL InitSystemFunctions() { if(IsSystemNT()){ g_OpenMutex = OpenMutexWin32W; g_CreateMutex = CreateMutexWin32W; g_OpenSharedMemory = OpenSharedMemoryWin32W; g_CreateSharedMemory = CreateSharedMemoryWin32W; g_CreateSharedFile = CreateSharedFileWin32W; } else{ g_OpenMutex = OpenMutexWin32A; g_CreateMutex = CreateMutexWin32A; g_OpenSharedMemory = OpenSharedMemoryWin32A; g_CreateSharedMemory = CreateSharedMemoryWin32A; g_CreateSharedFile = CreateSharedFileWin32A; } g_ReleaseMutex = ReleaseMutexWin32; g_WaitForSingleObject = WaitForSingleObjectWin32; g_CloseHandle = CloseHandleWin32; g_MapSharedMemory = MapSharedMemoryWin32; g_UnMapSharedMemory = UnMapSharedMemoryWin32; g_SetFilePointer = SetFilePointerWin32; g_WriteFile = WriteFileWin32; g_GetProcessorsNumber = GetProcessorsNumberWin32; return TRUE; } BOOL bInit = InitSystemFunctions();
shybzzz/ESP-1ch-Gateway
lib/ArduinoJson/extras/tests/JsonVariant/createNested.cpp
<reponame>shybzzz/ESP-1ch-Gateway // ArduinoJson - arduinojson.org // Copyright <NAME> 2014-2020 // MIT License #include <ArduinoJson.h> #include <stdint.h> #include <catch.hpp> TEST_CASE("JsonVariant::createNestedObject()") { DynamicJsonDocument doc(4096); JsonVariant variant = doc.to<JsonVariant>(); SECTION("promotes to array") { JsonObject obj = variant.createNestedObject(); obj["value"] = 42; REQUIRE(variant.is<JsonArray>() == true); REQUIRE(variant[0]["value"] == 42); REQUIRE(obj.isNull() == false); } SECTION("works on MemberProxy") { JsonObject obj = variant["items"].createNestedObject(); obj["value"] = 42; REQUIRE(variant["items"][0]["value"] == 42); } } TEST_CASE("JsonVariant::createNestedArray()") { DynamicJsonDocument doc(4096); JsonVariant variant = doc.to<JsonVariant>(); SECTION("promotes to array") { JsonArray arr = variant.createNestedArray(); REQUIRE(variant.is<JsonArray>() == true); REQUIRE(arr.isNull() == false); } SECTION("works on MemberProxy") { JsonArray arr = variant["items"].createNestedArray(); arr.add(42); REQUIRE(variant["items"][0][0] == 42); } } TEST_CASE("JsonVariant::createNestedObject(key)") { DynamicJsonDocument doc(4096); JsonVariant variant = doc.to<JsonVariant>(); SECTION("promotes to object") { JsonObject obj = variant.createNestedObject("weather"); obj["temp"] = 42; REQUIRE(variant.is<JsonObject>() == true); REQUIRE(variant["weather"]["temp"] == 42); } SECTION("works on MemberProxy") { JsonObject obj = variant["status"].createNestedObject("weather"); obj["temp"] = 42; REQUIRE(variant["status"]["weather"]["temp"] == 42); } } TEST_CASE("JsonVariant::createNestedArray(key)") { DynamicJsonDocument doc(4096); JsonVariant variant = doc.to<JsonVariant>(); SECTION("promotes to object") { JsonArray arr = variant.createNestedArray("items"); REQUIRE(variant.is<JsonObject>() == true); REQUIRE(arr.isNull() == false); } SECTION("works on MemberProxy") { JsonArray arr = variant["weather"].createNestedArray("temp"); arr.add(42); REQUIRE(variant["weather"]["temp"][0] == 42); } }