repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
TooDumbForAName/modern-boot-floppy
syslinux/core/fs/pxe/idle.c
<filename>syslinux/core/fs/pxe/idle.c /* ----------------------------------------------------------------------- * * * Copyright 2008 <NAME> - All Rights Reserved * Copyright 2009 Intel Corporation; author: <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston MA 02110-1301, USA; either version 2 of the License, or * (at your option) any later version; incorporated herein by reference. * * ----------------------------------------------------------------------- */ #include <stdio.h> #include <string.h> #include <core.h> #include <fs.h> #include <minmax.h> #include <sys/cpu.h> #include "pxe.h" void pxe_idle_init(void) { } void pxe_idle_cleanup(void) { idle_hook_func = NULL; }
aadps/kaldi
src/pybind/chain/chain_den_graph_pybind.cc
// pybind/chain/chain_den_graph_pybind.cc // Copyright 2019 Microsoft Corporation (author: <NAME>) // See ../../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "chain/chain_pybind.h" #include "chain/chain-den-graph.h" #include "fst/vector_fst_pybind.h" using namespace fst; using namespace kaldi::chain; void pybind_chain_den_graph(py::module& m) { using PyClass = DenominatorGraph; py::class_<PyClass>(m, "DenominatorGraph", "This class is responsible for storing the FST that we use as the" "'anti-model' or 'denominator-model', that models all possible phone" "sequences (or most possible phone sequences, depending how we built it).." "It stores the FST in a format where we can access both the transitions out" "of each state, and the transitions into each state.") .def(py::init<const StdVectorFst&, int>(), "Initialize from epsilon-free acceptor FST with pdf-ids plus one as the" "labels. 'num_pdfs' is only needeed for checking.", py::arg("fst"), py::arg("num_pdfs")); }
webdeveloper0012/Chain-link
spec/models/assignment_snapshot_spec.rb
describe AssignmentSnapshot, type: :model do describe "validations" do it { is_expected.to have_valid(:assignment).when(factory_create(:assignment)) } it { is_expected.not_to have_valid(:assignment).when(nil) } it { is_expected.to have_valid(:details).when(nil, '', {a: 1}) } it { is_expected.to have_valid(:progress).when(nil, 'started', 'completed', 'failed') } it { is_expected.not_to have_valid(:progress).when('', 'foo') } it { is_expected.to have_valid(:requester).when(nil, factory_create(:subtask)) } it { is_expected.to have_valid(:status).when(nil, 'in progress', 'completed', 'failed') } it { is_expected.not_to have_valid(:status).when('', 'foo') } it { is_expected.to have_valid(:xid).when(nil, SecureRandom.uuid) } it { is_expected.not_to have_valid(:xid).when('') } it { is_expected.to have_valid(:summary).when('anything', 'foo', nil, '') } context "when the snapshot is fulfilled" do subject { AssignmentSnapshot.new fulfilled: true } it { is_expected.to have_valid(:summary).when('anything', 'foo') } it { is_expected.not_to have_valid(:summary).when(nil, '') } end it { is_expected.to have_valid(:value).when(nil, '', SecureRandom.base64) } end describe "on create" do let(:snapshot) { factory_build :assignment_snapshot, assignment: assignment } let!(:assignment) { factory_create :assignment } let!(:adapter) { assignment.adapters.first } let(:adapter_response) do { fulfilled: false, xid: snapshot.xid, } end it "generates an external ID" do expect { snapshot.save }.to change { snapshot.xid }.from(nil) end it "sets the progress to started" do expect { snapshot.save }.to change { snapshot.progress }.from(nil).to(AssignmentSnapshot::STARTED) end context "with adapters" do before do factory_create :subtask, assignment: assignment factory_create :subtask, assignment: assignment factory_create :subtask, assignment: assignment assignment.reload allow_any_instance_of(AdapterSnapshot).to receive(:start) end it "creates an adapter snapshot for each adapter of the assignment" do expect { snapshot.save }.to change { snapshot.adapter_snapshots.count }.by(assignment.adapters.size) end it "sets the adapter index to the first possible" do expect { snapshot.save }.to change { snapshot.adapter_index }.from(nil).to(assignment.subtasks.first.index) end it "starts the adapter snapshot subtask processes" do expect_any_instance_of(AdapterSnapshot).to receive(:start) do |adapter_snapshot| expect(adapter_snapshot).to eq(snapshot.current_adapter_snapshot) end snapshot.save end end context "when the snapshot already has an external ID" do let(:xid) { SecureRandom.uuid } before { snapshot.xid = xid } it "generates an external ID" do expect { snapshot.save }.not_to change { snapshot.xid }.from(xid) end end end describe "on save" do let!(:snapshot) { factory_create :assignment_snapshot, fulfilled: pre_fulfilled } context "when the snapshot is already fulfilled" do let(:pre_fulfilled) { true } context "and it is marked as fulfilled" do it "does NOT notify the coordinator" do expect_any_instance_of(CoordinatorClient).not_to receive(:snapshot) snapshot.update_attributes details: {foo: SecureRandom.base64}, fulfilled: true end end context "and it is marked as unfulfilled" do it "does NOT notify the coordinator" do expect_any_instance_of(CoordinatorClient).not_to receive(:snapshot) response = snapshot.update_attributes({ details: {foo: SecureRandom.base64}, fulfilled: false }) expect(response).to be_falsey end end end context "when the snapshot is not already fulfilled" do let(:pre_fulfilled) { false } context "and it is marked as fulfilled" do it "does notify the coordinator" do expect(snapshot.assignment.coordinator).to receive(:snapshot) .with(snapshot.id) snapshot.update_attributes details: {foo: SecureRandom.base64}, fulfilled: true end end context "and it is marked as unfulfilled" do it "does NOT notify the coordinator" do expect_any_instance_of(CoordinatorClient).not_to receive(:snapshot) snapshot.update_attributes details: {foo: SecureRandom.base64}, fulfilled: false end end end end describe "#current_adapter_snapshot" do let(:snapshot) { factory_create :assignment_snapshot } let!(:adapter_snapshot1) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } let!(:adapter_snapshot2) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } let!(:adapter_snapshot3) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } before do snapshot.reload.update_attributes(adapter_index: adapter_snapshot2.index) end it "returns the adapter snapshot that matches the index" do expect(snapshot.current_adapter_snapshot).to eq(adapter_snapshot2) end end describe "#current_adapter_snapshot" do let(:snapshot) { factory_create :assignment_snapshot } let!(:adapter_snapshot1) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } let!(:adapter_snapshot2) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } let!(:adapter_snapshot3) { factory_create :adapter_snapshot, assignment_snapshot: snapshot } before do snapshot.reload.update_attributes(adapter_index: adapter_snapshot1.index) end it "returns the next adapter snapshot above the current index" do expect(snapshot.next_adapter_snapshot).to eq(adapter_snapshot2) end end describe "#adapter_response" do let!(:snapshot) { factory_create :assignment_snapshot } let!(:adapter_snapshot) { factory_create :adapter_snapshot } let(:handler) { instance_double AssignmentSnapshotHandler } before do allow(AssignmentSnapshotHandler).to receive(:new) .with(snapshot) .and_return(handler) end it "passes the response on to a handler" do expect_any_instance_of(AssignmentSnapshotHandler).to receive(:adapter_response) .with(adapter_snapshot) snapshot.adapter_response(adapter_snapshot) end end end
kozborn/programing-principles-and-practise-using-cpp
Chapter11/chapter11-2-5.cpp
#include "../std_lib_facilities.h" struct Person { string name; string lastName; string email; Person(string n, string ln, string e): name(n), lastName(ln), email(e) {} }; ostream& operator<<(ostream& os, const Person& p) { // left is for left align os << left << setw(10) << p.name << setw(15) << p.lastName << setw(30) << p.email; } int main() { try { cout << "Program for setting with of field when outputting text" << endl; Person p1("Piotr", "Kozubek", "<EMAIL>"); Person p2("Anna", "Kozubek", "<EMAIL>"); Person p3("Grzegorz", "Purgal", "<EMAIL>"); Person p4("Ievgen", "Martynov", "<EMAIL>"); Person p5("Artur", "Nowak", "<EMAIL>"); cout << p1 << endl; cout << p2 << endl; cout << p3 << endl; cout << p4 << endl; cout << p5 << endl; } catch(...) { cout << "Something went very bad" << endl; } return 0; }
muathendirangu/design-patterns-using-java
src/com/muathendirangu/structural/decorator/ChristmasTree.java
package com.muathendirangu.structural.decorator; public interface ChristmasTree { String Decorate(); }
uni-hamburg/renew-js
src/features/pointer/tools/PointerTool.js
<reponame>uni-hamburg/renew-js<filename>src/features/pointer/tools/PointerTool.js<gh_stars>0 import { Tool } from '../../../core/toolbox/Tool'; import { CardinalOrientation } from '../../orientation/CardinalOrientation'; export class PointerTool extends Tool { constructor (eventBus, rulePolicy, toolbox, selection) { super(); this.eventBus = eventBus; this.rulePolicy = rulePolicy; this.toolbox = toolbox; this.selection = selection; this.isSelecting = false; this.isMoving = false; this.isResizing = false; } onDisable (event) { this.eventBus.fire('selection.clear'); this.eventBus.fire('preview.clear'); this.eventBus.fire('rubberBand.preview.clear'); } onEnable (event) { } onMouseDown (event) { event.elements = this.selection.get(); if (event.hover && event.hover.type === 'handle') { this.isResizing = event.hover.orientation.direction; this.eventBus.fire('resize.element.init', event); } else { if (event.hover && !event.originalEvent.ctrlKey) { this.eventBus.fire('pointer.select', event); } if (event.hover && event.originalEvent.ctrlKey) { this.eventBus.fire('pointer.appendselect', event); } event.elements = this.selection.get(); if (event.hover) { if (event.rootStart) { this.isSelecting = true; } else { const context = { elements: event.elements }; if (this.rulePolicy.allowed('move.elements', context)) { this.eventBus.fire('move.preview.init', event); this.isMoving = true; } } } } } onMouseMove (event) { event.elements = this.selection.get(); if (event.mouseDown) { if (this.isMoving) { this.eventBus.fire('preview.move', event); } else if (this.isSelecting) { this.eventBus.fire('rubberBand.preview', event); } else if (this.isResizing) { switch (this.isResizing) { case CardinalOrientation.NORTH_WEST: this.eventBus.fire('resize.element.nw', event, true); break; case CardinalOrientation.NORTH_EAST: this.eventBus.fire('resize.element.ne', event, true); break; case CardinalOrientation.SOUTH_EAST: this.eventBus.fire('resize.element.se', event, true); break; case CardinalOrientation.SOUTH_WEST: this.eventBus.fire('resize.element.sw', event, true); break; case CardinalOrientation.NORTH: this.eventBus.fire('resize.element.n', event, true); break; case CardinalOrientation.EAST: this.eventBus.fire('resize.element.e', event, true); break; case CardinalOrientation.SOUTH: this.eventBus.fire('resize.element.s', event, true); break; case CardinalOrientation.WEST: this.eventBus.fire('resize.element.w', event, true); break; } } } } onMouseUp (event) { event.elements = this.selection.get(); if (this.isMoving) { this.eventBus.fire('move.elements.by', event, true); this.eventBus.fire('preview.clear', event); this.isMoving = false; } else if (this.isSelecting) { this.eventBus.fire('rubberBand.select', event); this.eventBus.fire('rubberBand.preview.clear', event); this.isSelecting = false; } else if (this.isResizing) { this.handleResizeCursor(event.hover); this.isResizing = false; } } onDoubleClick (event) { if (event.hover.type === 'label') { this.toolbox.activate('edit', { label: event.hover }); } } onHover (event) { if (this.isResizing) return; this.handleResizeCursor(event.element); } handleResizeCursor (element) { if (element && element.type === 'handle') { switch (element.orientation.direction) { case CardinalOrientation.NORTH_WEST: this.eventBus.fire('cursor.set.nwse'); break; case CardinalOrientation.NORTH_EAST: this.eventBus.fire('cursor.set.nesw'); break; case CardinalOrientation.SOUTH_EAST: this.eventBus.fire('cursor.set.nwse'); break; case CardinalOrientation.SOUTH_WEST: this.eventBus.fire('cursor.set.nesw'); break; case CardinalOrientation.NORTH: this.eventBus.fire('cursor.set.ns'); break; case CardinalOrientation.EAST: this.eventBus.fire('cursor.set.ew'); break; case CardinalOrientation.SOUTH: this.eventBus.fire('cursor.set.ns'); break; case CardinalOrientation.WEST: this.eventBus.fire('cursor.set.ew'); break; } } else { this.eventBus.fire('cursor.unset'); } } onOut (event) { if (this.isResizing) return; if (event.element && event.element.type === 'handle') { switch (event.element.orientation.direction) { case CardinalOrientation.NORTH_WEST: this.eventBus.fire('cursor.unset'); break; case CardinalOrientation.NORTH_EAST: this.eventBus.fire('cursor.unset'); break; case CardinalOrientation.SOUTH_EAST: this.eventBus.fire('cursor.unset'); break; case CardinalOrientation.SOUTH_WEST: this.eventBus.fire('cursor.unset'); break; } } } }
InvictrixRom/external_skia
src/sksl/ast/SkSLASTForStatement.h
<gh_stars>1-10 /* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SKSL_ASTFORSTATEMENT #define SKSL_ASTFORSTATEMENT #include "SkSLASTStatement.h" namespace SkSL { /** * A 'for' loop. */ struct ASTForStatement : public ASTStatement { ASTForStatement(Position position, std::unique_ptr<ASTStatement> initializer, std::unique_ptr<ASTExpression> test, std::unique_ptr<ASTExpression> next, std::unique_ptr<ASTStatement> statement) : INHERITED(position, kFor_Kind) , fInitializer(std::move(initializer)) , fTest(std::move(test)) , fNext(std::move(next)) , fStatement(std::move(statement)) {} String description() const override { String result("for ("); if (fInitializer) { result.append(fInitializer->description()); } result += " "; if (fTest) { result.append(fTest->description()); } result += "; "; if (fNext) { result.append(fNext->description()); } result += ") "; result += fStatement->description(); return result; } const std::unique_ptr<ASTStatement> fInitializer; const std::unique_ptr<ASTExpression> fTest; const std::unique_ptr<ASTExpression> fNext; const std::unique_ptr<ASTStatement> fStatement; typedef ASTStatement INHERITED; }; } // namespace #endif
patmbolger/shf-project
app/helpers/shf_applications_helper.rb
module ShfApplicationsHelper def can_edit_state? policy(@shf_application).permitted_attributes_for_edit.include? :state end # The AASM gem caches the display_name for a State. We cannot do that because # the I18n.locale may have changed, so we must get the localized name every time def states_selection_list ShfApplication.aasm.states.map { |state| [state.localized_name, state.name.to_s] } end def reasons_collection(other_reason_value, other_reason_text) collection = AdminOnly::MemberAppWaitingReason.all.to_a collection << AdminOnly::MemberAppWaitingReason.new(id: other_reason_value, "name_#{I18n.locale}" => "#{other_reason_text}") collection end def selected_reason_value(member_app, other_reason_value) (!member_app.custom_reason_text.blank?) ? other_reason_value : member_app.member_app_waiting_reasons_id end # the method to use to get the name for a reason, given the locale # If no locale is given, the current locale is used. # If the locale given isn't found or defined, the default name method is used def reason_name_method(locale = I18n.locale) reason_method 'name', locale end # the method to use to get the description for a reason, given the locale # If no locale is given, the current locale is used. # If the locale given isn't found or defined, the default name method is used def reason_desc_method(locale = I18n.locale) reason_method 'description', locale end # a collection of arrays with [the name of the reasons for waiting, the reason (object)] # in the locale def reasons_for_waiting_names(use_locale = I18n.locale) reasons_for_waiting_info('name', use_locale) end # a collection of arrays with [the descriptions of the reasons for waiting, the reason (object)] # in the locale def reasons_for_waiting_descs(use_locale = I18n.locale) reasons_for_waiting_info('description', use_locale) end def list_app_categories application, separator=', ' if application&.business_categories.any? application.business_categories.includes(:shf_applications) .map(&:name).sort.join(separator) end end private def reason_method(method_prefix, locale) possible_method = "#{method_prefix}_#{locale}".to_sym (AdminOnly::MemberAppWaitingReason.new.respond_to?(possible_method) ? possible_method : AdminOnly::MemberAppWaitingReason.send("default_#{method_prefix}_method".to_sym)) end def reasons_for_waiting_info(method_prefix, locale) method_name = reason_method(method_prefix, locale) AdminOnly::MemberAppWaitingReason.all.map { |r| [r.id, r.send(method_name)] } end end
CloudSlang/cs-actions
cs-maps/src/main/java/io/cloudslang/content/maps/services/ModifyMapElementsService.java
/* * (c) Copyright 2020 EntIT Software LLC, a Micro Focus company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cloudslang.content.maps.services; import io.cloudslang.content.maps.entities.ModifyMapElementsInput; import io.cloudslang.content.maps.exceptions.ValidationException; import io.cloudslang.content.maps.utils.MapSerializer; import io.cloudslang.content.maps.utils.StringMethods; import io.cloudslang.content.maps.validators.ModifyMapElementsInputValidator; import io.cloudslang.content.utils.OutputUtilities; import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.stream.Collectors; public class ModifyMapElementsService { private final ModifyMapElementsInputValidator validator = new ModifyMapElementsInputValidator(); public @NotNull Map<String, String> execute(@NotNull ModifyMapElementsInput input) throws Exception { ValidationException validationEx = validator.validate(input); if (validationEx != null) { throw validationEx; } MapSerializer serializer = new MapSerializer( input.getPairDelimiter(), input.getEntryDelimiter(), input.getMapStart(), input.getMapEnd(), input.getElementWrapper(), input.isStripWhitespaces(), false); Map<String, String> map = serializer.deserialize(input.getMap()); Map<String, String> newMap; switch (input.getElements().toLowerCase()) { case "keys": newMap = map.keySet().stream() .collect(Collectors.toMap(key -> StringMethods.execute(key, input.getMethod(), input.getValue(),input.isStripWhitespaces()), map::get)); break; case "values": newMap = map.keySet().stream() .collect(Collectors.toMap(key -> key, key -> StringMethods.execute(map.get(key), input.getMethod(), input.getValue(),input.isStripWhitespaces()))); break; default: newMap = map.keySet().stream() .collect(Collectors.toMap(key -> StringMethods.execute(key, input.getMethod(), input.getValue(),input.isStripWhitespaces()), key -> StringMethods.execute(map.get(key), input.getMethod(), input.getValue(),input.isStripWhitespaces()))); break; } String returnResult = serializer.serialize(newMap); return OutputUtilities.getSuccessResultsMap(returnResult); } }
billwert/azure-sdk-for-java
sdk/spring/spring-cloud-azure-actuator-autoconfigure/src/main/java/com/azure/spring/cloud/actuator/autoconfigure/appconfiguration/AppConfigurationHealthConfiguration.java
<filename>sdk/spring/spring-cloud-azure-actuator-autoconfigure/src/main/java/com/azure/spring/cloud/actuator/autoconfigure/appconfiguration/AppConfigurationHealthConfiguration.java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.cloud.actuator.autoconfigure.appconfiguration; import com.azure.data.appconfiguration.ConfigurationAsyncClient; import com.azure.spring.cloud.actuator.appconfiguration.AppConfigurationHealthIndicator; import com.azure.spring.cloud.autoconfigure.appconfiguration.AzureAppConfigurationAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configuration class of App Configuration Health */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ConfigurationAsyncClient.class, HealthIndicator.class }) @ConditionalOnBean(ConfigurationAsyncClient.class) @AutoConfigureAfter(AzureAppConfigurationAutoConfiguration.class) @ConditionalOnEnabledHealthIndicator("azure-appconfiguration") public class AppConfigurationHealthConfiguration { @Bean AppConfigurationHealthIndicator appconfigurationHealthIndicator(ConfigurationAsyncClient configurationAsyncClient) { return new AppConfigurationHealthIndicator(configurationAsyncClient); } }
DatabaseMasters/CrowdFundingWebsite
gulpfile.js
<filename>gulpfile.js /* globals process */ const gulp = require('gulp'); const nodemon = require('gulp-nodemon'); const istanbul = require('gulp-istanbul'); const mocha = require('gulp-mocha'); const server = require('./server'); // HACK not recommended // set port // eslint-disable-next-line no-process-env // const port = process.env.PORT || 3001; gulp.task('dev', () => { console.log('dev -------------------'); return nodemon({ ext: 'js', script: 'index.js', }).on('restart', () => { console.log('restarted -------------------'); }); }); gulp.task('pre-test', () => { return gulp.src([ './server.js', './app/**/*.js', '!./config/**/*.js', './data/**/*.js', './db/**/*.js', './models/**/*.js', ]) // to exclude folders '!./static/**' .pipe(istanbul({ includeUntested: true, })) .pipe(istanbul.hookRequire()); }); gulp.task('tests-all', ['pre-test'], (done) => { return gulp.src([ './tests/unit/**/*.js', './tests/integration/**/*.js', ]) .pipe(mocha({ reporter: 'spec', timeout: 3000, })) .pipe(istanbul.writeReports({ dir: './coverage/all', })) .on('error', () => process.exit(1)) .on('end', () => { process.exit(); }); }); gulp.task('tests-unit', ['pre-test'], () => { return gulp.src([ './tests/unit/**/*.js', ]) .pipe(mocha({ reporter: 'spec', timeout: 3000, })) .pipe(istanbul.writeReports({ dir: './coverage/unit', })) .on('error', () => process.exit(1)) .on('end', () => { process.exit(); }); }); gulp.task('tests-integration', ['pre-test'], () => { return gulp.src([ './tests/integration/**/*.js', ]) .pipe(mocha({ reporter: 'spec', timeout: 3000, })) .pipe(istanbul.writeReports({ dir: './coverage/integration', })) .on('error', () => process.exit(1)) .on('end', () => { process.exit(); }); }); const testConfig = { connectionString: 'mongodb://localhost/crowdfunding-db-test', port: 3002, }; const { MongoClient } = require('mongodb'); gulp.task('server-start', () => { return server(testConfig); }); gulp.task('server-stop', () => { return MongoClient.connect(testConfig.connectionString) .then((db) => { return db.dropDatabase(); }); }); gulp.task('tests:browser', ['server-start'], () => { return gulp.src('./tests/browser/**/*.js') .pipe(mocha({ reporter: 'spec', timeout: 10000, })) .once('error', (er) => { console.log(er); }) .once('end', () => { gulp.start('server-stop'); }); });
easyopsapis/easyops-api-go
protorepo-tool/basic/delete_tool.validator.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: delete_tool.proto package basic import ( fmt "fmt" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" _ "github.com/gogo/protobuf/types" _ "github.com/mwitkow/go-proto-validators" github_com_mwitkow_go_proto_validators "github.com/mwitkow/go-proto-validators" math "math" regexp "regexp" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf var _regex_DeleteToolRequest_VersionId = regexp.MustCompile(`^[a-fA-F0-9]{32}$`) var _regex_DeleteToolRequest_ToolId = regexp.MustCompile(`^[a-fA-F0-9]{32}$`) func (this *DeleteToolRequest) Validate() error { if !_regex_DeleteToolRequest_VersionId.MatchString(this.VersionId) { return github_com_mwitkow_go_proto_validators.FieldError("VersionId", fmt.Errorf(`value '%v' must be a string conforming to regex "^[a-fA-F0-9]{32}$"`, this.VersionId)) } if !_regex_DeleteToolRequest_ToolId.MatchString(this.ToolId) { return github_com_mwitkow_go_proto_validators.FieldError("ToolId", fmt.Errorf(`value '%v' must be a string conforming to regex "^[a-fA-F0-9]{32}$"`, this.ToolId)) } return nil } func (this *DeleteToolResponseWrapper) Validate() error { if this.Data != nil { if err := github_com_mwitkow_go_proto_validators.CallValidatorIfExists(this.Data); err != nil { return github_com_mwitkow_go_proto_validators.FieldError("Data", err) } } return nil }
antonmedv/year
packages/2019/03/29/index.js
<reponame>antonmedv/year module.exports = new Date(2019, 2, 29)
AzarguNazari/Student_Residence_Service
backend/Authorization-Server/src/main/java/srs/AuthServer/model/AuthUser.java
package srs.AuthServer.model; import java.util.Collection; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Getter; import lombok.Setter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import com.fasterxml.jackson.annotation.JsonProperty; @Setter @Getter public class AuthUser extends User { private static final long serialVersionUID = 1L; @Id @GeneratedValue @JsonProperty("id") private Integer id = null; @JsonProperty("first_name") @Column(name = "first_name") private String firstName; @JsonProperty("last_name") @Column(name = "last_name") private String lastName; private Student student; public AuthUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, Integer id, String firstName, String lastName, Student student) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); this.id = id; this.firstName = firstName; this.lastName = lastName; this.student = student; } }
dacozai/algorithm-diary
cpp/src/str/intToRoman.cpp
<gh_stars>1-10 #include "test.h" /** Question no.12 medium * Author : Li-Han, Chen; 陳立瀚 * Date : 4th, January, 2020 * Source : https://leetcode.com/problems/integer-to-roman/ * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. * * Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. * */ /** Solution * Runtime 4 ms MeMory 8.4 MB; * faster than 94.24%, less than 94.74% * O(N) O(1) */ std::string intToRoman(int num) { std::string ans=""; if (num > 3999 || num < 1) return ans; runRome(&num, ans, 1000, "M"); runRome(&num, ans, 900, "CM"); runRome(&num, ans, 500, "D"); runRome(&num, ans, 400, "CD"); runRome(&num, ans, 100, "C"); runRome(&num, ans, 90, "XC"); runRome(&num, ans, 50, "L"); runRome(&num, ans, 40, "XL"); runRome(&num, ans, 10, "X"); runRome(&num, ans, 9, "IX"); runRome(&num, ans, 5, "V"); runRome(&num, ans, 4, "IV"); runRome(&num, ans, 1, "I"); return ans; } void runRome(int *num, std::string& s, int n, std::string symbol) { while (*num>=n) { s.append(symbol); *num-=n; } }
pjbelo/WebsiteOne
experiments/landing_page_options.rb
ab_test "Landing page options" do description "Mirror, mirror on the wall, who's the better price of all?" alternatives 'text_trail','text_and_image_trail' metrics :signups, :premium_signups end
uk-gov-mirror/DFE-Digital.find-teacher-training
spec/features/courses/results_spec.rb
require 'rails_helper' describe 'Search results', type: :feature do include StubbedRequests::Courses include StubbedRequests::Subjects let(:results_page) { PageObjects::Page::Results.new } let(:base_parameters) { results_page_parameters } let(:subject) do build( :subject, :english, scholarship: '2000', bursary_amount: '4000', early_career_payments: '1000', ) end let(:accrediting_provider) { build(:provider) } let(:decorated_course) { course.decorate } let(:courses) { [course] } let(:page_index) { nil } let(:stub_courses_request) do stub_courses(query: base_parameters, course_count: 10) end before do stub_subjects stub_courses_request visit results_path(page: page_index) end it 'requests the courses' do expect(stub_courses_request).to have_been_requested end context 'multiple courses' do it 'Lists all courses' do expect(results_page.courses.count).to eq(10) results_page.courses.first.then do |first_course| expect(first_course.name.text).to eq('Geography (385N)') expect(first_course.provider_name.text).to eq('BHSSA') expect(first_course.qualification.text).to eq('PGCE with QTS') expect(first_course.study_mode.text).to eq('Full time') expect(first_course.accrediting_provider.text).to eq('University of Brighton') expect(first_course.funding_options.text).to eq('Student finance if you’re eligible') expect(first_course.main_address.text).to eq('Hove Park School, Hangleton Way, Hove, East Sussex, BN3 8AA') expect(first_course).to have_show_vacancies end end end context 'with a second page' do before do base_parameters.merge(page_index: 2) end it 'requests the second page' do expect(stub_courses_request).to have_been_requested end end end
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/ContactsUICore.framework/_CNUIUserActionUserActivityItem.h
<gh_stars>10-100 /* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:45:08 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/ContactsUICore.framework/ContactsUICore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <ContactsUICore/CNUIUserActionItem.h> @class NSUserActivity; @interface _CNUIUserActionUserActivityItem : CNUIUserActionItem { NSUserActivity* _userActivity; } @property (nonatomic,readonly) NSUserActivity * userActivity; //@synthesize userActivity=_userActivity - In the implementation block -(BOOL)_isIntent:(id)arg1 equalToOther:(id)arg2 ; -(unsigned long long)_hashForIntent:(id)arg1 ; -(id)_personFromIntent:(id)arg1 ; -(id)initWithType:(id)arg1 contactProperty:(id)arg2 bundleIdentifier:(id)arg3 userActivity:(id)arg4 group:(long long)arg5 options:(unsigned long long)arg6 ; -(id)performActionWithContext:(id)arg1 ; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)description; -(NSUserActivity *)userActivity; @end
alvaropp/AdventOfCode2017
2020/day3-2.py
import numpy as np with open("day3.txt", "r") as f: map = f.read().splitlines() moves = [ np.array([1, 1]), np.array([1, 3]), np.array([1, 5]), np.array([1, 7]), np.array([2, 1]), ] def count_trees(move): pos = np.array([0, 0]) n_lines = len(map) n_trees = 0 while pos[0] < n_lines - 1: pos[1] = np.mod(pos[1], len(map[0])) if map[pos[0]][pos[1]] == "#": n_trees += 1 pos += move return n_trees n_treess = [] for move in moves: n_treess.append(count_trees(move)) print(np.prod(n_treess))
eenurkka/incubator-nuttx
arch/arm/src/sama5/sam_serialinit.c
/**************************************************************************** * arch/arm/src/sama5/sam_serialinit.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include "sam_config.h" #include "sam_dbgu.h" #include "sam_serial.h" #ifdef USE_SERIALDRIVER /**************************************************************************** * Public Functions ****************************************************************************/ #ifdef USE_EARLYSERIALINIT /**************************************************************************** * Name: sam_earlyserialinit * * Description: * Performs the low level serial initialization early so that the serial * console will be available during bootup. This must be called * before arm_serialinit. * ****************************************************************************/ void sam_earlyserialinit(void) { /* NOTE: All PIO configuration for the USARTs was performed in * sam_lowsetup */ #if defined(SAMA5_HAVE_UART) || defined(SAMA5_HAVE_USART) /* Initialize UART/USART drivers */ uart_earlyserialinit(); #endif #ifdef SAMA5_HAVE_FLEXCOM_USART /* Initialize Flexcom USARTs */ flexus_earlyserialinit(); #endif } #endif /**************************************************************************** * Name: arm_serialinit * * Description: * Register all serial console and serial ports. This assumes * that arm_earlyserialinit was called previously. * ****************************************************************************/ void arm_serialinit(void) { #if defined(SAMA5_HAVE_UART) || defined(SAMA5_HAVE_USART) /* Register UART/USART drivers */ uart_serialinit(); #endif #ifdef SAMA5_HAVE_FLEXCOM_USART /* Register Flexcom USART drivers */ flexus_serialinit(); #endif /* Register the DBGU as well */ #ifdef CONFIG_SAMA5_DBGU sam_dbgu_register(); #endif } #endif /* USE_SERIALDRIVER */
checho651/bfx-report-ui
src/state/filters/saga.js
import { put, takeLatest, } from 'redux-saga/effects' import queryTypes from 'state/query/constants' import { getTarget } from 'state/query/utils' import uiTypes from 'state/ui/constants' import { decodeFilters } from 'state/filters/utils' import { fetchInvoices, refresh as refreshInvoices } from 'state/invoices/actions' import { fetchLedgers, refresh as refreshLedgers } from 'state/ledgers/actions' import { fetchTrades, refresh as refreshTrades } from 'state/trades/actions' import { fetchOrders, refresh as refreshOrders } from 'state/orders/actions' import { fetchMovements, refresh as refreshMovements } from 'state/movements/actions' import { fetchPositions, refresh as refreshPositions } from 'state/positions/actions' import { fetchFOffer, refresh as refreshFOffer } from 'state/fundingOfferHistory/actions' import { fetchFLoan, refresh as refreshFLoan } from 'state/fundingLoanHistory/actions' import { fetchFCredit, refresh as refreshFCredit } from 'state/fundingCreditHistory/actions' import { fetchFPayment, refresh as refreshFPayment } from 'state/fundingPayment/actions' import { fetchData as fetchSPayments, refresh as refreshSPayments } from 'state/stakingPayments/actions' import { fetchAffiliatesEarnings, refresh as refreshAffiliatesEarnings } from 'state/affiliatesEarnings/actions' import { fetchPublicTrades, refresh as refreshPublicTrades } from 'state/publicTrades/actions' import { fetchPublicFunding, refresh as refreshPublicFunding } from 'state/publicFunding/actions' import { fetchTickers, refresh as refreshTickers } from 'state/tickers/actions' import { fetchDerivatives, refresh as refreshDerivatives } from 'state/derivatives/actions' import { fetchData as fetchLogins, refresh as refreshLogins } from 'state/logins/actions' import { fetchData as fetchChangeLogs, refresh as refreshChangeLogs } from 'state/changeLogs/actions' import types from './constants' import actions from './actions' const { MENU_INVOICES, MENU_LEDGERS, MENU_TRADES, MENU_ORDERS, MENU_MOVEMENTS, MENU_POSITIONS, MENU_FOFFER, MENU_FLOAN, MENU_FCREDIT, MENU_FPAYMENT, MENU_SPAYMENTS, MENU_AFFILIATES_EARNINGS, MENU_PUBLIC_TRADES, MENU_PUBLIC_FUNDING, MENU_TICKERS, MENU_DERIVATIVES, MENU_LOGINS, MENU_CHANGE_LOGS, } = queryTypes export function* setFilters({ payload }) { const { section, refresh = true } = payload if (!refresh) { return } switch (section) { case MENU_INVOICES: yield put(refreshInvoices()) yield put(fetchInvoices()) break case MENU_LEDGERS: yield put(refreshLedgers()) yield put(fetchLedgers()) break case MENU_TRADES: yield put(refreshTrades()) yield put(fetchTrades()) break case MENU_ORDERS: yield put(refreshOrders()) yield put(fetchOrders()) break case MENU_MOVEMENTS: yield put(refreshMovements()) yield put(fetchMovements()) break case MENU_POSITIONS: yield put(refreshPositions()) yield put(fetchPositions()) break case MENU_FOFFER: yield put(refreshFOffer()) yield put(fetchFOffer()) break case MENU_FLOAN: yield put(refreshFLoan()) yield put(fetchFLoan()) break case MENU_FCREDIT: yield put(refreshFCredit()) yield put(fetchFCredit()) break case MENU_FPAYMENT: yield put(refreshFPayment()) yield put(fetchFPayment()) break case MENU_SPAYMENTS: yield put(refreshSPayments()) yield put(fetchSPayments()) break case MENU_AFFILIATES_EARNINGS: yield put(refreshAffiliatesEarnings()) yield put(fetchAffiliatesEarnings()) break case MENU_PUBLIC_TRADES: yield put(refreshPublicTrades()) yield put(fetchPublicTrades()) break case MENU_PUBLIC_FUNDING: yield put(refreshPublicFunding()) yield put(fetchPublicFunding()) break case MENU_TICKERS: yield put(refreshTickers()) yield put(fetchTickers()) break case MENU_DERIVATIVES: yield put(refreshDerivatives()) yield put(fetchDerivatives()) break case MENU_LOGINS: yield put(refreshLogins()) yield put(fetchLogins()) break case MENU_CHANGE_LOGS: yield put(refreshChangeLogs()) yield put(fetchChangeLogs()) break default: } } function* setFiltersFromUrl() { const { pathname, search } = window.location const section = getTarget(pathname, false) if (!section) { return } const filters = decodeFilters({ query: search, section }) if (filters.length) { yield put(actions.setFilters({ section, filters, refresh: false })) // fetch will be done automatically after auth } } export default function* filtersSaga() { yield takeLatest(types.SET_FILTERS, setFilters) yield takeLatest(uiTypes.UI_LOADED, setFiltersFromUrl) }
Hyq0823/Stardust
src/main/java/com/java8/Student.java
package com.java8; /** * @Author: huangyunquan * @Description:Created on 2018/12/4 20:36. */ public class Student { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
techoopsie/oopsie-sdk-java
src/main/java/io/oopsie/sdk/Application.java
<filename>src/main/java/io/oopsie/sdk/Application.java package io.oopsie.sdk; import io.oopsie.sdk.error.NotFoundInModelException; import java.util.stream.Stream; public class Application { private final String name; private final Resources resources; Application(String name, Resources resources) { this.name = name; this.resources = resources; } /** * Returns the name of the Application. * @return app name. */ public String getName() { return name; } /** * Returns the named {@link Resource} from related {@link Site} object. * * @param name the name of the resource to get * @return the named {@link Resource} * @throws NotFoundInModelException if name is not part of the model */ public final Resource getResource(String name) throws NotFoundInModelException { return this.resources.getResource(name); } /** * Returns the Resources object for this Application * @return Resources object. */ public Resources getResources() { return resources; } @Override public String toString() { return name; } }
jacadcaps/webkitty
Source/WebCore/layout/inlineformatting/LineLayoutContext.h
/* * Copyright (C) 2019 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #pragma once #if ENABLE(LAYOUT_FORMATTING_CONTEXT) #include "InlineLineBreaker.h" #include "InlineLineBuilder.h" namespace WebCore { namespace Layout { struct LineCandidate; class LineLayoutContext { public: LineLayoutContext(const InlineFormattingContext&, const ContainerBox& formattingContextRoot, const InlineItems&); struct LineContent { struct PartialContent { bool trailingContentHasHyphen { false }; unsigned overflowContentLength { 0 }; }; Optional<unsigned> trailingInlineItemIndex; Optional<PartialContent> partialContent; struct Float { enum class Intrusive { No, Yes }; Intrusive isIntrusive { Intrusive::Yes }; const InlineItem* item { nullptr }; }; using FloatList = Vector<Float>; FloatList floats; const LineBuilder::RunList runList; const LineBoxBuilder lineBox; }; struct InlineItemRange { bool isEmpty() const { return start == end; } size_t size() const { return end - start; } size_t start { 0 }; size_t end { 0 }; }; LineContent layoutLine(LineBuilder&, const InlineItemRange, Optional<unsigned> partialLeadingContentLength); private: void nextContentForLine(LineCandidate&, unsigned inlineItemIndex, const InlineItemRange layoutRange, Optional<unsigned> overflowLength, InlineLayoutUnit availableLineWidth, InlineLayoutUnit currentLogicalRight); struct Result { LineBreaker::IsEndOfLine isEndOfLine { LineBreaker::IsEndOfLine::No }; struct CommittedContentCount { size_t value { 0 }; bool isRevert { false }; }; CommittedContentCount committedCount { }; Optional <LineContent::PartialContent> partialContent { }; }; enum class CommitIntrusiveFloatsOnly { No, Yes }; void commitFloats(LineBuilder&, const LineCandidate&, CommitIntrusiveFloatsOnly = CommitIntrusiveFloatsOnly::No); Result handleFloatsAndInlineContent(LineBreaker&, LineBuilder&, const InlineItemRange& layoutRange, const LineCandidate&); size_t rebuildLine(LineBuilder&, const InlineItemRange& layoutRange); void commitPartialContent(LineBuilder&, const LineBreaker::RunList&, const LineBreaker::Result::PartialTrailingContent&); LineContent close(LineBuilder&, const InlineItemRange layoutRange, unsigned committedInlineItemCount, Optional<LineContent::PartialContent>); InlineLayoutUnit inlineItemWidth(const InlineItem&, InlineLayoutUnit contentLogicalLeft) const; const InlineFormattingContext& formattingContext() const { return m_inlineFormattingContext; } const ContainerBox& root() const { return m_formattingContextRoot; } const InlineFormattingContext& m_inlineFormattingContext; const ContainerBox& m_formattingContextRoot; const InlineItems& m_inlineItems; LineContent::FloatList m_floats; Optional<InlineTextItem> m_partialLeadingTextItem; const InlineItem* m_lastWrapOpportunityItem { nullptr }; unsigned m_successiveHyphenatedLineCount { 0 }; }; } } #endif
consulo/incubating-consulo-ruby
ruby-api/src/main/java/org/jetbrains/plugins/ruby/ruby/sdk/jruby/JRubySdkType.java
<reponame>consulo/incubating-consulo-ruby /* * Copyright 2000-2008 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.ruby.ruby.sdk.jruby; import javax.annotation.Nullable; import org.jetbrains.annotations.NonNls; import org.jetbrains.plugins.ruby.RBundle; import org.jetbrains.plugins.ruby.jruby.JRubyIcons; import org.jetbrains.plugins.ruby.ruby.sdk.RubySdkType; import org.jetbrains.plugins.ruby.ruby.sdk.RubySdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.SystemInfo; import consulo.ui.image.Image; /** * Created by IntelliJ IDEA. * * @author: <NAME> * @date: Aug 22, 2007 */ public class JRubySdkType extends RubySdkType { @NonNls private static final String JRUBY_WIN_EXE = "jruby.bat"; @NonNls private static final String JRUBY_UNIX_EXE = "jruby"; /** * @deprecated Don't use direct this constant(you can affect JRubySdkType), use getRubyExecutable() */ @NonNls private static String JRUBY_EXE; static { if(SystemInfo.isWindows) { //noinspection deprecation JRUBY_EXE = JRUBY_WIN_EXE; } else if(SystemInfo.isUnix) { //noinspection deprecation JRUBY_EXE = JRUBY_UNIX_EXE; } else { LOG.error(RBundle.message("os.not.supported")); } } public JRubySdkType() { super("JRUBY_SDK"); } public static JRubySdkType getInstance() { return EP_NAME.findExtension(JRubySdkType.class); } public static boolean isJRubySDK(@Nullable final Sdk sdk) { return sdk != null && sdk.getSdkType() instanceof JRubySdkType; } @Override public String getRubyExecutable() { //noinspection deprecation return JRUBY_EXE; } @Override public String getPresentableName() { return RBundle.message("sdk.jruby.title"); } @Override protected String suggestHomePath() { return RubySdkUtil.suggestJRubyHomePath(); } @Override public Image getIcon() { return JRubyIcons.JRUBY_SDK_ICON_CLOSED; } }
deti/boss
backend/model/migrate/env.py
<filename>backend/model/migrate/env.py import conf from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig import logging from model import db from sqlalchemy.sql.sqltypes import Boolean from sqlalchemy.dialects.mysql.base import TINYINT USE_TWOPHASE = False # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. fileConfig(config.config_file_name) logger = logging.getLogger('alembic.env') config.set_main_option('sqlalchemy.url', conf.database.uri) db_uri = {"account": conf.database.uri} db_uri.update(conf.database.binds) class FakeMetadata(object): def __init__(self, bind): tables = db.get_tables_for_bind(bind) self.tables = {name: t for name, t in db.metadata.tables.items() if t in tables} self.sorted_tables = [t for t in db.metadata.sorted_tables if t in tables] target_metadata = {"fitter": FakeMetadata("fitter"), "account": FakeMetadata(None)} # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def compare_type(context, inspected_column, metadata_column, inspected_type, metadata_type): # return True if the types are different, # False if not, or None to allow the default implementation # to compare these types if isinstance(metadata_type, Boolean) and isinstance(inspected_type, TINYINT): return False return None def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ # for the --sql use case, run migrations for each URL into # individual files. engines = {} for name in db_uri: engines[name] = rec = {} rec['url'] = db_uri[name] for name, rec in engines.items(): logger.info("Migrating database %s" % name) file_ = "%s.sql" % name logger.info("Writing output to %s" % file_) with open(file_, 'w') as buffer: context.configure(url=rec['url'], output_buffer=buffer, target_metadata=target_metadata.get(name), compare_type=compare_type) with context.begin_transaction(): context.run_migrations(engine_name=name) def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # for the direct-to-DB use case, start a transaction on all # engines, then run all migrations, then commit all transactions. engines = {} for name in db_uri: engines[name] = rec = {} rec['url'] = db_uri[name] rec['engine'] = engine_from_config( {"sqlalchemy.url": db_uri[name]}, prefix='sqlalchemy.', poolclass=pool.NullPool) for name, rec in engines.items(): engine = rec['engine'] rec['connection'] = conn = engine.connect() if USE_TWOPHASE: rec['transaction'] = conn.begin_twophase() else: rec['transaction'] = conn.begin() try: for name, rec in engines.items(): logger.info("Migrating database %s" % name) context.configure( connection=rec['connection'], upgrade_token="%s_upgrades" % name, downgrade_token="%s_downgrades" % name, target_metadata=target_metadata.get(name), compare_type=compare_type ) context.run_migrations(engine_name=name) if USE_TWOPHASE: for rec in engines.values(): rec['transaction'].prepare() for rec in engines.values(): rec['transaction'].commit() except: for rec in engines.values(): rec['transaction'].rollback() raise finally: for rec in engines.values(): rec['connection'].close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
DVSR1966/par4all
packages/PIPS/validation/Scilab/Scilab2C-2/interfaces/int_cos.h
<filename>packages/PIPS/validation/Scilab/Scilab2C-2/interfaces/int_cos.h /* * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2008-2008 - INRIA - <NAME> * * This file must be used under the terms of the CeCILL. * This source file is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at * http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt * */ /* THIS IS AN AUTOMATICALLY GENERATED FILE : DO NOT EDIT BY HAND. */ #ifndef __INT_COS_H__ #define __INT_COS_H__ #define s0coss0(in) scoss(in) #define d0cosd0(in) dcoss(in) #define c0cosc0(in) ccoss(in) #define z0cosz0(in) zcoss(in) #define s2coss2(in,size,out) scosa(in, size[0]*size[1], out) #define d2cosd2(in,size,out) dcosa(in, size[0]*size[1], out) #define c2cosc2(in,size,out) ccosa(in, size[0]*size[1], out) #define z2cosz2(in,size,out) zcosa(in, size[0]*size[1], out) #endif /* !__INT_COS_H__ */
brainliubo/openairstudy
RRC_Rel14/LTE_DL-CCCH-MessageType.h
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "/home/guicliu/ue_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1" * `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/guicliu/ue_folder/cmake_targets/lte_noS1_build_oai/build/CMakeFiles/RRC_Rel14` */ #ifndef _LTE_DL_CCCH_MessageType_H_ #define _LTE_DL_CCCH_MessageType_H_ #include <asn_application.h> /* Including external dependencies */ #include "LTE_RRCConnectionReestablishment.h" #include "LTE_RRCConnectionReestablishmentReject.h" #include "LTE_RRCConnectionReject.h" #include "LTE_RRCConnectionSetup.h" #include <constr_CHOICE.h> #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum LTE_DL_CCCH_MessageType_PR { LTE_DL_CCCH_MessageType_PR_NOTHING, /* No components present */ LTE_DL_CCCH_MessageType_PR_c1, LTE_DL_CCCH_MessageType_PR_messageClassExtension } LTE_DL_CCCH_MessageType_PR; typedef enum LTE_DL_CCCH_MessageType__c1_PR { LTE_DL_CCCH_MessageType__c1_PR_NOTHING, /* No components present */ LTE_DL_CCCH_MessageType__c1_PR_rrcConnectionReestablishment, LTE_DL_CCCH_MessageType__c1_PR_rrcConnectionReestablishmentReject, LTE_DL_CCCH_MessageType__c1_PR_rrcConnectionReject, LTE_DL_CCCH_MessageType__c1_PR_rrcConnectionSetup } LTE_DL_CCCH_MessageType__c1_PR; /* LTE_DL-CCCH-MessageType */ typedef struct LTE_DL_CCCH_MessageType { LTE_DL_CCCH_MessageType_PR present; union LTE_DL_CCCH_MessageType_u { struct LTE_DL_CCCH_MessageType__c1 { LTE_DL_CCCH_MessageType__c1_PR present; union LTE_DL_CCCH_MessageType__LTE_c1_u { LTE_RRCConnectionReestablishment_t rrcConnectionReestablishment; LTE_RRCConnectionReestablishmentReject_t rrcConnectionReestablishmentReject; LTE_RRCConnectionReject_t rrcConnectionReject; LTE_RRCConnectionSetup_t rrcConnectionSetup; } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } c1; struct LTE_DL_CCCH_MessageType__messageClassExtension { /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } messageClassExtension; } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } LTE_DL_CCCH_MessageType_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_LTE_DL_CCCH_MessageType; extern asn_CHOICE_specifics_t asn_SPC_LTE_DL_CCCH_MessageType_specs_1; extern asn_TYPE_member_t asn_MBR_LTE_DL_CCCH_MessageType_1[2]; extern asn_per_constraints_t asn_PER_type_LTE_DL_CCCH_MessageType_constr_1; #ifdef __cplusplus } #endif #endif /* _LTE_DL_CCCH_MessageType_H_ */ #include <asn_internal.h>
gfreshinc/points
test/domain/rule_test.rb
<reponame>gfreshinc/points require "test_helper" require 'securerandom' require 'json' module GfreshPoint module Domain class RuleTest < Minitest::Test end end end
soyastudio/curly-clouds
curly-clouds-commons/src/main/java/soya/framework/commons/reflect/cloning/ICloningStrategy.java
<reponame>soyastudio/curly-clouds package soya.framework.commons.reflect.cloning; import java.lang.reflect.Field; public interface ICloningStrategy { enum Strategy { NULL_INSTEAD_OF_CLONE, // return null instead of a clone SAME_INSTANCE_INSTEAD_OF_CLONE, // return same instance instead of a clone IGNORE // ignore this strategy for this instance } Strategy strategyFor(Object toBeCloned, Field field); }
au-re/exhibit
src/ApplicationList/ApplicationList/demo/completeList.js
import { ApplicationList, ApplicationListDropdown, ApplicationListItem } from "../../../lib"; import React from "react"; export default () => ( <ApplicationList> <ApplicationListItem label="not active" link="/Other" /> <ApplicationListItem label="active" link="/ApplicationList" /> <ApplicationListItem label="not active" link="/Other" /> <ApplicationListDropdown label="Demo Dropdown Open" open> <ApplicationListItem label="not active" /> <ApplicationListItem label="not active" /> </ApplicationListDropdown> <ApplicationListDropdown label="Demo Dropdown Closed"> <ApplicationListItem label="not active" link="/Other" /> <ApplicationListItem label="not active" link="/Other" /> </ApplicationListDropdown> <ApplicationListItem label="not active" link="/Other" /> <ApplicationListItem label="not active" link="/Other" /> </ApplicationList>);
Bechol/job4j
chapter_003/src/test/java/listtomap/UserConvertTest.java
package listtomap; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class UserConvertTest { @Test public void whenUsersFromListToMap() { UserConvert map = new UserConvert(); User firstUser = new User(1, "Oleg", "Piter"); User secondUser = new User(2, "Petr", "Bryansk"); List<User> users = Arrays.asList(firstUser, secondUser); Map<Integer, User> result = map.process(users); Map<Integer, User> expect = new HashMap<>(); expect.put(firstUser.getId(), firstUser); expect.put(secondUser.getId(), secondUser); assertThat(result, is(expect)); } }
antkmsft/azure-sdk-for-go
sdk/internal/log/log.go
<reponame>antkmsft/azure-sdk-for-go //go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package log import ( "fmt" "os" "time" ) /////////////////////////////////////////////////////////////////////////////////////////////////// // NOTE: The following are exported as public surface area from azcore. DO NOT MODIFY /////////////////////////////////////////////////////////////////////////////////////////////////// // Event is used to group entries. Each group can be toggled on or off. type Event string // SetEvents is used to control which events are written to // the log. By default all log events are writen. func SetEvents(cls ...Event) { log.cls = cls } // SetListener will set the Logger to write to the specified listener. func SetListener(lst func(Event, string)) { log.lst = lst } /////////////////////////////////////////////////////////////////////////////////////////////////// // END PUBLIC SURFACE AREA /////////////////////////////////////////////////////////////////////////////////////////////////// // Should returns true if the specified log event should be written to the log. // By default all log events will be logged. Call SetEvents() to limit // the log events for logging. // If no listener has been set this will return false. // Calling this method is useful when the message to log is computationally expensive // and you want to avoid the overhead if its log event is not enabled. func Should(cls Event) bool { if log.lst == nil { return false } if log.cls == nil || len(log.cls) == 0 { return true } for _, c := range log.cls { if c == cls { return true } } return false } // Write invokes the underlying listener with the specified event and message. // If the event shouldn't be logged or there is no listener then Write does nothing. func Write(cls Event, message string) { if !Should(cls) { return } log.lst(cls, message) } // Writef invokes the underlying listener with the specified event and formatted message. // If the event shouldn't be logged or there is no listener then Writef does nothing. func Writef(cls Event, format string, a ...interface{}) { if !Should(cls) { return } log.lst(cls, fmt.Sprintf(format, a...)) } // TestResetEvents is used for TESTING PURPOSES ONLY. func TestResetEvents() { log.cls = nil } // logger controls which events to log and writing to the underlying log. type logger struct { cls []Event lst func(Event, string) } // the process-wide logger var log logger func init() { initLogging() } // split out for testing purposes func initLogging() { if cls := os.Getenv("AZURE_SDK_GO_LOGGING"); cls == "all" { // cls could be enhanced to support a comma-delimited list of log events log.lst = func(cls Event, msg string) { // simple console logger, it writes to stderr in the following format: // [time-stamp] Event: message fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", time.Now().Format(time.StampMicro), cls, msg) } } }
eaciit/gdrj
modules/summarysalespls/update4pvaaddproductcat.go
<reponame>eaciit/gdrj package main import ( "eaciit/gdrj/model" "eaciit/gdrj/modules" "os" "flag" "github.com/eaciit/dbox" // "github.com/eaciit/orm/v1" "github.com/eaciit/toolkit" // "strings" "time" ) var conn dbox.IConnection var count int var ( t0 time.Time fiscalyear, iscount, scount int data map[string]float64 masters = toolkit.M{} ) func setinitialconnection() { var err error conn, err = modules.GetDboxIConnection("db_godrej") if err != nil { toolkit.Println("Initial connection found : ", err) os.Exit(1) } err = gdrj.SetDb(conn) if err != nil { toolkit.Println("Initial connection found : ", err) os.Exit(1) } } func prepmasterproduct() { toolkit.Println("--> Product") csr, _ := conn.NewQuery().From("product").Cursor(nil) products := toolkit.M{} defer csr.Close() for { m := toolkit.M{} e := csr.Fetch(&m, 1, false) if e != nil { break } products.Set(m.GetString("_id"), m.GetString("brandcategoryid")) } masters.Set("products", products) toolkit.Println("End PL MODEL <--") } func getstep(count int) int { v := count / 100 if v == 0 { return 1 } return v } func main() { t0 = time.Now() data = make(map[string]float64) flag.IntVar(&fiscalyear, "year", 2015, "YYYY representation of godrej fiscal year. Default is 2015") flag.Parse() workerconn, _ := modules.GetDboxIConnection("db_godrej") defer workerconn.Close() setinitialconnection() defer gdrj.CloseDb() prepmasterproduct() toolkit.Println("Start data query...") csr, _ := workerconn.NewQuery().Select().From("salespls-summary-4pva").Cursor(nil) defer csr.Close() scount = csr.Count() jobs := make(chan toolkit.M, scount) result := make(chan int, scount) for wi := 0; wi < 10; wi++ { go workersave(wi, jobs, result) } iscount = 0 step := getstep(scount) * 10 for { iscount++ tkm := toolkit.M{} e := csr.Fetch(&tkm, 1, false) if e != nil { toolkit.Println("EOF") break } jobs <- tkm if iscount%step == 0 { toolkit.Printfn("Sending %d of %d (%d) in %s", iscount, scount, iscount*100/scount, time.Since(t0).String()) } } close(jobs) for ri := 0; ri < scount; ri++ { <-result if ri%step == 0 { toolkit.Printfn("Saving %d of %d (%d pct) in %s", ri, scount, ri*100/scount, time.Since(t0).String()) } } toolkit.Printfn("Processing done in %s", time.Since(t0).String()) } func workersave(wi int, jobs <-chan toolkit.M, result chan<- int) { workerconn, _ := modules.GetDboxIConnection("db_godrej") defer workerconn.Close() qSave := workerconn.NewQuery(). From("salespls-summary-4pva-1.1"). SetConfig("multiexec", true). Save() products := masters.Get("products", toolkit.M{}).(toolkit.M) trx := toolkit.M{} for trx = range jobs { key := trx.Get("key", toolkit.M{}).(toolkit.M) skuid := key.GetString("product_skuid") key.Set("product_brandcategoryid", products.GetString(skuid)) trx.Set("key", key) err := qSave.Exec(toolkit.M{}.Set("data", trx)) if err != nil { toolkit.Println(err) } result <- 1 } }
alwell-kevin/gitlab
ee/app/helpers/ee/events_helper.rb
<reponame>alwell-kevin/gitlab<filename>ee/app/helpers/ee/events_helper.rb<gh_stars>0 # frozen_string_literal: true module EE module EventsHelper extend ::Gitlab::Utils::Override override :event_note_target_url def event_note_target_url(event) if event.epic_note? group_epic_url(event.group, event.note_target, anchor: dom_id(event.target)) elsif event.design_note? design_url(event.note_target, anchor: dom_id(event.note)) else super end end private def design_url(design, opts) designs_project_issue_url( design.project, design.issue, opts.merge(vueroute: design.filename) ) end end end
naver/webgraphics
mozilla/gfx/graphite2/src/Code.cpp
/* GRAPHITE2 LICENSING Copyright 2010, SIL International All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should also have received a copy of the GNU Lesser General Public License along with this library in the file named "LICENSE". If not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA or visit their web page on the internet at http://www.fsf.org/licenses/lgpl.html. Alternatively, the contents of this file may be used under the terms of the Mozilla Public License (http://mozilla.org/MPL) or the GNU General Public License, as published by the Free Software Foundation, either version 2 of the License or (at your option) any later version. */ // This class represents loaded graphite stack machine code. It performs // basic sanity checks, on the incoming code to prevent more obvious problems // from crashing graphite. // Author: <NAME> #include <cassert> #include <cstddef> #include <cstdlib> #include <cstring> #include "graphite2/Segment.h" #include "inc/Code.h" #include "inc/Face.h" #include "inc/GlyphFace.h" #include "inc/GlyphCache.h" #include "inc/Machine.h" #include "inc/Rule.h" #include "inc/Silf.h" #include <cstdio> #ifdef NDEBUG #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #endif using namespace graphite2; using namespace vm; namespace { inline bool is_return(const instr i) { const opcode_t * opmap = Machine::getOpcodeTable(); const instr pop_ret = *opmap[POP_RET].impl, ret_zero = *opmap[RET_ZERO].impl, ret_true = *opmap[RET_TRUE].impl; return i == pop_ret || i == ret_zero || i == ret_true; } struct context { context(uint8 ref=0) : codeRef(ref) {flags.changed=false; flags.referenced=false;} struct { uint8 changed:1, referenced:1; } flags; uint8 codeRef; }; } // end namespace class Machine::Code::decoder { public: struct limits; static const int NUMCONTEXTS = 256; decoder(limits & lims, Code &code, enum passtype pt) throw(); bool load(const byte * bc_begin, const byte * bc_end); void apply_analysis(instr * const code, instr * code_end); byte max_ref() { return _max_ref; } int out_index() const { return _out_index; } private: void set_ref(int index) throw(); void set_noref(int index) throw(); void set_changed(int index) throw(); opcode fetch_opcode(const byte * bc); void analyse_opcode(const opcode, const int8 * const dp) throw(); bool emit_opcode(opcode opc, const byte * & bc); bool validate_opcode(const opcode opc, const byte * const bc); bool valid_upto(const uint16 limit, const uint16 x) const throw(); bool test_context() const throw(); bool test_ref(int8 index) const throw(); void failure(const status_t s) const throw() { _code.failure(s); } Code & _code; int _out_index; uint16 _out_length; instr * _instr; byte * _data; limits & _max; enum passtype _passtype; int _stack_depth; bool _in_ctxt_item; int16 _slotref; context _contexts[NUMCONTEXTS]; byte _max_ref; }; struct Machine::Code::decoder::limits { const byte * bytecode; const uint8 pre_context; const uint16 rule_length, classes, glyf_attrs, features; const byte attrid[gr_slatMax]; }; inline Machine::Code::decoder::decoder(limits & lims, Code &code, enum passtype pt) throw() : _code(code), _out_index(code._constraint ? 0 : lims.pre_context), _out_length(code._constraint ? 1 : lims.rule_length), _instr(code._code), _data(code._data), _max(lims), _passtype(pt), _stack_depth(0), _in_ctxt_item(false), _slotref(0), _max_ref(0) { } Machine::Code::Code(bool is_constraint, const byte * bytecode_begin, const byte * const bytecode_end, uint8 pre_context, uint16 rule_length, const Silf & silf, const Face & face, enum passtype pt, byte * * const _out) : _code(0), _data(0), _data_size(0), _instr_count(0), _max_ref(0), _status(loaded), _constraint(is_constraint), _modify(false), _delete(false), _own(_out==0) { #ifdef GRAPHITE2_TELEMETRY telemetry::category _code_cat(face.tele.code); #endif assert(bytecode_begin != 0); if (bytecode_begin == bytecode_end) { // ::new (this) Code(); return; } assert(bytecode_end > bytecode_begin); const opcode_t * op_to_fn = Machine::getOpcodeTable(); // Allocate code and data target buffers, these sizes are a worst case // estimate. Once we know their real sizes the we'll shrink them. if (_out) _code = reinterpret_cast<instr *>(*_out); else _code = static_cast<instr *>(malloc(estimateCodeDataOut(bytecode_end-bytecode_begin, 1, is_constraint ? 0 : rule_length))); _data = reinterpret_cast<byte *>(_code + (bytecode_end - bytecode_begin)); if (!_code || !_data) { failure(alloc_failed); return; } decoder::limits lims = { bytecode_end, pre_context, rule_length, silf.numClasses(), face.glyphs().numAttrs(), face.numFeatures(), {1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,255, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0, silf.numUser()} }; decoder dec(lims, *this, pt); if(!dec.load(bytecode_begin, bytecode_end)) return; // Is this an empty program? if (_instr_count == 0) { release_buffers(); ::new (this) Code(); return; } // When we reach the end check we've terminated it correctly if (!is_return(_code[_instr_count-1])) { failure(missing_return); return; } assert((_constraint && immutable()) || !_constraint); dec.apply_analysis(_code, _code + _instr_count); _max_ref = dec.max_ref(); // Now we know exactly how much code and data the program really needs // realloc the buffers to exactly the right size so we don't waste any // memory. assert((bytecode_end - bytecode_begin) >= ptrdiff_t(_instr_count)); assert((bytecode_end - bytecode_begin) >= ptrdiff_t(_data_size)); memmove(_code + (_instr_count+1), _data, _data_size*sizeof(byte)); size_t const total_sz = ((_instr_count+1) + (_data_size + sizeof(instr)-1)/sizeof(instr))*sizeof(instr); if (_out) *_out += total_sz; else _code = static_cast<instr *>(realloc(_code, total_sz)); _data = reinterpret_cast<byte *>(_code + (_instr_count+1)); if (!_code) { failure(alloc_failed); return; } // Make this RET_ZERO, we should never reach this but just in case ... _code[_instr_count] = op_to_fn[RET_ZERO].impl[_constraint]; #ifdef GRAPHITE2_TELEMETRY telemetry::count_bytes(_data_size + (_instr_count+1)*sizeof(instr)); #endif } Machine::Code::~Code() throw () { if (_own) release_buffers(); } bool Machine::Code::decoder::load(const byte * bc, const byte * bc_end) { _max.bytecode = bc_end; while (bc < bc_end) { const opcode opc = fetch_opcode(bc++); if (opc == vm::MAX_OPCODE) return false; analyse_opcode(opc, reinterpret_cast<const int8 *>(bc)); if (!emit_opcode(opc, bc)) return false; } return bool(_code); } // Validation check and fixups. // opcode Machine::Code::decoder::fetch_opcode(const byte * bc) { const opcode opc = opcode(*bc++); // Do some basic sanity checks based on what we know about the opcode if (!validate_opcode(opc, bc)) return MAX_OPCODE; // And check it's arguments as far as possible switch (opc) { case NOP : break; case PUSH_BYTE : case PUSH_BYTEU : case PUSH_SHORT : case PUSH_SHORTU : case PUSH_LONG : ++_stack_depth; break; case ADD : case SUB : case MUL : case DIV : case MIN_ : case MAX_ : case AND : case OR : case EQUAL : case NOT_EQ : case LESS : case GTR : case LESS_EQ : case GTR_EQ : case BITOR : case BITAND : if (--_stack_depth <= 0) failure(underfull_stack); break; case NEG : case TRUNC8 : case TRUNC16 : case NOT : case BITNOT : case BITSET : if (_stack_depth <= 0) failure(underfull_stack); break; case COND : _stack_depth -= 2; if (_stack_depth <= 0) failure(underfull_stack); break; case NEXT : case NEXT_N : // runtime checked case COPY_NEXT : ++_out_index; if (_out_index < -1 || _out_index > _out_length || _slotref > _max.rule_length) failure(out_of_range_data); break; case PUT_GLYPH_8BIT_OBS : valid_upto(_max.classes, bc[0]); test_context(); break; case PUT_SUBS_8BIT_OBS : test_ref(int8(bc[0])); valid_upto(_max.classes, bc[1]); valid_upto(_max.classes, bc[2]); test_context(); break; case PUT_COPY : test_ref(int8(bc[0])); test_context(); break; case INSERT : if (_passtype >= PASS_TYPE_POSITIONING) failure(invalid_opcode); ++_out_length; if (_out_index < 0) ++_out_index; if (_out_index < -1 || _out_index >= _out_length) failure(out_of_range_data); break; case DELETE : if (_passtype >= PASS_TYPE_POSITIONING) failure(invalid_opcode); if (_out_index < _max.pre_context) failure(out_of_range_data); --_out_index; --_out_length; if (_out_index < -1 || _out_index > _out_length) failure(out_of_range_data); break; case ASSOC : if (bc[0] == 0) failure(out_of_range_data); for (uint8 num = bc[0]; num; --num) test_ref(int8(bc[num])); test_context(); break; case CNTXT_ITEM : valid_upto(_max.rule_length, _max.pre_context + int8(bc[0])); if (bc + 2 + bc[1] >= _max.bytecode) failure(jump_past_end); if (_in_ctxt_item) failure(nested_context_item); break; case ATTR_SET : case ATTR_ADD : case ATTR_SUB : case ATTR_SET_SLOT : if (--_stack_depth < 0) failure(underfull_stack); valid_upto(gr_slatMax, bc[0]); if (attrCode(bc[0]) == gr_slatUserDefn) // use IATTR for user attributes failure(out_of_range_data); test_context(); break; case IATTR_SET_SLOT : if (--_stack_depth < 0) failure(underfull_stack); if (valid_upto(gr_slatMax, bc[0])) valid_upto(_max.attrid[bc[0]], bc[1]); test_context(); break; case PUSH_SLOT_ATTR : ++_stack_depth; valid_upto(gr_slatMax, bc[0]); test_ref(int8(bc[1])); if (attrCode(bc[0]) == gr_slatUserDefn) // use IATTR for user attributes failure(out_of_range_data); break; case PUSH_GLYPH_ATTR_OBS : case PUSH_ATT_TO_GATTR_OBS : ++_stack_depth; valid_upto(_max.glyf_attrs, bc[0]); test_ref(int8(bc[1])); break; case PUSH_ATT_TO_GLYPH_METRIC : case PUSH_GLYPH_METRIC : ++_stack_depth; valid_upto(kgmetDescent, bc[0]); test_ref(int8(bc[1])); // level: dp[2] no check necessary break; case PUSH_FEAT : ++_stack_depth; valid_upto(_max.features, bc[0]); test_ref(int8(bc[1])); break; case PUSH_ISLOT_ATTR : ++_stack_depth; if (valid_upto(gr_slatMax, bc[0])) { test_ref(int8(bc[1])); valid_upto(_max.attrid[bc[0]], bc[2]); } break; case PUSH_IGLYPH_ATTR :// not implemented ++_stack_depth; break; case POP_RET : if (--_stack_depth < 0) failure(underfull_stack); GR_FALLTHROUGH; // no break case RET_ZERO : case RET_TRUE : break; case IATTR_SET : case IATTR_ADD : case IATTR_SUB : if (--_stack_depth < 0) failure(underfull_stack); if (valid_upto(gr_slatMax, bc[0])) valid_upto(_max.attrid[bc[0]], bc[1]); test_context(); break; case PUSH_PROC_STATE : // dummy: dp[0] no check necessary case PUSH_VERSION : ++_stack_depth; break; case PUT_SUBS : test_ref(int8(bc[0])); valid_upto(_max.classes, uint16(bc[1]<< 8) | bc[2]); valid_upto(_max.classes, uint16(bc[3]<< 8) | bc[4]); test_context(); break; case PUT_SUBS2 : // not implemented case PUT_SUBS3 : // not implemented break; case PUT_GLYPH : valid_upto(_max.classes, uint16(bc[0]<< 8) | bc[1]); test_context(); break; case PUSH_GLYPH_ATTR : case PUSH_ATT_TO_GLYPH_ATTR : ++_stack_depth; valid_upto(_max.glyf_attrs, uint16(bc[0]<< 8) | bc[1]); test_ref(int8(bc[2])); break; case SET_FEAT : valid_upto(_max.features, bc[0]); test_ref(int8(bc[1])); break; default: failure(invalid_opcode); break; } return bool(_code) ? opc : MAX_OPCODE; } void Machine::Code::decoder::analyse_opcode(const opcode opc, const int8 * arg) throw() { switch (opc) { case DELETE : _code._delete = true; break; case ASSOC : set_changed(0); // for (uint8 num = arg[0]; num; --num) // _analysis.set_noref(num); break; case PUT_GLYPH_8BIT_OBS : case PUT_GLYPH : _code._modify = true; set_changed(0); break; case ATTR_SET : case ATTR_ADD : case ATTR_SUB : case ATTR_SET_SLOT : case IATTR_SET_SLOT : case IATTR_SET : case IATTR_ADD : case IATTR_SUB : set_noref(0); break; case NEXT : case COPY_NEXT : ++_slotref; _contexts[_slotref] = context(_code._instr_count+1); // if (_analysis.slotref > _analysis.max_ref) _analysis.max_ref = _analysis.slotref; break; case INSERT : if (_slotref >= 0) --_slotref; _code._modify = true; break; case PUT_SUBS_8BIT_OBS : // slotref on 1st parameter case PUT_SUBS : _code._modify = true; set_changed(0); GR_FALLTHROUGH; // no break case PUT_COPY : if (arg[0] != 0) { set_changed(0); _code._modify = true; } set_ref(arg[0]); break; case PUSH_GLYPH_ATTR_OBS : case PUSH_SLOT_ATTR : case PUSH_GLYPH_METRIC : case PUSH_ATT_TO_GATTR_OBS : case PUSH_ATT_TO_GLYPH_METRIC : case PUSH_ISLOT_ATTR : case PUSH_FEAT : case SET_FEAT : set_ref(arg[1]); break; case PUSH_ATT_TO_GLYPH_ATTR : case PUSH_GLYPH_ATTR : set_ref(arg[2]); break; default: break; } } bool Machine::Code::decoder::emit_opcode(opcode opc, const byte * & bc) { const opcode_t * op_to_fn = Machine::getOpcodeTable(); const opcode_t & op = op_to_fn[opc]; if (op.impl[_code._constraint] == 0) { failure(unimplemented_opcode_used); return false; } const size_t param_sz = op.param_sz == VARARGS ? bc[0] + 1 : op.param_sz; // Add this instruction *_instr++ = op.impl[_code._constraint]; ++_code._instr_count; // Grab the parameters if (param_sz) { memcpy(_data, bc, param_sz * sizeof(byte)); bc += param_sz; _data += param_sz; _code._data_size += param_sz; } // recursively decode a context item so we can split the skip into // instruction and data portions. if (opc == CNTXT_ITEM) { assert(_out_index == 0); _in_ctxt_item = true; _out_index = _max.pre_context + int8(_data[-2]); _slotref = int8(_data[-2]); _out_length = _max.rule_length; const size_t ctxt_start = _code._instr_count; byte & instr_skip = _data[-1]; byte & data_skip = *_data++; ++_code._data_size; const byte *curr_end = _max.bytecode; if (load(bc, bc + instr_skip)) { bc += instr_skip; data_skip = instr_skip - (_code._instr_count - ctxt_start); instr_skip = _code._instr_count - ctxt_start; _max.bytecode = curr_end; _out_length = 1; _out_index = 0; _slotref = 0; _in_ctxt_item = false; } else { _out_index = 0; _slotref = 0; return false; } } return bool(_code); } void Machine::Code::decoder::apply_analysis(instr * const code, instr * code_end) { // insert TEMP_COPY commands for slots that need them (that change and are referenced later) int tempcount = 0; if (_code._constraint) return; const instr temp_copy = Machine::getOpcodeTable()[TEMP_COPY].impl[0]; for (const context * c = _contexts, * const ce = c + _slotref; c < ce; ++c) { if (!c->flags.referenced || !c->flags.changed) continue; instr * const tip = code + c->codeRef + tempcount; memmove(tip+1, tip, (code_end - tip) * sizeof(instr)); *tip = temp_copy; ++code_end; ++tempcount; _code._delete = true; } _code._instr_count = code_end - code; } inline bool Machine::Code::decoder::validate_opcode(const opcode opc, const byte * const bc) { if (opc >= MAX_OPCODE) { failure(invalid_opcode); return false; } const opcode_t & op = Machine::getOpcodeTable()[opc]; if (op.impl[_code._constraint] == 0) { failure(unimplemented_opcode_used); return false; } if (op.param_sz == VARARGS && bc >= _max.bytecode) { failure(arguments_exhausted); return false; } const size_t param_sz = op.param_sz == VARARGS ? bc[0] + 1 : op.param_sz; if (bc - 1 + param_sz >= _max.bytecode) { failure(arguments_exhausted); return false; } return true; } bool Machine::Code::decoder::valid_upto(const uint16 limit, const uint16 x) const throw() { const bool t = (limit != 0) && (x < limit); if (!t) failure(out_of_range_data); return t; } inline bool Machine::Code::decoder::test_ref(int8 index) const throw() { return valid_upto(_max.rule_length, _slotref + _max.pre_context + index); } bool Machine::Code::decoder::test_context() const throw() { if (_out_index >= _out_length || _out_index < 0 || _slotref >= NUMCONTEXTS - 1) { failure(out_of_range_data); return false; } return true; } inline void Machine::Code::failure(const status_t s) throw() { release_buffers(); _status = s; } inline void Machine::Code::decoder::set_ref(int index) throw() { if (index + _slotref < 0 || index + _slotref >= NUMCONTEXTS) return; _contexts[index + _slotref].flags.referenced = true; if (index + _slotref > _max_ref) _max_ref = index + _slotref; } inline void Machine::Code::decoder::set_noref(int index) throw() { if (index + _slotref < 0 || index + _slotref >= NUMCONTEXTS) return; if (index + _slotref > _max_ref) _max_ref = index + _slotref; } inline void Machine::Code::decoder::set_changed(int index) throw() { if (index + _slotref < 0 || index + _slotref >= NUMCONTEXTS) return; _contexts[index + _slotref].flags.changed= true; if (index + _slotref > _max_ref) _max_ref = index + _slotref; } void Machine::Code::release_buffers() throw() { if (_own) free(_code); _code = 0; _data = 0; _own = false; } int32 Machine::Code::run(Machine & m, slotref * & map) const { // assert(_own); assert(*this); // Check we are actually runnable if (m.slotMap().size() <= size_t(_max_ref + m.slotMap().context()) || m.slotMap()[_max_ref + m.slotMap().context()] == 0) { m._status = Machine::slot_offset_out_bounds; return 1; // return m.run(_code, _data, map); } return m.run(_code, _data, map); }
ZhekehZ/catboost
catboost/libs/helpers/ut/short_vector_ops_ut.cpp
#include <library/unittest/registar.h> #include <catboost/libs/helpers/short_vector_ops.h> #include <library/sse/sse.h> Y_UNIT_TEST_SUITE(ShortVectorOpsTest) { Y_UNIT_TEST(CalculateScorePattern) { #ifdef ARCADIA_SSE const double values[] = {0.0, 0.25, 0.5, 0.75}; auto genericHorizontalSum = NGenericSimdOps::HorizontalAdd( NGenericSimdOps::FusedMultiplyAdd( values + 0, values + 2, NGenericSimdOps::MakeZeros() )); auto sse2HorizontalSum = NSse2SimdOps::HorizontalAdd( NSse2SimdOps::FusedMultiplyAdd( values + 0, values + 2, NSse2SimdOps::MakeZeros() )); UNIT_ASSERT_DOUBLES_EQUAL(genericHorizontalSum, sse2HorizontalSum, 1e-18); #endif } Y_UNIT_TEST(CalculatePairwiseScorePattern) { #ifdef ARCADIA_SSE const double values[] = {0.0, 0.25, 0.5, 0.75}; auto genericHorizontalSum = NGenericSimdOps::HorizontalAdd( NGenericSimdOps::ElementwiseAdd( NGenericSimdOps::Gather(values + 0, values + 2), NGenericSimdOps::Gather(values + 1, values + 3) )); auto sse2HorizontalSum = NSse2SimdOps::HorizontalAdd( NSse2SimdOps::ElementwiseAdd( NSse2SimdOps::Gather(values + 0, values + 2), NSse2SimdOps::Gather(values + 1, values + 3) )); UNIT_ASSERT_DOUBLES_EQUAL(genericHorizontalSum, sse2HorizontalSum, 1e-18); #endif } Y_UNIT_TEST(UpdateScoreBinKernelPlain) { #ifdef _sse_ const double trueStats[] = {0.0, 0.25, 0.5, 0.75}; const double falseStats[] = {1.0, 0.75, 0.5, 0.25}; const double scaledL2Regularizer = 1.0; double genericScoreBin[2]; NGenericSimdOps::UpdateScoreBinKernelPlain( scaledL2Regularizer, &trueStats[0], &falseStats[0], &genericScoreBin[0] ); double sse2ScoreBin[2]; NGenericSimdOps::UpdateScoreBinKernelPlain( scaledL2Regularizer, &trueStats[0], &falseStats[0], &sse2ScoreBin[0] ); UNIT_ASSERT_DOUBLES_EQUAL(genericScoreBin[0], sse2ScoreBin[0], 1e-18); UNIT_ASSERT_DOUBLES_EQUAL(genericScoreBin[1], sse2ScoreBin[1], 1e-18); #endif } Y_UNIT_TEST(UpdateScoreBinKernelOrdered) { #ifdef _sse_ const double trueStats[] = {0.0, 0.25, 0.5, 0.75}; const double falseStats[] = {1.0, 0.75, 0.5, 0.25}; const double scaledL2Regularizer = 1.0; double genericScoreBin[2]; NGenericSimdOps::UpdateScoreBinKernelOrdered( scaledL2Regularizer, &trueStats[0], &falseStats[0], &genericScoreBin[0] ); double sse2ScoreBin[2]; NGenericSimdOps::UpdateScoreBinKernelOrdered( scaledL2Regularizer, &trueStats[0], &falseStats[0], &sse2ScoreBin[0] ); UNIT_ASSERT_DOUBLES_EQUAL(genericScoreBin[0], sse2ScoreBin[0], 1e-18); UNIT_ASSERT_DOUBLES_EQUAL(genericScoreBin[1], sse2ScoreBin[1], 1e-18); #endif } }
Xilinx/graphanalytics
louvainmod/src/partitionLouvain.cpp
<reponame>Xilinx/graphanalytics /* * Copyright 2021 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WANCUNCUANTIES ONCU CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "defs.h" #include "partitionLouvain.hpp" #include "ctrlLV.h" #include "louvainPhase.h" #ifdef PRINTINFO #define PRINTINFO_PARLV #endif void FreeG(graphNew* &G) { free(G->edgeListPtrs); free(G->edgeList); free(G); } void printG_org( graphNew* G ){ long vertexNum = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", vertexNum, NE); for(long v=0; v< vertexNum; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; printf("v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t", v, adj1, adj2, degree); for(int d=0; d<degree; d++){ printf(" %4ld\t", vtxInd[adj1+d].tail); } printf("\n"); } } void printG(graphNew* G, long* C, long* M, long star, long end){ long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; //printf("|==C==|==V==|==M==|=OFF=|=Dgr=|\n"); for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2 - adj1; //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%-4d : v=%-4d m=%-4d off=%4d, dgr=%-3d\t",C[v], v, M[v], adj1, degree); long m = M==NULL?v:M[v]; long c = C==NULL?v:C[v]; //printf(" c=%-4d, v=%-4d,", c, v, m, adj1, degree); if(m<0) printf(" \033[1;31;40mc=%-5ld v=%-5ld m=%-5ld\033[0m", c, v, m); else printf(" c=%-5ld v=%-5ld m=%-5ld", c, v, m); printf(" o=%-5ld d=%-4ld |", adj1, degree); for(long d=0; d<degree; d++){ //\033[1;31;40mERROR\033[0m long t = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; if(M!=NULL&&M[t]<0) printf("\033[1;31;40m%5ld\033[0m/%1.0f ", t, w); else printf("%5ld/%1.0f ", t, w); } printf("\n"); } } void printG(graphNew* G, long* C, long* M, long star, long end, bool isCid, bool isDir, ParLV* p_par, int idx){ long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; //printf("|==C==|==V==|==M==|=OFF=|=Dgr=|\n"); for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; long m = M==NULL?v:M[v]; long c = C==NULL?v:C[v]; long c_final = c+p_par->off_lved[idx]; //printf(" c=%-4d, v=%-4d,", c, v, m, adj1, degree); if (m<0){ if(p_par->st_PreMerged==true) c_final = p_par->p_v_new[idx][v]; printf(" \033[1;31;40mc=%-5ld (%-5ld) v=%-5ld m=%-5ld c(m)=%-5ld\033[0m", c, c_final, v, m, p_par->FindC_nhop(m)); } else printf(" c=%-5ld (%-5ld) v=%-5ld m=%-5ld c(m)=%-5ld", c, c_final, v, m, c); printf(" o=%-5ld d=%-4ld |", adj1, degree); for(long d=0; d<degree; d++){ long t = vtxInd[adj1+d].tail; if (isDir){ if (isCid){ if(C[v] < C[t]) continue; } else{ if(v < t) continue; } } double w = vtxInd[adj1+d].weight; if ( M != NULL && M[t]<0) printf("\033[1;31;40m%5ld\033[0m/%1.0f ", (isCid ? C[t] : t), w); else printf("%5ld/%1.0f ", (isCid ? C[t] : t), w); } printf("\n"); } } void printG(graphNew* G, long* C, long* M, long star, long end, bool isCid, bool isDir){ long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; //printf("|==C==|==V==|==M==|=OFF=|=Dgr=|\n"); for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; long m = M==NULL?v:M[v]; long c = C==NULL?v:C[v]; if (m < 0) printf(" \033[1;31;40mc=%-5ld v=%-5ld m=%-5ld\033[0m", c, v, m); else printf(" c=%-5ld v=%-5ld m=%-5ld", c, v, m); printf(" o=%-5ld d=%-4ld |", adj1, degree); for(int d=0; d<degree; d++){ long t = vtxInd[adj1+d].tail; if(isDir){ if(isCid){ if(C[v] < C[t]) continue; } else{ if(v < t) continue; } } double w = vtxInd[adj1+d].weight; if(M!=NULL&&M[t]<0) printf("\033[1;31;40m%5ld\033[0m/%1.0f ", isCid?C[t]:t, w); else printf("%5ld/%1.0f ", isCid?C[t]:t, w); } printf("\n"); } } void printG( char* name, graphNew* G, long* C, long* M, long star, long end ){ FILE* fp=fopen(name, "w"); if(fp==NULL) return; long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; fprintf(fp, "v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; //printf("|==C==|==V==|==M==|=OFF=|=Dgr=|\n"); for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%-4d : v=%-4d m=%-4d off=%4d, dgr=%-3d\t",C[v], v, M[v], adj1, degree); long m = M==NULL?v:M[v]; long c = C==NULL?v:C[v]; //printf(" c=%-4d, v=%-4d,", c, v, m, adj1, degree); if(m<0) printf(" \033[1;31;40mc=%-5ld v=%-5ld m=%-5ld\033[0m", c, v, m); else printf(" c=%-5ld v=%-5ld m=%-5ld", c, v, m); if(m<0) fprintf(fp,"[c=%-5ld v=%-5ld m=%-5ld]", c, v, m); else fprintf(fp," c=%-5ld v=%-5ld m=%-5ld", c, v, m); fprintf(fp," o=%-5ld d=%-4ld |", adj1, degree); for (long d=0; d<degree; d++){ //\033[1;31;40mERROR\033[0m long t = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; if(M!=NULL&&M[t]<0) fprintf(fp,"[%5ld]%1.0f ", t, w); else fprintf(fp,"%5ld/%1.0f ", t, w); if(M!=NULL&&M[t]<0) printf("\033[1;31;40m%5ld\033[0m/%1.0f ", t, w); else printf("%5ld/%1.0f ", t, w); } fprintf(fp,"\n"); } fclose(fp); } void printG_NOWeight( graphNew* G, long* C, long* M, long star, long end ) { long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; //printf("|==C==|==V==|==M==|=OFF=|=Dgr=|\n"); for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%4ld : v=%4ld\t adj1=%4ld, adj2=%4ld, degree=%4ld\t",C[v], v, adj1, adj2, degree); //printf("c=%-4d : v=%-4d m=%-4d off=%4d, dgr=%-3d\t",C[v], v, M[v], adj1, degree); long m = M==NULL?v:M[v]; long c = C==NULL?v:C[v]; //printf(" c=%-4d, v=%-4d,", c, v, m, adj1, degree); if(m<0) printf(" \033[1;31;40mc=%-5ld v=%-5ld m=%-5ld\033[0m", c, v, m); else printf(" c=%-5ld v=%-5ld m=%-5ld", c, v, m); printf(" o=%-5ld d=%-4ld |", adj1, degree); for(int d=0; d<degree; d++){ //\033[1;31;40mERROR\033[0m long t = vtxInd[adj1+d].tail; if(M!=NULL&&M[t]<0) printf("\033[1;31;40m%5ld\033[0m ", t); else printf("%5ld ", t); } printf("\n"); } } void printG_old2( graphNew* G, long* C, long* M, long star, long end ){ long NV = G->numVertices; long NE = G->numEdges; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; printf("v=%ld\t; e=%ld \n", NV, NE); if(star<0) star=0; if(end >NV) end=NV; for(long v=star; v< end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; long degree = adj2-adj1; printf("c=%-4ld : v=%-4ld m=%-4ld off=%4ld, dgr=%-3ld\t",C[v], v, M[v], adj1, degree); for(long d=0; d<degree; d++){ printf(" %4ld ", vtxInd[adj1+d].tail); } printf("\n"); } } void printG( graphNew* G, long* C, long* M ){ long NV = G->numVertices; printG(G, C, M, 0, NV); } void printG( graphNew* G, long* C ){ long NV = G->numVertices; printG(G, C, NULL, 0, NV); } long CountV( graphNew* G, long star, long end ){ long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; if(star<0) star=0; if(end >NV) end=NV; map<long, long> map_all; map<long, long>::iterator iter_all; long cnt=0; for(long v = star; v < end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; if(map_all.find(v) == map_all.end()) map_all[cnt] = cnt++; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; if(map_all.find(e) == map_all.end()) map_all[cnt] = cnt++; }//for } return cnt; } long CountV( graphNew* G){ long NV = G->numVertices; return CountV(G, 0, NV); } long CountVGh( graphNew* G, long star, long end ){ long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; if(star<0) star=0; if(end >NV) end=NV; map<long, long> map_all; map<long, long>::iterator iter_all; long cnt=0; for(long v = star; v < end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; //if(map_all.find(v) == map_all.end()) // map_all[cnt] = cnt++; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; if(e<star||e>=end){ if(map_all.find(e) == map_all.end()) map_all[e] = cnt++; } }//for } return cnt; } long CountVGh( graphNew* G){ long NV = G->numVertices; return CountVGh(G, 0, NV); } void CreateSubG( graphNew* G_src, long start, long size, graphNew* G_sub, long* M_sub2src, long* M_sub2ghost ) { long end = start + size; long NV_s = G_src->numVertices; long NE_s = G_src->numEdges; long* off_s = G_src->edgeListPtrs; edge* edge_s = G_src->edgeList; map<long, long> clusterLocalMap; //Map each neighbor's cluster to a local number map<long, long>::iterator storedAlready; long numUniqueClusters = 0; long num_v_par = 0; long num_e_par = 0; long v = start; map<long, long> map_ghost; map<long, long> map_all; map<long, long>::iterator iter_ghost; map<long, long>::iterator iter_all; while (1){ long adj1 = off_s[v]; long adj2 = off_s[v+1]; int dgr = adj2-adj1; iter_all = map_all.find(v); } for(long v=start; v < end; v++){ long adj1 = off_s[v]; long adj2 = off_s[v+1]; int degree = adj2 - adj1; for(long e=0; e<degree; e++){ long head = edge_s[v+e].head; long tail = edge_s[v+e].tail; bool isHeadin = (head>= start) && (head<end); bool isTailin = (tail>= start) && (tail<end); bool isEgAllIn = isHeadin && isTailin; bool isEgAllOut = (!isHeadin) && (!isTailin); bool isOnlyHeadIn = isHeadin && (!isTailin); bool isOnlyTailIn = isTailin && (!isHeadin); long head_m; long tail_m; //Remap the head and tail if(isEgAllOut){ continue; }else{ storedAlready = clusterLocalMap.find(head); if( storedAlready != clusterLocalMap.end() ){ head_m = storedAlready->second; //Renumber the cluster id }else{ clusterLocalMap[head] = numUniqueClusters;////Does not exist, add to the map head_m = numUniqueClusters; //Renumber the cluster id numUniqueClusters++; //Increment the number } storedAlready = clusterLocalMap.find(tail); if( storedAlready != clusterLocalMap.end() ){ tail_m = storedAlready->second; //Renumber the cluster id }else{ clusterLocalMap[tail] = numUniqueClusters;////Does not exist, add to the map tail_m = numUniqueClusters; //Renumber the cluster id numUniqueClusters++; //Increment the number } } edge_s[v+e].head = head_m; edge_s[v+e].tail = tail_m; } } } void CopyG( graphNew* G_scr, graphNew* G_des ) { long NV = G_scr->numVertices; long NE = G_scr->numEdges; G_des->numEdges = NE; G_des->numVertices = NV; long* vtxPtr = G_scr->edgeListPtrs; edge* vtxInd = G_scr->edgeList; long* vtxPtr2 = G_des->edgeListPtrs; edge* vtxInd2 = G_des->edgeList; for(int v = 0; v< NV; v++){ long adj1 = vtxPtr[0+v]; long adj2 = vtxPtr[0+v+1]; vtxPtr2[v] = adj1 - 0; vtxPtr2[v+1] = adj2 - 0; int degree = adj2 - adj1; long adj1_des = vtxPtr2[v]; for( int d=0; d < degree; d++){ vtxInd2[adj1_des+d].head = vtxInd[adj1+d].head; vtxInd2[adj1_des+d].tail = vtxInd[adj1+d].tail; vtxInd2[adj1_des+d].weight = vtxInd[adj1+d].weight; } } } graphNew* CloneGbad( graphNew* G_scr){ long NV = G_scr->numVertices; long NE = G_scr->numEdges; graphNew* G_des = (graphNew*)malloc(sizeof( graphNew)); G_des->edgeListPtrs = (long* )malloc(sizeof( long ) * (NV+1)); G_des->edgeList = (edge* )malloc(sizeof( edge ) * NE); CopyG(G_scr, G_des); return G_des; } void CreatSubG( long head, long end_line, graphNew* G_scr, graphNew* G_des ) { long NV = G_scr->numVertices; long* vtxPtr = G_scr->edgeListPtrs; edge* vtxInd = G_scr->edgeList; long NE = G_scr->numEdges; G_des->numVertices = G_scr->numVertices; G_des->numEdges = G_scr->numEdges; G_des->edgeListPtrs = (long*)malloc(sizeof(long)*(NV+1)); long base_edge = vtxPtr[head]; long size_edge = vtxPtr[head + end_line] - base_edge; G_des->edgeList = (edge*)malloc(sizeof(edge)*size_edge); long* vtxPtr2 = G_des->edgeListPtrs; edge* vtxInd2 = G_des->edgeList; for(int v = 0; v< NV; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2 - adj1; if(v >= head && v < (head + end_line)){ vtxPtr2[v] = adj1 - base_edge;//txPtr[head] vtxPtr2[v+1] = adj2 - base_edge;//txPtr[head] long adj1_des = vtxPtr2[v]; for( int d=0; d < degree; d++){ vtxInd2[adj1_des+d].head = vtxInd[adj1+d].head; vtxInd2[adj1_des+d].tail = vtxInd[adj1+d].tail; vtxInd2[adj1_des+d].weight = vtxInd[adj1+d].weight; } }else if( v<head){ vtxPtr2[v] = 0; vtxPtr2[v+1] = 0; }else{ vtxPtr2[v] = size_edge; vtxPtr2[v+1] = size_edge; } } } graphNew* CloneG(graphNew* G_scr) { long NV = G_scr->numVertices; graphNew*G_des = (graphNew*)malloc(sizeof( graphNew)); CreatSubG(0, NV, G_scr, G_des); return G_des; } void InitC(long* C, long NV){ assert(C); for(int i=0;i< NV; i++) C[i]=i; } ///////////////////////////////////////////////////////////////////////////////////// ///GLV////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// GLV::GLV(int& id){ InitVar(); ID=id; sprintf(name, "%d", id); id++; } GLV::~GLV(){FreeMem();} void GLV::InitVar(){ G=0; C=0; M=0; colors=0; NC=NElg=NVl=0; NV=-1; NE=-1; numColors=-1; numThreads = 1; Q=0; times.parNo=-1;//No partition }; void GLV::FreeMem(){ if(G) FreeG(G); if(C) free(C); if(M) free(M); if(colors) free(colors); } void GLV::CleanCurrentG() { if(G!=0){ #ifdef PRINTINFO_PARLV printf("GLV: Current G is not empty!!!: \n"); printf("GLV: To be clean G in GLV: "); printSimple(); //displayGraphCharacteristics(G); printf("GLV: FreeMem\n"); #endif FreeMem(); #ifdef PRINTINFO_PARLV printf("GLV: InitVar\n"); #endif InitVar(); } } void GLV::InitByFile(char* name_file){ double totTimeColoring; CleanCurrentG(); G = host_PrepareGraph( 3, name_file, 0); SyncWithG(); InitM(); displayGraphCharacteristics(G); printf("INFO: GLV: NV = %ld\t NE = %ld\t numColor = %d \n", NV, NE, numColors); } void GLV::InitByOhterG(graphNew* G_orig){ assert(G_orig); CleanCurrentG(); G = CloneG(G_orig); SyncWithG(); InitM(); printf("INFO: GLV: NV = %ld\t NE = %ld\t numColor = %d \n", NV, NE, numColors); } void GLV::SetByOhterG(graphNew* G_src){ assert(G_src); CleanCurrentG(); G = G_src; SyncWithG(); InitM(); #ifdef PRINTINFO_PARLV printf("GLV: NV = %ld\t NE = %ld\t numColor = %d \n", NV, NE, numColors); #endif } void GLV::RstNVlByM(){ NVl=0; for(int i=0;i<NV;i++) if(M[i]>=0)NVl++; } void GLV::RstNVElg(){ NElg=0; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; for(long v=0; v<NV; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; if(M[v]<0) continue; for(long k=adj1; k<adj2; k++){ edge e = vtxInd[k]; if(M[e.tail]<0) NElg++; } }//for v } void GLV::SetByOhterG(graphNew* G_src, long* M_src){ assert(G_src); CleanCurrentG(); G = G_src; SyncWithG(); if(M)free(M); M=M_src; RstNVlByM(); RstNVElg(); #ifdef PRINTINFO_PARLV printf("GLV: NV = %ld\t NE = %ld\t numColor = %d \n", NV, NE, numColors); #endif } void GLV::SetM(long* M_src){ assert(M_src); assert(G); NVl=0; for(int i=0; i<NV; i++){ M[i] = M_src[i]; if(M[i]>=0) NVl++; } RstNVElg(); } void GLV::SetM(){ assert(G); for(int i=0; i<NV; i++) M[i] = i; NVl=NV; } void GLV::InitM(long* M_src){ assert(M_src); assert(G); NV = G->numVertices; NE = G->numEdges; if(M){ printf("GLV: InitM: M is not empty and will be free and re-allocated.\n"); free(M); } M = (long *) malloc (NV * sizeof(long)); SetM(M_src); } void GLV::InitM(){ assert(G); NV = G->numVertices; NE = G->numEdges; if(M){ printf("GLV: InitM: M is not empty and will be free and re-allocated.\n"); free(M); } M = (long *) malloc (NV * sizeof(long)); SetM(); } void GLV::SetC(long* C_src){ assert(C_src); assert(G); NV = G->numVertices; NE = G->numEdges; for(int i=0; i<NV; i++) C[i] = C_src[i]; } void GLV::SetC(){ assert(G); NV = G->numVertices; NE = G->numEdges; for(int i=0; i<NV; i++) C[i] = i; NC = NV; } void GLV::InitC(long* C_src){ assert(C_src); assert(G); NV = G->numVertices; NE = G->numEdges; if(C){ #ifdef PRINTINFO_PARLV printf("GLV: InitC: C is not empty and will be free and re-allocated.\n"); #endif free(C); } C = (long *) malloc (NV * sizeof(long)); SetC(C_src); } void GLV::InitC(){ assert(G); NV = G->numVertices; NE = G->numEdges; if(C){ #ifdef PRINTINFO_PARLV printf("GLV: InitC: C is not empty and will be free and re-allocated.\n"); #endif free(C); } C = (long *) malloc (NV * sizeof(long)); SetC(); } void GLV::ResetColor() { double totTimeColoring; numColors = Phaseloop_UsingFPGA_InitColorBuff(G, colors, numThreads, totTimeColoring); } void GLV::ResetC() { this->com_list.clear(); InitC();/* FeatureLV f1(this); f1.PrintFeature(); com_list.push_back(f1);*/ } void GLV::SyncWithG(){ double totTimeColoring; assert(G); if( NV < G->numVertices){ if(C)free(C); C = (long *) malloc (G->numVertices * sizeof(long)); if(colors) free(colors); colors = (int*)malloc(G->numVertices * sizeof(int)); } NV = G->numVertices; NE = G->numEdges; ResetColor(); ResetC(); } void GLV::InitG(graphNew* G_src){ assert(G_src); if(G) CleanCurrentG(); G = CloneG(G_src); NV = G->numVertices; NE = G->numEdges; } void GLV::SetName(char* nm){strcpy(name, nm);}; void GLV::InitColor(){ //double totTimeColoring; assert(G); NV = G->numVertices; NE = G->numEdges; if(colors) free(colors); colors = (int*)malloc(G->numVertices * sizeof(int)); ResetColor(); } void GLV::print(){ printSimple(); assert(G); assert(C); assert(M); printG(G, C, M); } void GLV::printSimple(){ //list<FeatureLV>::iterator iter = com_list.back(); //list<FeatureLV>::iterator iter = com_list[com_list.size() - 1]; //Q = com_list.back().Q; //long NC = this->NC;//com_list.back().NC; if(NC==NV) printf("| GLV ID: %-2d| NC/NV: \033[1;37;40m%8ld\033[0m/", ID, NC); else printf("| GLV ID: %-2d| NC/NV: \033[1;31;40m%8ld\033[0m/", ID, NC); if(NV<(1)){ if(NV==NVl) printf(" \033[1;37;40m%-3ld\033[0m(%-3ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); else printf(" \033[1;37;40m%-3ld\033[0m(%-3ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); }else if(NV<(1000000)){ if(NV==NVl) printf(" \033[1;37;40m%-6ld\033[0m(%-5ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); else printf(" \033[1;37;40m%-6ld\033[0m(%-5ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); }else{ if(NV==NVl) printf(" \033[1;37;40m%-6ld\033[0m(%-8ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); else printf(" \033[1;37;40m%-6ld\033[0m(%-8ld/%2d%%)", NV, (NV-NVl), (int)(100*(float)(NV-NVl)/(float)NV)); } if(NE<(1000)){ if(NElg==0) printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); else printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); }else if(NE<(1000000)){ if(NElg==0) printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); else printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); }else{ if(NElg==0) printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); else printf(" NE: %9ld(%-9ld/%2d%%)| Colors:%-6d ", NE, NElg, (int)(100*(float)NElg/(float)NE), numColors); } if(Q>0) printf(" Q: \033[1;32;40m%1.6f\033[0m ", Q); else printf(" Q:\033[1;37;40m%2.6f\033[0m ", Q); printf("| name: %s \n",name); } void GLV::PushFeature(int ph, int iter, double time, bool FPGA){ FeatureLV f1(this); f1.No_phase = ph; f1.Num_iter = iter; f1.time = time; f1.isFPGA = FPGA; this->com_list.push_back(f1); this->NC = f1.NC; this->Q =f1.Q; } void GLV::printFeature(){ list<FeatureLV>::iterator iter=com_list.begin(); while(iter!=com_list.end()){ (*iter).PrintFeature(); iter++; } } void GLV::SetName_par(int ID_par, int ID_src, long start, long end, int th) { char nm[256]; sprintf(nm, "ID_%d_ParID_%d_%ld_%ld_th%d", ID_par, ID_src, start, end, th); this->SetName(nm); } void GLV::SetName_lv(int ID_par, int ID_src) { char nm[256]; sprintf(nm,"ID_%d_lv_ID_%d",ID_par, ID_src); this->SetName(nm); } void GLV::SetName_ParLvMrg(int num_par, int ID_src) { char nm[256]; sprintf(nm,"ID_%d_Mrg_lv_Par%d_ID_%d", ID, num_par, ID_src); this->SetName(nm); } void GLV::SetName_loadg(int ID_curr, char* path) { char nm[256]; sprintf(nm, "ID_%d_%s", ID_curr ,path ); this->SetName(nm); } void GLV::SetName_cat( int ID_src1, int ID_src2) { char nm[256]; sprintf(nm,"ID_%d_cat_ID_%d_ID%d", ID, ID_src1, ID_src2); this->SetName(nm); } //////////////////////////////////////////////////////////////////////////// SttGPar::SttGPar(long s, long e){ assert (e>s); start = s; end = e; num_v = num_e = num_e_dir = num_e_ll_dir = 0; num_v_l = num_v_g = 0; num_e_ll = num_e_lg = num_e_gl = num_e_gg = 0; } SttGPar::SttGPar(){ num_v = num_e = num_e_dir = num_e_ll_dir = 0; num_v_l = num_v_g = 0; num_e_ll = num_e_lg = num_e_gl = num_e_gg = 0; } void SttGPar::PrintStt(){ printf("**SttGPar::PrintStt BEGIN**\n"); printf("From %ld to %ld \n", start, end); num_v_l = end-start; printf("Total V : %ld\t Total Vl : %ld\t Total Vg: %ld\t Vl/V=%2.2f%% \n", num_v, num_v_l, num_v_g, (float)num_v_l/(float)num_v*100.0); assert (num_e_lg == num_e-num_e_ll); printf("Total 2E: %ld\t Total ll : %ld\t Total lg: %ld\t ll/E=%2.2f%% \n", num_e, num_e_ll, num_e_lg, (float)num_e_ll/(float)num_e*100.0); printf("Total|E|: %ld\t Total |ll|: %ld\t Total lg: %ld\t |ll|/|E|=%2.2f%% \n", num_e_dir, num_e_ll_dir, num_e_lg, (float)num_e_ll_dir/(float)num_e_dir*100.0); printf("**SttGPar::PrintStt END**\n"); } bool SttGPar::InRange(long v){ return v >= start && v < end; } void SttGPar::AddEdge(edge* edges, long head, long tail, double weight, long* M_g) { long head_m = head - start; long off = end - start; long tail_m; map<long , long>::iterator itr; num_e++; //num_e if( InRange(tail)){ num_e_ll++; if(head <= tail){ tail_m = tail - start; edges[num_e_dir].head = head_m; edges[num_e_dir].tail = tail_m; edges[num_e_dir].weight = weight; num_e_ll_dir++; num_e_dir++; } }else{ itr = map_v_g.find(tail); if(itr == map_v_g.end()){ tail_m = num_v_g + off; M_g[tail_m] = -tail-1;// using negtive to indicate it ghost map_v_g[tail] = num_v_g++; //printf("NODIR(%ld)\t: lg:<%ld %ld> -> <%ld %ld> \t= %ld + %ld \n", num_e_dir, head, tail, head_m, tail_m, num_v_g, off); }else { tail_m = itr->second + off; //printf("NODIR(%ld)\t: lg:<%ld %ld> -> <%ld %ld> \t= %ld + %ld \n", num_e_dir, head, tail, head_m, tail_m, itr->second, off); } edges[num_e_dir].head = head_m; edges[num_e_dir].tail = tail_m; edges[num_e_dir].weight = weight; num_e_lg++; num_e_dir++; } num_v_l = end - start; num_v = num_v_l + num_v_g; } long SttGPar::findAt(VGMinDgr& gMinDgr, long tail, long dgr, long num_vg, int th_maxGhost) { long index = 0; long low = 0, high; if(th_maxGhost == 1) { if(dgr < gMinDgr.dgrs[0] || (dgr == gMinDgr.dgrs[0] && tail < gMinDgr.tail[0]) ) return 0; else return -1; } else if(th_maxGhost > 1) { //th_maxGhost > 1 && num_vg < th_maxGhost high = num_vg < th_maxGhost ? num_vg-1 : th_maxGhost-1; if(dgr < gMinDgr.dgrs[0] || (dgr == gMinDgr.dgrs[0] && tail < gMinDgr.tail[0])) return 0; else { while(low <= high) { index = (low + high)/2; if(dgr == gMinDgr.dgrs[index] && tail == gMinDgr.tail[index]) return -1; else if(dgr < gMinDgr.dgrs[index] || (dgr == gMinDgr.dgrs[index] && tail < gMinDgr.tail[index])) high = index - 1; else if (dgr > gMinDgr.dgrs[index] || (dgr == gMinDgr.dgrs[index] && tail > gMinDgr.tail[index]) ) low = index + 1; } return low; } } else return -1; } void SttGPar::EdgePruning(edge* edges, long head, long tail, double weight, long* M_g, VGMinDgr& gMinDgr, long& num_vg, long& e_dgr, int th_maxGhost) { long head_m = head - start; long tail_m; //num_e if( InRange(tail)){ num_e++; num_e_ll++; if(head<=tail){ tail_m = tail - start; //printf("NODIR(%ld)\t: ll:<%ld %ld> -> <%ld %ld> \t= %ld - %ld \n", num_e_dir, head, tail, head_m, tail_m, tail, start); edges[num_e_dir].head = head_m; edges[num_e_dir].tail = tail_m; edges[num_e_dir].weight = weight; num_e_ll_dir++; num_e_dir++; } } else{ //printf("tail=%ld dgr= %ld \n", tail, e_dgr); if(num_vg == 0) { gMinDgr.tail[0] = tail; gMinDgr.dgrs[0] = e_dgr; gMinDgr.wght[0] = weight; } else { long at = findAt(gMinDgr, tail, e_dgr, num_vg, th_maxGhost); if(at >= 0 && at < th_maxGhost) { long where = num_vg < th_maxGhost ? num_vg : (th_maxGhost - 1); for(int i = where; i > at; i--) { gMinDgr.tail[i] = gMinDgr.tail[i-1]; gMinDgr.dgrs[i] = gMinDgr.dgrs[i-1]; gMinDgr.wght[i] = gMinDgr.wght[i-1]; } gMinDgr.tail[at] = tail; gMinDgr.dgrs[at] = e_dgr; gMinDgr.wght[at] = weight; // printf("insert: at= %ld \n", at); } } num_vg++; } } void SttGPar::CountVPruning( graphNew* G, long st, long ed, int th_maxGhost){ assert (G); assert (ed>st); start = st; end = ed; long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; assert (end <= NV); long ne = vtxPtr[end]- vtxPtr[start]; edge* elist = (edge*)malloc(sizeof(edge) * (ne)); long* M_g = (long*)malloc(sizeof(long) * (NV)); //long off = end - start; long off = end - start; for(int i=0; i<NV; i++){ M_g[i] = i<off? i + start : -2; } for(long v = start; v < end; v++){ map<long , long>::iterator itr; VGMinDgr gMinDgr; long num_vg = 0; long e_dgr = 0; long head_m = 0, tail_m = 0; long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d=0; d<degree; d++) { long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; e_dgr = vtxPtr[e+1] - vtxPtr[e]; head_m = v - start; EdgePruning(elist, v, e, w, M_g, gMinDgr, num_vg, e_dgr, th_maxGhost ); }//for long smallest = num_vg < th_maxGhost ? num_vg : th_maxGhost; for(int i = 0; i < smallest; i++) { itr = map_v_g.find(gMinDgr.tail[i]); if(itr == map_v_g.end()){ tail_m = num_v_g + off; M_g[tail_m] = -gMinDgr.tail[i] - 1; map_v_g[gMinDgr.tail[i]] = num_v_g++; } else { tail_m = itr->second + off; } elist[num_e_dir].head = head_m; elist[num_e_dir].tail = tail_m; elist[num_e_dir].weight = gMinDgr.wght[i]; num_e_lg++; num_e_dir++; num_e++; printf("vertex= %ld\t nGhost= %ld\t sGhost= %ld\t degree= %ld\t\n", v, num_vg, gMinDgr.tail[i], gMinDgr.dgrs[i]); } } num_v_l = end - start; num_v = num_v_l + num_v_g; graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GetGFromEdge(Gnew, elist, num_v, num_e_dir); //printG(Gnew); printG(Gnew, M_g); FreeG(Gnew); free(elist); free(M_g); } void SttGPar::CountV( graphNew* G, long st, long ed, edge* elist, long* M_g){ assert (G); assert (ed>st); start = st; end = ed; long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; assert (end <= NV); long ne = vtxPtr[end]- vtxPtr[start]; elist = (edge*)malloc(sizeof(edge) * (ne)); M_g = (long*)malloc(sizeof(long) * (NV)); //long off = end - start; long off = end - start; for(int i=0; i<NV; i++){ M_g[i] = i<off? i + start : -2; } for(long v = start; v < end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; AddEdge(elist, v, e, w, M_g); }//for } graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GetGFromEdge(Gnew, elist, num_v, num_e_dir); //printG(Gnew); printG(Gnew, M_g); FreeG(Gnew); free(elist); free(M_g); } void SttGPar::CountV( graphNew* G, long st, long ed){ assert (G); assert (ed>st); start = st; end = ed; long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; assert (end <= NV); long ne = vtxPtr[end]- vtxPtr[start]; edge* elist = (edge*)malloc(sizeof(edge) * (ne)); long* M_g = (long*)malloc(sizeof(long) * (NV)); //long off = end - start; long off = end - start; for(int i=0; i<NV; i++){ M_g[i] = i<off? i + start : -2; } for(long v = start; v < end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; AddEdge(elist, v, e, w, M_g); }//for } graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GetGFromEdge(Gnew, elist, num_v, num_e_dir); //printG(Gnew); printG(Gnew, M_g); FreeG(Gnew); free(elist); free(M_g); } GLV* CloneGlv( GLV* glv_src, int& id_glv) { assert (glv_src); GLV* glv = new GLV(id_glv); glv->InitG(glv_src->G); glv->InitC(glv_src->C); glv->InitM(glv_src->M); glv->InitColor(); return glv; } GLV* GLV::CloneSelf( int& id_glv) { GLV* glv = new GLV(id_glv); glv->Q = this->Q; glv->InitG(G); glv->InitC(C); glv->InitM(M); glv->InitColor(); return glv; } GLV* GLV::CloneSelf_lite( int& id_glv) { GLV* glv = new GLV(id_glv); glv->Q = this->Q; glv->G = this->G; glv->NV = this->NV; glv->NC = this->NV; glv->NE = this->NE; glv->NVl = this->NVl; glv->NElg = this->NElg; glv->InitC(C); glv->InitM(M); glv->InitColor(); return glv; } GLV* SttGPar::ParNewGlv( graphNew* G_src, long st, long ed, int& id_glv ){ assert (G_src); assert (ed>st); start = st; end = ed; long NV = G_src->numVertices; long* vtxPtr = G_src->edgeListPtrs; edge* vtxInd = G_src->edgeList; assert (end <= NV); long ne = vtxPtr[end]- vtxPtr[start]; edge* elist = (edge*)malloc(sizeof(edge) * (ne)); long* M_v = (long*)malloc(sizeof(long) * (NV));//address by v long off = end - start; for(int i=0; i<NV; i++){ M_v[i] = i<off? i + start : -2; } for(long v = start; v < end; v++){ long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; AddEdge(elist, v, e, w, M_v); }//for } graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GLV* glv = new GLV(id_glv); GetGFromEdge(Gnew, elist, num_v, num_e_dir); glv->SetByOhterG(Gnew); glv->SetM(M_v); //printG(Gnew); //FreeG(Gnew); free(elist); free(M_v); glv->NVl = ed-st; glv->RstNVElg(); return glv; } GLV* SttGPar::ParNewGlv_Prun(graphNew* G, long st, long ed, int& id_glv, int th_maxGhost){ start = st; end = ed; long NV = G->numVertices; long* vtxPtr = G->edgeListPtrs; edge* vtxInd = G->edgeList; assert (end <= NV); long ne = vtxPtr[end]- vtxPtr[start]; edge* elist = (edge*)malloc(sizeof(edge) * (ne)); long* M_v = (long*)malloc(sizeof(long) * (NV)); //long off = end - start; long off = end - start; for(int i=0; i<NV; i++){ M_v[i] = i<off? i + start : -2; } for(long v = start; v < end; v++){ map<long , long>::iterator itr; VGMinDgr gMinDgr; long num_vg = 0; long e_dgr = 0; long head_m = 0, tail_m = 0; long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d=0; d<degree; d++){ long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; e_dgr = vtxPtr[e+1] - vtxPtr[e]; head_m = v - start; EdgePruning(elist, v, e, w, M_v, gMinDgr, num_vg, e_dgr, th_maxGhost); }//for long smallest = num_vg < th_maxGhost ? num_vg : th_maxGhost; for(int i = 0; i < smallest; i++) { itr = map_v_g.find(gMinDgr.tail[i]); if(itr == map_v_g.end()){ tail_m = num_v_g + off; M_v[tail_m] = -gMinDgr.tail[i]-1; map_v_g[gMinDgr.tail[i]] = num_v_g++; } else { tail_m = itr->second + off; } elist[num_e_dir].head = head_m; elist[num_e_dir].tail = tail_m; elist[num_e_dir].weight = gMinDgr.wght[i]; num_e_lg++; num_e_dir++; num_e++; //printf("vertex= %ld\t nGhost= %ld\t sGhost= %ld\t degree= %ld\t\n", v, num_vg, gMinDgr.tail[i], gMinDgr.dgrs[i]); } } num_v_l = end - start; num_v = num_v_l + num_v_g; graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GLV* glv = new GLV(id_glv); GetGFromEdge(Gnew, elist, num_v, num_e_dir); glv->SetByOhterG(Gnew); glv->SetM(M_v); //printG(Gnew); //FreeG(Gnew); free(elist); free(M_v); return glv; } GLV* SttGPar::ParNewGlv_Prun(long start_tg, long* offsets_tg, edge* edgelist_tg, long* dgrlist_tg, long start_par, long size_par, int& id_glv, int th_maxGhost) { /*std::cout << "\nDEBUG: ParNewGlv_Prun " << "\n size_par=" << size_par << "\n id_glv=" << id_glv << std::endl;*/ start = start_par; // global ID of first local vertex (vertex in the partition) long ed_par = start_par+size_par; // 1 + global ID of last local vertex end = ed_par; long NV_par_local = end - start; // number of local vertices long NE_par = offsets_tg[end-start_tg] - offsets_tg[start-start_tg]; // number of edges connected to local vertices edge* elist = (edge*)malloc(sizeof(edge) * (NE_par)); // output partition edge list with local vertex IDs // Array of local IDs for all local vertices followed by encoded global IDs of ghost nodes for the current // partition. The array size is the sum of the number of local nodes plus the number of edges to cover the // worst-case scenario that every edge connects to a different ghost node. const unsigned long M_v_size = NV_par_local + NE_par; long* M_v = (long*)malloc(sizeof(long) * (M_v_size)); //long off = end - start; // Initialize M_v with all local vertices and set all possible ghost vertices to a dummy value //std::cout << "DEBUG: M_v_size = " << M_v_size << std::endl; for (int i=0; i < M_v_size; i++) { M_v[i] = i<NV_par_local? i + start : -2; } long cnt_e_input = offsets_tg[start_par-start_tg]; // index of current edge (used for dgrlist_tg) // Iterate through all local vertices of the partition, building the output edgelist for (long v = start; v < end; v++) { map<long , long>::iterator itr; VGMinDgr gMinDgr; // list of ghost vertices for the current local vertex sorted from smallest degree to largest long num_vg = 0; // number of ghost vertices for the current local vertex long head_m = 0, tail_m = 0; // locally (to the partition) renumbered vertices of the current edge long adj1 = offsets_tg[v - start_tg]; // index of first edge of current vertex long adj2 = offsets_tg[v+1 - start_tg]; // 1 + index of last edge of current vertex int degree = adj2-adj1; // number of edges of current vertex // Add each edge of v to elist (if tail is local) or gMinDgr (if tail is a ghost) for (int d = 0; d < degree; d++) { long e = edgelist_tg[adj1+d].tail; double w = edgelist_tg[adj1+d].weight; long e_dgr2 = dgrlist_tg[cnt_e_input]; head_m = v - start; EdgePruning(elist, v, e, w, M_v, gMinDgr, num_vg, e_dgr2, th_maxGhost); cnt_e_input++; } // Add edges for ghost nodes collected in gMinDgr, limited to th_maxGhost edges long smallest = num_vg < th_maxGhost ? num_vg : th_maxGhost; for(int i = 0; i < smallest; i++) { itr = map_v_g.find(gMinDgr.tail[i]); if(itr == map_v_g.end()){ tail_m = num_v_g + NV_par_local; // next free slot in M_v M_v[tail_m] = -gMinDgr.tail[i]-1; // Save encoded global ID of ghost node in M_v map_v_g[gMinDgr.tail[i]] = num_v_g++; // Maps from ghost global ID to slot in M_v } else { tail_m = itr->second + NV_par_local; // Reuse ghost node already seen } elist[num_e_dir].head = head_m; elist[num_e_dir].tail = tail_m; elist[num_e_dir].weight = gMinDgr.wght[i]; num_e_lg++; num_e_dir++; num_e++; //printf("DBG_PAR:vertex= %ld\t nGhost= %ld\t sGhost= %ld\t degree= %ld\t\n", v, num_vg, gMinDgr.tail[i], gMinDgr.dgrs[i]); } } // Convert the new edgelist and M_v into a GLV. The offset list is inferred from the edgelist. num_v_l = end - start; num_v = num_v_l + num_v_g; graphNew* Gnew = (graphNew*)malloc(sizeof(graphNew)); GLV* glv = new GLV(id_glv); GetGFromEdge(Gnew, elist, num_v, num_e_dir); glv->SetByOhterG(Gnew); glv->SetM(M_v); free(elist); free(M_v); return glv; } void SttGPar::CountV(graphNew* G, edge* elist, long* M_g) { long NV = G->numVertices; return CountV(G, 0, NV, elist, M_g); } void SttGPar::CountV(graphNew* G) { long NV = G->numVertices; return CountV(G, 0, NV); } void GetGFromEdge(graphNew *G, edge *edgeListTmp, long num_v, long num_e_dir) { //Parse the first line: long NV = num_v, ED=num_e_dir*2, NE=num_e_dir; printf("|V|= %ld, |E|= %ld \n", NV, NE); //Remove duplicate entries: //Allocate for Edge Pointer and keep track of degree for each vertex long *edgeListPtr = (long *) malloc((NV+1) * sizeof(long)); #pragma omp parallel for for (long i=0; i <= NV; i++) edgeListPtr[i] = 0; //For first touch purposes #pragma omp parallel for for(long i=0; i<NE; i++) { __sync_fetch_and_add(&edgeListPtr[edgeListTmp[i].head + 1], 1); //Plus one to take care of the zeroth location __sync_fetch_and_add(&edgeListPtr[edgeListTmp[i].tail + 1], 1); } // Build the EdgeListPtr Array: Cumulative addition for (long i=0; i<NV; i++) { edgeListPtr[i+1] += edgeListPtr[i]; //Prefix Sum: } //The last element of Cumulative will hold the total number of characters printf("DEBUG: Sanity Check: 2|E| = %ld, edgeListPtr[NV]= %ld\n", NE*2, edgeListPtr[NV]); edge *edgeList = (edge *) malloc ((2*NE) * sizeof(edge)); //Every edge stored twice assert(edgeList != 0); // Keep track of how many edges have been added for a vertex: long *added = (long *) malloc (NV * sizeof(long)); assert (added != 0); #pragma omp parallel for for (long i = 0; i < NV; i++) added[i] = 0; //Build the edgeList from edgeListTmp: //#pragma omp parallel for for(long i=0; i<NE; i++) { long head = edgeListTmp[i].head; long tail = edgeListTmp[i].tail; double weight = edgeListTmp[i].weight; long Where = edgeListPtr[head] + __sync_fetch_and_add(&added[head], 1); edgeList[Where].head = head; edgeList[Where].tail = tail; edgeList[Where].weight = weight; //added[head]++; //Now add the counter-edge: Where = edgeListPtr[tail] + __sync_fetch_and_add(&added[tail], 1); edgeList[Where].head = tail; edgeList[Where].tail = head; edgeList[Where].weight = weight; //added[tail]++; } G->sVertices = NV; G->numVertices = NV; G->numEdges = NE; G->edgeListPtrs = edgeListPtr; G->edgeList = edgeList; //free(edgeListTmp); free(added); } long GetGFromEdge_selfloop(graphNew * G, edge *edgeListTmp, long num_v, long num_e_dir) { long NV = num_v, ED=num_e_dir*2, NE=num_e_dir; //Remove duplicate entries: /* long NewEdges = removeEdges(NV, NE, edgeListTmp); if (NewEdges < NE) { printf("GetGFromEdge_selfloop: Number of duplicate entries detected: %ld\n", NE-NewEdges); NE = NewEdges; //Only look at clean edges }*/ #ifdef PRINTINFO_PARLV printf("|V|= %ld, |E|= %ld \n", NV, NE); #endif long *edgeListPtr = (long *) malloc((NV+1) * sizeof(long)); #pragma omp parallel for for (long i=0; i <= NV; i++) edgeListPtr[i] = 0; //For first touch purposes #pragma omp parallel for for(long i=0; i<NE; i++) { __sync_fetch_and_add(&edgeListPtr[edgeListTmp[i].head + 1], 1); //Plus one to take care of the zeroth location if(edgeListTmp[i].head != edgeListTmp[i].tail) __sync_fetch_and_add(&edgeListPtr[edgeListTmp[i].tail + 1], 1); } //////Build the EdgeListPtr Array: Cumulative addition for (long i=0; i<NV; i++) { edgeListPtr[i+1] += edgeListPtr[i]; //Prefix Sum: } //The last element of Cumulative will hold the total number of characters #ifdef PRINTINFO_PARLV printf("Sanity Check: 2|E| = %ld, edgeListPtr[NV]= %ld GetGFromEdge_selfloop\n", NE*2, edgeListPtr[NV]); #endif // printf("About to allocate memory for graph data structures\n"); edge *edgeList = (edge *) malloc ((2*NE) * sizeof(edge)); //Every edge stored twice assert(edgeList != 0); //Keep track of how many edges have been added for a vertex: long *added = (long *) malloc (NV * sizeof(long)); assert (added != 0); #pragma omp parallel for for (long i = 0; i < NV; i++) added[i] = 0; // printf("About to build edgeList...\n"); //Build the edgeList from edgeListTmp: //#pragma omp parallel for for(long i=0; i<NE; i++) { long head = edgeListTmp[i].head; long tail = edgeListTmp[i].tail; double weight = edgeListTmp[i].weight; long Where = edgeListPtr[head] + __sync_fetch_and_add(&added[head], 1); edgeList[Where].head = head; edgeList[Where].tail = tail; edgeList[Where].weight = weight; //added[head]++; //Now add the counter-edge: //printf("GetGFromEdge_selfloop e=%-6d head=%-6d tail=%-6d w=%-4.0f where(%d)=%d + added[head](%d) \n",i, head, tail, weight, Where, edgeListPtr[head], added[head]); if(head != tail){ Where = edgeListPtr[tail] + __sync_fetch_and_add(&added[tail], 1); edgeList[Where].head = tail; edgeList[Where].tail = head; edgeList[Where].weight = weight; } //added[tail]++; } G->sVertices = NV; G->numVertices = NV; G->numEdges = NE; G->edgeListPtrs = edgeListPtr; G->edgeList = edgeList; //free(edgeListTmp); free(added); return NE; } ////////////////////////////////////////////////////////////////// double FeatureLV::ComputeQ(GLV* glv){ assert(glv->G); NV = glv->G->numVertices; NE = glv->G->numEdges; long* vtxPtr = glv->G->edgeListPtrs; edge* vtxInd = glv->G->edgeList; long* tot_m = (long*)malloc(sizeof(long)*NV); for(int v=0; v< NV; v++) tot_m[v]=0; m=0; for(int v=0; v< NV; v++){ long cid = glv->C[v]; long adj1 = vtxPtr[v]; long adj2 = vtxPtr[v+1]; int degree = adj2-adj1; for(int d =0; d<degree; d++){ long e = vtxInd[adj1+d].tail; double w = vtxInd[adj1+d].weight; long cide = glv->C[e]; m+=w; tot_m[cide]+=w; if(cide==cid) totalIn+=w; } } NC=0; for(int v=0; v< NV; v++){ totalTot+=tot_m[v]*tot_m[v]; if(tot_m[v]) NC++; } Q = totalIn/m - totalTot/(m*m); free(tot_m); glv->Q = Q; return Q; } double FeatureLV::ComputeQ2(GLV* glv){ assert(glv->G); NV = glv->G->numVertices; NE = glv->G->numEdges; long* vtxPtr = glv->G->edgeListPtrs; edge* vtxInd = glv->G->edgeList; long* tot_m = (long*)malloc(sizeof(long)*NV); for(int v=0; v< NV; v++) tot_m[v]=0; m=0; for(int e=0; e< NE; e++){ long head = vtxInd[e].head; long tail = vtxInd[e].tail; double w = vtxInd[e].weight; long cid = glv->C[head]; long cide = glv->C[tail]; m+=w; tot_m[cide]+=w; if(cide==cid) totalIn+=w; } NC=0; for(int v=0; v< NV; v++){ totalTot+=tot_m[v]*tot_m[v]; if(tot_m[v]) NC++; } Q = totalIn/m - totalTot/(m*m); free(tot_m); return Q; } void FeatureLV::PrintFeature(){ printf("NC=%-8ld NV=%-8ld NE=%-8ld ", NC, NV, NE); printf("Q=%-2.6f m=%-8.1f totalTot=%-14.1f totalIn=%-8.1f ", Q, m, totalTot, totalIn); printf("No_phase=%-2d Num_iter=%-2d time=%-8.1f %s \n", No_phase, Num_iter, time, isFPGA==true?"FPGA":"CPU" ); } FeatureLV::FeatureLV(GLV* glv) { init(); ComputeQ(glv); } void FeatureLV::init(){ NV=NE=0; totalTot=totalIn=m=0; Q = -1; NC = 0; No_phase = Num_iter =0; time=0;isFPGA=true; } FeatureLV::FeatureLV(){ init(); }//FeatureLV() ////////////////////////////////////////////////////////////////////////////////////////// int glb_cnt_glv=0; GLV* CreateByFile_general(char* inFile, int& id_glv) { assert(inFile); FILE* fp = fopen(inFile, "r"); if (fp == NULL) { printf("\033[1;31;40mERROR\033[0m: L3 can't open input file %s\n", inFile); return NULL; } else fclose(fp); GLV *glv_src = new GLV(id_glv); glv_src->InitByFile(inFile); return glv_src; } GLV* CreateByFile_general(char* inFile){ assert(inFile); FILE* fp=fopen(inFile, "r"); if(fp==NULL){ printf("\033[1;31;40mERROR\033[0m: L3 can't open input file %s\n", inFile); return NULL; }else fclose(fp); GLV *glv_src = new GLV(glb_cnt_glv); glv_src->InitByFile(inFile); return glv_src; }
Zubrailx/university
year-1/Programming/lab-4/lab4/src/com/company/human/WoodenWoman.java
package com.company.human; import com.company.enums.*; import com.company.exceptions.SomeSameObjectsException; public class WoodenWoman extends AdvancedHumanWithBodyParts{ public static int id = 0; { id++; if (id > 1){ try { throw new SomeSameObjectsException("There can't be more than 1 Wooden Woman", id); }catch(SomeSameObjectsException ex){ System.out.println("-----------------------------------------------------------\n" + ex.getMessage()); System.out.println("Your number of objects: " + ex.getValue()+"\n-----------------------------------------------------------"); } } } private final String height = Adjective.BIG.getValueOfAdjective(); private final String kindOfBody = Adjective.WOODEN.getValueOfAdjective(); public WoodenWoman(){ super("Wooden Woman", Location.WATER); } public Cheeks cheeks = new Cheeks(Adjective.ROSY); public Eyes eyes = new Eyes(Adjective.ROUND, Adjective.WIDELY_OPENED, Adjective.BLUE); public Face face = new Face(Adjective.SMILING); public Hair hair = new Hair(Adjective.BLUE, Adjective.LONG); public Lips lips = new Lips(Adjective.ROSY); public String getHeight() { return height; } public String getKindOfBody(){ return kindOfBody; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; WoodenWoman objH = (WoodenWoman) obj; return this.getName().equals(objH.getName()) && this.getName() != null && this.getLocation().equals(objH.getLocation()) && this.getHeight().equals(objH.getHeight()) && this.getKindOfBody().equals(objH.getKindOfBody()); } @Override public int hashCode() { final int prime = 21; int result = 1; result = prime * result + ((this.getName() == null) ? 0: this.getName().hashCode()) + ((this.getLocation() == null) ? 0: this.getLocation().hashCode()*3) + ((this.getKindOfBody() == null)? 0: this.getKindOfBody().hashCode())*5 + ((this.getHeight() == null) ? 0: this.getHeight().hashCode())*7; return result; } @Override public String toString() { return "AdvancedHumanWithBodyParts." + this.getName() + ", location: " + this.getLocation() + ", height: " + this.getHeight() + ", kindOfBody: " + this.getKindOfBody(); } }
lightxun/LightJoker-For-Web
code/jq+bootstrap/Plugins/ckeditor/v4.14.1/plugins/uicolor/lang/sq.js
<gh_stars>1-10 /** * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'uicolor', 'sq', { title: 'UI Mbledhës i Ngjyrave', options: 'Variantet e Ngjyrave', highlight: 'Theksuar', selected: 'Ngjyra e Përzgjedhur', predefined: 'Setet e paradefinuara të ngjyrave', config: 'Hidhni këtë varg në skedën tuaj config.js' } );
deltegic/deltegic
thirdparty/aria2/src/XmlRpcRequestParserStateMachine.cc
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2011 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "XmlRpcRequestParserStateMachine.h" #include "XmlRpcRequestParserController.h" #include "XmlRpcRequestParserStateImpl.h" namespace aria2 { namespace rpc { namespace { auto initialState = new InitialXmlRpcRequestParserState(); auto unknownElementState = new UnknownElementXmlRpcRequestParserState(); auto methodCallState = new MethodCallXmlRpcRequestParserState(); auto methodNameState = new MethodNameXmlRpcRequestParserState(); auto paramsState = new ParamsXmlRpcRequestParserState(); auto paramState = new ParamXmlRpcRequestParserState(); auto valueState = new ValueXmlRpcRequestParserState(); auto intState = new IntXmlRpcRequestParserState(); auto stringState = new StringXmlRpcRequestParserState(); auto base64State = new Base64XmlRpcRequestParserState(); auto structState = new StructXmlRpcRequestParserState(); auto memberState = new MemberXmlRpcRequestParserState(); auto nameState = new NameXmlRpcRequestParserState(); auto arrayState = new ArrayXmlRpcRequestParserState(); auto dataState = new DataXmlRpcRequestParserState(); auto arrayValueState = new ArrayValueXmlRpcRequestParserState(); } // namespace XmlRpcRequestParserStateMachine::XmlRpcRequestParserStateMachine() : controller_(new XmlRpcRequestParserController()) { stateStack_.push(initialState); } XmlRpcRequestParserStateMachine::~XmlRpcRequestParserStateMachine() { delete controller_; } void XmlRpcRequestParserStateMachine::reset() { controller_->reset(); while (!stateStack_.empty()) { stateStack_.pop(); } stateStack_.push(initialState); } bool XmlRpcRequestParserStateMachine::needsCharactersBuffering() const { return stateStack_.top()->needsCharactersBuffering(); } bool XmlRpcRequestParserStateMachine::finished() const { return stateStack_.top() == initialState; } void XmlRpcRequestParserStateMachine::beginElement( const char* localname, const char* prefix, const char* nsUri, const std::vector<XmlAttr>& attrs) { stateStack_.top()->beginElement(this, localname, attrs); } void XmlRpcRequestParserStateMachine::endElement(const char* localname, const char* prefix, const char* nsUri, std::string characters) { stateStack_.top()->endElement(this, localname, std::move(characters)); stateStack_.pop(); } void XmlRpcRequestParserStateMachine::setMethodName(std::string methodName) { controller_->setMethodName(std::move(methodName)); } const std::string& XmlRpcRequestParserStateMachine::getMethodName() const { return controller_->getMethodName(); } void XmlRpcRequestParserStateMachine::popArrayFrame() { controller_->popArrayFrame(); } void XmlRpcRequestParserStateMachine::popStructFrame() { controller_->popStructFrame(); } void XmlRpcRequestParserStateMachine::pushFrame() { controller_->pushFrame(); } void XmlRpcRequestParserStateMachine::setCurrentFrameValue( std::unique_ptr<ValueBase> value) { controller_->setCurrentFrameValue(std::move(value)); } const std::unique_ptr<ValueBase>& XmlRpcRequestParserStateMachine::getCurrentFrameValue() const { return controller_->getCurrentFrameValue(); } std::unique_ptr<ValueBase> XmlRpcRequestParserStateMachine::popCurrentFrameValue() { return controller_->popCurrentFrameValue(); } void XmlRpcRequestParserStateMachine::setCurrentFrameName(std::string name) { controller_->setCurrentFrameName(std::move(name)); } void XmlRpcRequestParserStateMachine::pushUnknownElementState() { stateStack_.push(unknownElementState); } void XmlRpcRequestParserStateMachine::pushMethodCallState() { stateStack_.push(methodCallState); } void XmlRpcRequestParserStateMachine::pushMethodNameState() { stateStack_.push(methodNameState); } void XmlRpcRequestParserStateMachine::pushParamsState() { stateStack_.push(paramsState); } void XmlRpcRequestParserStateMachine::pushParamState() { stateStack_.push(paramState); } void XmlRpcRequestParserStateMachine::pushValueState() { stateStack_.push(valueState); } void XmlRpcRequestParserStateMachine::pushIntState() { stateStack_.push(intState); } void XmlRpcRequestParserStateMachine::pushStringState() { stateStack_.push(stringState); } void XmlRpcRequestParserStateMachine::pushBase64State() { stateStack_.push(base64State); } void XmlRpcRequestParserStateMachine::pushStructState() { stateStack_.push(structState); } void XmlRpcRequestParserStateMachine::pushMemberState() { stateStack_.push(memberState); } void XmlRpcRequestParserStateMachine::pushNameState() { stateStack_.push(nameState); } void XmlRpcRequestParserStateMachine::pushArrayState() { stateStack_.push(arrayState); } void XmlRpcRequestParserStateMachine::pushDataState() { stateStack_.push(dataState); } void XmlRpcRequestParserStateMachine::pushArrayValueState() { stateStack_.push(arrayValueState); } } // namespace rpc } // namespace aria2
Freankll/vue-cli-3.0
src/api/kabuto/data-collision.js
import fetch from '@/libs/fetch/fetch'; import {getUrlByEnv} from './kabuto-common'; /** * 查询数据碰撞 * @param parameter */ export function pageDataCollisions(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/page`), method: 'get', params }); } export function pageDataCollisionsByDissuadeUser(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/page-by-dissuade-user`), method: 'get', params }); } export function pageDataCollisionsByOrg(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/page-by-org`), method: 'get', params }); } export function getRelationVictimPage (params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/victim/relation`), method: 'get', params }); } export function getRelationSuspectPage(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/suspect/relation`), method: 'get', params }); } // 关联预警 export function getLinkedDiagram(obj) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/linked-diagram`), method: 'get', params: obj }); } // 相关预警 export function getRelationMapData(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/relation-diagram`), method: 'get', params }); } // 关键信息检索 export function searchKeyWorldCollisions(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/relation/keyword`), method: 'get', params }); } // 关联人物 export function getRelationPeople(params) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/linked-person`), method: 'get', params }); } // 关联图数据导出 // 文件类型导出 export function exportReationTable(data) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/diagram-data/excel`), method: 'get', responseType: 'blob', params: data }); } //获取挽损金额 export function getRecoverAmounts(data) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/recover-amounts/sum`), method: 'get', params: data }); } // 劝阻员导出 export function exportDissuaderTable(data) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/dissuade-user/excel`), method: 'get', responseType: 'blob', params: data }); } // 领导的导出 export function exportLeaderTable(data) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions/leader/excel`), method: 'get', responseType: 'blob', params: data }); } // 获取数据碰撞信息 // orginalid dataType export function getDataCollisionsInfo (data) { return fetch({ url: getUrlByEnv(`/kabuto/in/data-collisions`), method: 'get', params: data }); }
chrishmorris/PiMS
current/logic/src/org/pimslims/lab/experiment/LeftToRightGradient.java
package org.pimslims.lab.experiment; import java.util.Map; public class LeftToRightGradient extends Gradient { public LeftToRightGradient(float min, float max, String start, String end) { super(min, max, start, end); } @Override public Map<String, Float> gradient() { throw new UnsupportedOperationException("Not implemented yet"); } }
jjiege/odoo
addons/hr_payroll_account/wizard/hr_payroll_payslips_by_employees.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class HrPayslipEmployees(models.TransientModel): _inherit = 'hr.payslip.employees' @api.multi def compute_sheet(self): journal_id = False if self.env.context.get('active_id'): journal_id = self.env['hr.payslip.run'].browse(self.env.context.get('active_id')).journal_id.id return super(HrPayslipEmployees, self.with_context(journal_id=journal_id)).compute_sheet()
xyxiaoyou/snappy-store
gemfire-junit/src/main/java/com/gemstone/gemfire/internal/cache/TXManagerImplJUnitTest.java
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.internal.cache; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.gemstone.gemfire.cache.AttributesFactory; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.CacheTransactionManager; import com.gemstone.gemfire.cache.ExpirationAttributes; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.RegionShortcut; import com.gemstone.gemfire.cache.TransactionId; import junit.framework.TestCase; /** * junit test for suspend and resume methods * @author sbawaska */ public class TXManagerImplJUnitTest extends TestCase { protected Cache cache = null; protected Region region = null; @Override protected void setUp() throws Exception { super.setUp(); createCache(); } private void createCache() { Properties props = new Properties(); props.put("mcast-port", "0"); props.put("locators", ""); cache = new CacheFactory(props).create(); region = cache.createRegionFactory(RegionShortcut.REPLICATE).create("testRegion"); } @Override protected void tearDown() throws Exception { super.tearDown(); cache.close(); } /** * two threads suspend and resume a single transaction, while * making changes. * @throws Exception */ public void testSuspendResume() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); region.put("key", "value"); assertEquals("value", region.get("key")); final TransactionId txId = mgr.suspend(); mgr.resume(txId); try { mgr.resume(txId); fail("expected ex not thrown"); } catch (IllegalStateException e) { } final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Thread t = new Thread(new Runnable() { public void run() { try { mgr.resume(txId); fail("expected exception not thrown"); } catch (IllegalStateException e) { } assertFalse(mgr.tryResume(txId)); latch.countDown(); assertTrue(mgr.tryResume(txId, 100, TimeUnit.MILLISECONDS)); assertEquals("value1", region.get("key1")); region.put("key2", "value2"); latch2.countDown(); assertEquals(txId, mgr.suspend()); } }); t.start(); latch.await(); region.put("key1", "value1"); assertEquals(txId, mgr.suspend()); latch2.await(); assertTrue(mgr.tryResume(txId, 100, TimeUnit.MILLISECONDS)); assertEquals("value2", region.get("key2")); t.join(); mgr.commit(); assertEquals(3, region.size()); } public void testResumeTimeout() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); mgr.resume(txId); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new Runnable() { public void run() { assertFalse(mgr.tryResume(txId, 1, TimeUnit.SECONDS)); latch.countDown(); } }); long start = System.currentTimeMillis(); t.start(); latch.await(); long end = System.currentTimeMillis(); // other thread waits for 1 second assertTrue(end - start > 950); t.join(); mgr.commit(); } public void testMultipleSuspends() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); mgr.resume(txId); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final CountDownLatch latch3 = new CountDownLatch(1); Thread t1 = new Thread(new Runnable() { public void run() { latch2.countDown(); assertTrue(mgr.tryResume(txId, 1, TimeUnit.SECONDS)); assertNull(region.get("key2")); region.put("key1", "value1"); assertEquals(txId, mgr.suspend()); } }); Thread t2 = new Thread(new Runnable() { public void run() { latch3.countDown(); assertTrue(mgr.tryResume(txId, 1, TimeUnit.SECONDS)); assertEquals("value1", region.get("key1")); region.put("key2", "value"); assertEquals(txId, mgr.suspend()); latch.countDown(); } }); t1.start(); latch2.await(); Thread.sleep(200); t2.start(); latch3.await(); Thread.sleep(200); mgr.suspend(); if (!latch.await(30, TimeUnit.SECONDS)) { fail("junit test failed"); } mgr.tryResume(txId, 1, TimeUnit.SECONDS); assertEquals(3, region.size()); mgr.commit(); } public void testUnblockOnCommit() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); mgr.resume(txId); final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Thread t1 = new Thread(new Runnable() { public void run() { latch.countDown(); assertFalse(mgr.tryResume(txId, 10, TimeUnit.SECONDS)); latch2.countDown(); } }); Thread t2 = new Thread(new Runnable() { public void run() { latch.countDown(); assertFalse(mgr.tryResume(txId, 10, TimeUnit.SECONDS)); latch2.countDown(); } }); t1.start(); t2.start(); latch.await(); Thread.sleep(100); long start = System.currentTimeMillis(); mgr.commit(); assertTrue("expected to wait for less than 100 millis, but waited for:" +(System.currentTimeMillis() - start), latch2.await(100, TimeUnit.MILLISECONDS)); t1.join(); t2.join(); } public void testExists() { CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); TransactionId txId = mgr.suspend(); assertTrue(mgr.exists(txId)); mgr.resume(txId); assertTrue(mgr.exists(txId)); mgr.commit(); assertFalse(mgr.exists(txId)); mgr.begin(); txId = mgr.suspend(); assertTrue(mgr.exists(txId)); mgr.resume(txId); assertTrue(mgr.exists(txId)); mgr.rollback(); assertFalse(mgr.exists(txId)); } public void testEarlyoutOnTryResume() { CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); TransactionId txId = mgr.suspend(); mgr.resume(txId); mgr.commit(); long start = System.currentTimeMillis(); mgr.tryResume(txId, 10, TimeUnit.SECONDS); assertTrue("did not expect tryResume to block", System.currentTimeMillis() - start < 100); } /** * test that timeout of Long.MAX_VALUE does not return immediately * @throws Exception */ public void testWaitForever() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); mgr.resume(txId); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread(new Runnable() { public void run() { long start = System.currentTimeMillis(); assertTrue(mgr.tryResume(txId, Long.MAX_VALUE, TimeUnit.MILLISECONDS)); long end = System.currentTimeMillis(); assert end - start >= 1000; latch.countDown(); } }); t.start(); Thread.sleep(1100); mgr.suspend(); latch.await(); } public void testResumeCommitWithExpiry_bug45558() throws Exception { final CacheTransactionManager mgr = cache.getCacheTransactionManager(); final CountDownLatch l = new CountDownLatch(1); region.close(); AttributesFactory<String, String> af = new AttributesFactory<String, String>(); af.setStatisticsEnabled(true); af.setEntryIdleTimeout(new ExpirationAttributes(5)); //region.getAttributesMutator().setEntryTimeToLive(new ExpirationAttributes(5)); region = cache.createRegion(getName(), af.create()); region.put("key", "value"); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); Thread t = new Thread(new Runnable() { @Override public void run() { mgr.resume(txId); mgr.commit(); l.countDown(); } }); t.start(); l.await(); } public void testSuspendTimeout() throws Exception { cache.close(); System.setProperty("gemfire.suspendedTxTimeout", "1"); createCache(); TXManagerImpl mgr = (TXManagerImpl) cache.getCacheTransactionManager(); assertEquals(1, mgr.getSuspendedTransactionTimeout()); mgr.begin(); region.put("key", "value"); final TransactionId txId = mgr.suspend(); Thread.sleep(70*1000); try { mgr.resume(txId); fail("An expected exception was not thrown"); } catch (IllegalStateException expected) { } assertNull(region.get("key")); System.setProperty("gemfire.suspendedTxTimeout", ""); } }
generate-cordova-package/generate-cordova-package-0.0.x
tests/render-plugin-demo-app/render-plugin-demo-app.test.js
<reponame>generate-cordova-package/generate-cordova-package-0.0.x<filename>tests/render-plugin-demo-app/render-plugin-demo-app.test.js<gh_stars>0 /* global it, expect */ /* (see <https://github.com/standard/standard/issues/905>) */ const renderPluginDemoApp = require('../../lib/cordova-plugin/demo-app/render') const demoAppProperties = { demoAppName: 'test-plugin-demo-app', id: 'cc.plugintestdemo', description: 'plugin demo app', version: '0.1.3', license: 'ISC', author: 'Alice', email: '<EMAIL>;', jsObjectName: 'TestObject', jsFunctionName: 'testFunction', // added by `lib/with-copyright-year.js` // when used from the CLI: copyrightYear: 2023 } it('renders fs-tree object correctly for Cordova plugin demo app', () => { const outputTree = renderPluginDemoApp(demoAppProperties) expect(outputTree).toMatchSnapshot() })
ggrrll/pandapipes
pandapipes/io/io_utils.py
<reponame>ggrrll/pandapipes<filename>pandapipes/io/io_utils.py # Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel, and University of Kassel. All rights reserved. # Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. import importlib import json from functools import partial from inspect import isclass from pandapipes.multinet.create_multinet import MultiNet, create_empty_multinet from pandapipes.component_models.abstract_models import Component from pandapipes.create import create_empty_network from pandapipes.pandapipes_net import pandapipesNet, get_basic_net_entries from pandapower.io_utils import pp_hook from pandapower.io_utils import with_signature, to_serializable, JSONSerializableClass, \ isinstance_partial as ppow_isinstance, FromSerializableRegistry, PPJSONDecoder from copy import deepcopy try: import pplog as logging except ImportError: import logging logger = logging.getLogger(__name__) def isinstance_partial(obj, cls): if isinstance(obj, pandapipesNet): return False return ppow_isinstance(obj, cls) class FromSerializableRegistryPpipe(FromSerializableRegistry): from_serializable = deepcopy(FromSerializableRegistry.from_serializable) class_name = '' module_name = '' def __init__(self, obj, d, ppipes_hook): """ :param obj: object the data is written to :type obj: object :param d: data to be re-serialized :type d: any kind :param ppipes_hook: a way how to handle non-default data :type ppipes_hook: funct """ super().__init__(obj, d, ppipes_hook) @from_serializable.register(class_name="method") def method(self): module = importlib.import_module(self.module_name) logger.warning('Deserializing of method not tested. This might fail...') func = getattr(module, self.obj) # class_ = getattr(module, obj) # doesn't work return func @from_serializable.register(class_name='pandapipesNet', module_name='pandapipes.pandapipes_net') def pandapipesNet(self): if isinstance(self.obj, str): # backwards compatibility from pandapipes import from_json_string return from_json_string(self.obj) else: net = pandapipesNet(get_basic_net_entries()) net.update(self.obj) return net @from_serializable.register() def rest(self): module = importlib.import_module(self.module_name) class_ = getattr(module, self.class_name) if isclass(class_) and issubclass(class_, JSONSerializableClass): if isinstance(self.obj, str): self.obj = json.loads(self.obj, cls=PPJSONDecoder, object_hook=partial(pp_hook, registry_class=FromSerializableRegistryPpipe)) # backwards compatibility if "net" in self.obj: del self.obj["net"] return class_.from_dict(self.obj) if isclass(class_) and issubclass(class_, Component): return class_ else: # for non-pp objects, e.g. tuple return class_(self.obj, **self.d) @from_serializable.register(class_name='MultiNet') def MultiNet(self): if isinstance(self.obj, str): # backwards compatibility from pandapipes import from_json_string return from_json_string(self.obj) else: net = create_empty_multinet() net.update(self.obj) return net @to_serializable.register(pandapipesNet) def json_net(obj): net_dict = {k: item for k, item in obj.items() if not k.startswith("_")} d = with_signature(obj, net_dict) return d @to_serializable.register(type) def json_component(class_): if issubclass(class_, Component): d = with_signature(class_(), str(class_().__dict__)) return d else: raise (UserWarning('with_signature needs to be defined for ' 'class %s in @to_serializable.register(type)!' % class_)) @to_serializable.register(MultiNet) def json_net(obj): net_dict = {k: item for k, item in obj.items() if not k.startswith("_")} d = with_signature(obj, net_dict) return d
eloymore/P32021
dependencies/CeguiDependencies/src/src/devil-1.7.8/src-ILUT/src/ilut_directx9.c
<reponame>eloymore/P32021 //----------------------------------------------------------------------------- // // ImageLib Utility Toolkit Sources // Copyright (C) 2000-2009 by <NAME> // Last modified: 01/30/2009 // // Filename: src-ILUT/src/ilut_directx9.c // // Description: DirectX 9 functions for textures // //----------------------------------------------------------------------------- #include "ilut_internal.h" #ifdef ILUT_USE_DIRECTX9 #include <d3d9.h> //#include <d3dx9math.h> //#include <d3dx9tex.h> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") ILimage* MakeD3D9Compliant(IDirect3DDevice9 *Device, D3DFORMAT *DestFormat); ILenum GetD3D9Compat(ILenum Format); //D3DFORMAT GetD3DFormat(ILenum Format); D3DFORMAT D3DGetDXTCNumDX9(ILenum DXTCFormat); ILenum D3DGetDXTCFormat(D3DFORMAT DXTCNum); ILboolean iD3D9CreateMipmaps(IDirect3DTexture9 *Texture, ILimage *Image); IDirect3DTexture9* iD3DMakeTexture( IDirect3DDevice9 *Device, void *Data, ILuint DLen, ILuint Width, ILuint Height, D3DFORMAT Format, D3DPOOL Pool, ILuint Levels ); #define ILUT_TEXTUREFORMAT_D3D9_COUNT 7 ILboolean FormatsDX9Checked = IL_FALSE; ILboolean FormatsDX9supported[ILUT_TEXTUREFORMAT_D3D9_COUNT] = { IL_FALSE, IL_FALSE, IL_FALSE, IL_FALSE, IL_FALSE, IL_FALSE, IL_FALSE }; D3DFORMAT FormatsDX9[ILUT_TEXTUREFORMAT_D3D9_COUNT] = { D3DFMT_R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_L8, D3DFMT_DXT1, D3DFMT_DXT3, D3DFMT_DXT5, D3DFMT_A16B16G16R16F}; ILboolean ilutD3D9Init() { return IL_TRUE; } void CheckFormatsDX9(IDirect3DDevice9 *Device) { D3DDISPLAYMODE DispMode; HRESULT hr; IDirect3D9 *TestD3D9; ILuint i; IDirect3DDevice9_GetDirect3D(Device, (IDirect3D9**)&TestD3D9); IDirect3DDevice9_GetDisplayMode(Device, 0, &DispMode); for (i = 0; i < ILUT_TEXTUREFORMAT_D3D9_COUNT; i++) { hr = IDirect3D9_CheckDeviceFormat(TestD3D9, D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, DispMode.Format, 0, D3DRTYPE_TEXTURE, FormatsDX9[i]); FormatsDX9supported[i] = (ILboolean)SUCCEEDED(hr); } IDirect3D9_Release(TestD3D9); FormatsDX9Checked = IL_TRUE; return; } #ifndef _WIN32_WCE ILboolean ILAPIENTRY ilutD3D9TexFromFile(IDirect3DDevice9 *Device, ILconst_string FileName, IDirect3DTexture9 **Texture) { iBindImageTemp(); if (!ilLoadImage(FileName)) return IL_FALSE; *Texture = ilutD3D9Texture(Device); return IL_TRUE; } #endif//_WIN32_WCE #ifndef _WIN32_WCE ILboolean ILAPIENTRY ilutD3D9CubeTexFromFile(IDirect3DDevice9 *Device, ILconst_string FileName, IDirect3DCubeTexture9 **Texture) { iBindImageTemp(); if (!ilLoadImage(FileName)) return IL_FALSE; *Texture = ilutD3D9CubeTexture(Device); return IL_TRUE; } #endif//_WIN32_WCE ILboolean ILAPIENTRY ilutD3D9CubeTexFromFileInMemory(IDirect3DDevice9 *Device, void *Lump, ILuint Size, IDirect3DCubeTexture9 **Texture) { iBindImageTemp(); if( !ilLoadL(IL_TYPE_UNKNOWN, Lump, Size) ) return IL_FALSE; *Texture = ilutD3D9CubeTexture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9CubeTexFromResource(IDirect3DDevice9 *Device, HMODULE SrcModule, ILconst_string SrcResource, IDirect3DCubeTexture9 **Texture) { HRSRC Resource; ILubyte *Data; iBindImageTemp(); Resource = (HRSRC)LoadResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)); Data = (ILubyte*)LockResource(Resource); if (!ilLoadL(IL_TYPE_UNKNOWN, Data, SizeofResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)))) return IL_FALSE; *Texture = ilutD3D9CubeTexture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9CubeTexFromFileHandle(IDirect3DDevice9 *Device, ILHANDLE File, IDirect3DCubeTexture9 **Texture) { iBindImageTemp(); if( !ilLoadF(IL_TYPE_UNKNOWN, File) ) return IL_FALSE; *Texture = ilutD3D9CubeTexture(Device); return IL_TRUE; } D3DCUBEMAP_FACES iToD3D9Cube(ILuint cube) { switch (cube) { case IL_CUBEMAP_POSITIVEX: return D3DCUBEMAP_FACE_POSITIVE_X; case IL_CUBEMAP_NEGATIVEX: return D3DCUBEMAP_FACE_NEGATIVE_X; case IL_CUBEMAP_POSITIVEY: return D3DCUBEMAP_FACE_POSITIVE_Y; case IL_CUBEMAP_NEGATIVEY: return D3DCUBEMAP_FACE_NEGATIVE_Y; case IL_CUBEMAP_POSITIVEZ: return D3DCUBEMAP_FACE_POSITIVE_Z; case IL_CUBEMAP_NEGATIVEZ: return D3DCUBEMAP_FACE_NEGATIVE_Z; default: return D3DCUBEMAP_FACE_POSITIVE_X; //??? } } IDirect3DCubeTexture9* ILAPIENTRY ilutD3D9CubeTexture(IDirect3DDevice9 *Device) { IDirect3DCubeTexture9 *Texture; D3DLOCKED_RECT Box; D3DFORMAT Format; ILimage *StartImage; ILimage *Image; int i; Texture=NULL; Image=NULL; ilutCurImage = ilGetCurImage(); if (ilutCurImage == NULL) { ilSetError(ILUT_ILLEGAL_OPERATION); return NULL; } if (!FormatsDX9Checked) CheckFormatsDX9(Device); Image = MakeD3D9Compliant(Device, &Format); if (Image == NULL) { if (Image != ilutCurImage) ilCloseImage(Image); return NULL; } StartImage = ilutCurImage; if (FAILED(IDirect3DDevice9_CreateCubeTexture(Device, StartImage->Width, ilutGetInteger(ILUT_D3D_MIPLEVELS),0,Format, (D3DPOOL)ilutGetInteger(ILUT_D3D_POOL), &Texture, NULL))) return NULL; for (i = 0; i < CUBEMAP_SIDES; i++) { if (ilutCurImage==NULL || ilutCurImage->CubeFlags == 0) { SAFE_RELEASE(Texture) return NULL; } Image = ilutCurImage; Image = MakeD3D9Compliant(Device, &Format); if( Image == NULL ) { SAFE_RELEASE(Texture) return NULL; } if( FAILED(IDirect3DCubeTexture9_LockRect(Texture,iToD3D9Cube(Image->CubeFlags), 0, &Box, NULL, /*D3DLOCK_DISCARD*/0))) { SAFE_RELEASE(Texture) return NULL; } memcpy(Box.pBits, Image->Data, Image->SizeOfData); if (IDirect3DCubeTexture9_UnlockRect(Texture,iToD3D9Cube(Image->CubeFlags), 0) != D3D_OK) { SAFE_RELEASE(Texture) return IL_FALSE; } ilutCurImage=ilutCurImage->Faces; } ilutCurImage = StartImage; // We don't want to have mipmaps for such a large image. //if (Image != ilutCurImage) // ilCloseImage(Image); return Texture; } #ifndef _WIN32_WCE ILboolean ILAPIENTRY ilutD3D9VolTexFromFile(IDirect3DDevice9 *Device, ILconst_string FileName, IDirect3DVolumeTexture9 **Texture) { iBindImageTemp(); if (!ilLoadImage(FileName)) return IL_FALSE; *Texture = ilutD3D9VolumeTexture(Device); return IL_TRUE; } #endif//_WIN32_WCE ILboolean ILAPIENTRY ilutD3D9TexFromFileInMemory(IDirect3DDevice9 *Device, void *Lump, ILuint Size, IDirect3DTexture9 **Texture) { iBindImageTemp(); if (!ilLoadL(IL_TYPE_UNKNOWN, Lump, Size)) return IL_FALSE; *Texture = ilutD3D9Texture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9VolTexFromFileInMemory(IDirect3DDevice9 *Device, void *Lump, ILuint Size, IDirect3DVolumeTexture9 **Texture) { iBindImageTemp(); if (!ilLoadL(IL_TYPE_UNKNOWN, Lump, Size)) return IL_FALSE; *Texture = ilutD3D9VolumeTexture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9TexFromResource(IDirect3DDevice9 *Device, HMODULE SrcModule, ILconst_string SrcResource, IDirect3DTexture9 **Texture) { HRSRC Resource; ILubyte *Data; iBindImageTemp(); Resource = (HRSRC)LoadResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)); Data = (ILubyte*)LockResource(Resource); if (!ilLoadL(IL_TYPE_UNKNOWN, Data, SizeofResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)))) return IL_FALSE; *Texture = ilutD3D9Texture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9VolTexFromResource(IDirect3DDevice9 *Device, HMODULE SrcModule, ILconst_string SrcResource, IDirect3DVolumeTexture9 **Texture) { HRSRC Resource; ILubyte *Data; iBindImageTemp(); Resource = (HRSRC)LoadResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)); Data = (ILubyte*)LockResource(Resource); if (!ilLoadL(IL_TYPE_UNKNOWN, Data, SizeofResource(SrcModule, FindResource(SrcModule, SrcResource, RT_BITMAP)))) return IL_FALSE; *Texture = ilutD3D9VolumeTexture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9TexFromFileHandle(IDirect3DDevice9 *Device, ILHANDLE File, IDirect3DTexture9 **Texture) { iBindImageTemp(); if (!ilLoadF(IL_TYPE_UNKNOWN, File)) return IL_FALSE; *Texture = ilutD3D9Texture(Device); return IL_TRUE; } ILboolean ILAPIENTRY ilutD3D9VolTexFromFileHandle(IDirect3DDevice9 *Device, ILHANDLE File, IDirect3DVolumeTexture9 **Texture) { iBindImageTemp(); if (!ilLoadF(IL_TYPE_UNKNOWN, File)) return IL_FALSE; *Texture = ilutD3D9VolumeTexture(Device); return IL_TRUE; } D3DFORMAT D3DGetDXTCNumDX9(ILenum DXTCFormat) { switch (DXTCFormat) { case IL_DXT1: return D3DFMT_DXT1; case IL_DXT3: return D3DFMT_DXT3; case IL_DXT5: return D3DFMT_DXT5; } return D3DFMT_UNKNOWN; } ILenum D3DGetDXTCFormat(D3DFORMAT DXTCNum) { switch (DXTCNum) { case D3DFMT_DXT1: return IL_DXT1; case D3DFMT_DXT3: return IL_DXT3; case D3DFMT_DXT5: return IL_DXT5; } return D3DFMT_UNKNOWN; } IDirect3DTexture9* iD3DMakeTexture( IDirect3DDevice9 *Device, void *Data, ILuint DLen, ILuint Width, ILuint Height, D3DFORMAT Format, D3DPOOL Pool, ILuint Levels ) { IDirect3DTexture9 *Texture; D3DLOCKED_RECT Rect; if (FAILED(IDirect3DDevice9_CreateTexture(Device, Width, Height, Levels, 0, Format, Pool, &Texture, NULL))) return NULL; if (FAILED(IDirect3DTexture9_LockRect(Texture, 0, &Rect, NULL, 0))) return NULL; memcpy(Rect.pBits, Data, DLen); IDirect3DTexture9_UnlockRect(Texture, 0); return Texture; } IDirect3DTexture9* ILAPIENTRY ilutD3D9Texture(IDirect3DDevice9 *Device) { IDirect3DTexture9 *Texture; // D3DLOCKED_RECT Rect; D3DFORMAT Format; ILimage *Image; ILenum DXTCFormat; ILuint Size; ILubyte *Buffer; Image = ilutCurImage = ilGetCurImage(); if (ilutCurImage == NULL) { ilSetError(ILUT_ILLEGAL_OPERATION); return NULL; } if (!FormatsDX9Checked) CheckFormatsDX9(Device); if (ilutGetBoolean(ILUT_D3D_USE_DXTC) && FormatsDX9supported[3] && FormatsDX9supported[4] && FormatsDX9supported[5]) { if (ilutCurImage->DxtcData != NULL && ilutCurImage->DxtcSize != 0) { ILuint dxtcFormat = ilutGetInteger(ILUT_DXTC_FORMAT); Format = D3DGetDXTCNumDX9(ilutCurImage->DxtcFormat); ilutSetInteger(ILUT_DXTC_FORMAT, ilutCurImage->DxtcFormat); Texture = iD3DMakeTexture(Device, ilutCurImage->DxtcData, ilutCurImage->DxtcSize, ilutCurImage->Width, ilutCurImage->Height, Format, (D3DPOOL)(ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT ? D3DPOOL_SYSTEMMEM : ilutGetInteger(ILUT_D3D_POOL)), ilutGetInteger(ILUT_D3D_MIPLEVELS)); if (!Texture) return NULL; iD3D9CreateMipmaps(Texture, Image); if (ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT) { IDirect3DTexture9 *SysTex = Texture; // copy texture to device memory if (FAILED(IDirect3DDevice9_CreateTexture(Device, ilutCurImage->Width, ilutCurImage->Height, ilutGetInteger(ILUT_D3D_MIPLEVELS), 0, Format, D3DPOOL_DEFAULT, &Texture, NULL))) { IDirect3DTexture9_Release(SysTex); return NULL; } if (FAILED(IDirect3DDevice9_UpdateTexture(Device, (LPDIRECT3DBASETEXTURE9)SysTex, (LPDIRECT3DBASETEXTURE9)Texture))) { IDirect3DTexture9_Release(SysTex); return NULL; } IDirect3DTexture9_Release(SysTex); } ilutSetInteger(ILUT_DXTC_FORMAT, dxtcFormat); goto success; } if (ilutGetBoolean(ILUT_D3D_GEN_DXTC)) { DXTCFormat = ilutGetInteger(ILUT_DXTC_FORMAT); /* Image = MakeD3D9Compliant(Device, &Format); if (Image == NULL) { if (Image != ilutCurImage) ilCloseImage(Image); return NULL; } */ Size = ilGetDXTCData(NULL, 0, DXTCFormat); if (Size != 0) { Buffer = (ILubyte*)ialloc(Size); if (Buffer == NULL) return NULL; Size = ilGetDXTCData(Buffer, Size, DXTCFormat); if (Size == 0) { ifree(Buffer); return NULL; } Format = D3DGetDXTCNumDX9(DXTCFormat); Texture = iD3DMakeTexture(Device, Buffer, Size, ilutCurImage->Width, ilutCurImage->Height, Format, (D3DPOOL)(ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT ? D3DPOOL_SYSTEMMEM : ilutGetInteger(ILUT_D3D_POOL)), ilutGetInteger(ILUT_D3D_MIPLEVELS)); if (!Texture) return NULL; iD3D9CreateMipmaps(Texture, Image); if (ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT) { IDirect3DTexture9 *SysTex = Texture; if (FAILED(IDirect3DDevice9_CreateTexture(Device, ilutCurImage->Width, ilutCurImage->Height, ilutGetInteger(ILUT_D3D_MIPLEVELS), 0, Format, D3DPOOL_DEFAULT, &Texture, NULL))) { IDirect3DTexture9_Release(SysTex); return NULL; } if (FAILED(IDirect3DDevice9_UpdateTexture(Device, (LPDIRECT3DBASETEXTURE9)SysTex, (LPDIRECT3DBASETEXTURE9)Texture))) { IDirect3DTexture9_Release(SysTex); return NULL; } IDirect3DTexture9_Release(SysTex); } goto success; } } } Image = MakeD3D9Compliant(Device, &Format); if (Image == NULL) { if (Image != ilutCurImage) ilCloseImage(Image); return NULL; } Texture = iD3DMakeTexture(Device, Image->Data, Image->SizeOfPlane, Image->Width, Image->Height, Format, (D3DPOOL)(ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT ? D3DPOOL_SYSTEMMEM : ilutGetInteger(ILUT_D3D_POOL)), ilutGetInteger(ILUT_D3D_MIPLEVELS)); if (!Texture) return NULL; iD3D9CreateMipmaps(Texture, Image); if (ilutGetInteger(ILUT_D3D_POOL) == D3DPOOL_DEFAULT) { IDirect3DTexture9 *SysTex = Texture; // create texture in system memory if (FAILED(IDirect3DDevice9_CreateTexture(Device, Image->Width, Image->Height, ilutGetInteger(ILUT_D3D_MIPLEVELS), 0, Format, (D3DPOOL)ilutGetInteger(ILUT_D3D_POOL), &Texture, NULL))) { IDirect3DTexture9_Release(SysTex); return NULL; } if (FAILED(IDirect3DDevice9_UpdateTexture(Device, (LPDIRECT3DBASETEXTURE9)SysTex, (LPDIRECT3DBASETEXTURE9)Texture))) { IDirect3DTexture9_Release(SysTex); return NULL; } IDirect3DTexture9_Release(SysTex); } // if (Image != ilutCurImage) // ilCloseImage(Image); success: if (Image != ilutCurImage) ilCloseImage(Image); return Texture; } IDirect3DVolumeTexture9* ILAPIENTRY ilutD3D9VolumeTexture(IDirect3DDevice9 *Device) { IDirect3DVolumeTexture9 *Texture; D3DLOCKED_BOX Box; D3DFORMAT Format; ILimage *Image; ilutCurImage = ilGetCurImage(); if (ilutCurImage == NULL) { ilSetError(ILUT_ILLEGAL_OPERATION); return NULL; } if (!FormatsDX9Checked) CheckFormatsDX9(Device); Image = MakeD3D9Compliant(Device, &Format); if (Image == NULL) return NULL; if (FAILED(IDirect3DDevice9_CreateVolumeTexture(Device, Image->Width, Image->Height, Image->Depth, 1, 0, Format, (D3DPOOL)ilutGetInteger(ILUT_D3D_POOL), &Texture, NULL))) return NULL; if (FAILED(IDirect3DVolumeTexture9_LockBox(Texture, 0, &Box, NULL, 0))) return NULL; memcpy(Box.pBits, Image->Data, Image->SizeOfData); if (!IDirect3DVolumeTexture9_UnlockBox(Texture, 0)) return IL_FALSE; // We don't want to have mipmaps for such a large image. if (Image != ilutCurImage) ilCloseImage(Image); return Texture; } ILimage *MakeD3D9Compliant(IDirect3DDevice9 *Device, D3DFORMAT *DestFormat) { ILuint color; ILimage *Converted, *Scaled, *CurImage; ILuint nConversionType, ilutFormat; ILboolean bForceIntegerFormat = ilutGetBoolean(ILUT_FORCE_INTEGER_FORMAT); Device; ilutFormat = ilutCurImage->Format; nConversionType = ilutCurImage->Type; if (!ilutCurImage) return NULL; switch (ilutCurImage->Type) { case IL_UNSIGNED_BYTE: case IL_BYTE: case IL_SHORT: case IL_UNSIGNED_SHORT: case IL_INT: case IL_UNSIGNED_INT: *DestFormat = D3DFMT_A8R8G8B8; nConversionType = IL_UNSIGNED_BYTE; ilutFormat = IL_BGRA; break; case IL_FLOAT: case IL_DOUBLE: case IL_HALF: if (bForceIntegerFormat || (!FormatsDX9supported[6])) { *DestFormat = D3DFMT_A8R8G8B8; nConversionType = IL_UNSIGNED_BYTE; ilutFormat = IL_BGRA; } else { *DestFormat = D3DFMT_A16B16G16R16F; nConversionType = IL_HALF; ilutFormat = IL_RGBA; // } break; } // Images must be in BGRA format. if (((ilutCurImage->Format != ilutFormat)) || (ilutCurImage->Type != nConversionType)) { Converted = iConvertImage(ilutCurImage, ilutFormat, nConversionType); if (Converted == NULL) return NULL; } else { Converted = ilutCurImage; } // perform alpha key on images if requested color=ilutGetInteger(ILUT_D3D_ALPHA_KEY_COLOR); if((color>=0) && (nConversionType == IL_UNSIGNED_BYTE)) { ILubyte *data; ILubyte *maxdata; ILuint t; data=(Converted->Data); maxdata=(Converted->Data+Converted->SizeOfData); while(data<maxdata) { t= (data[2]<<16) + (data[1]<<8) + (data[0]) ; if((t&0x00ffffff)==(color&0x00ffffff)) { data[0]=0; data[1]=0; data[2]=0; data[3]=0; } data+=4; } } // Images must have their origin in the upper left. if (Converted->Origin != IL_ORIGIN_UPPER_LEFT) { CurImage = ilutCurImage; ilSetCurImage(Converted); iluFlipImage(); ilSetCurImage(CurImage); } // Images must have powers-of-2 dimensions. if (ilNextPower2(ilutCurImage->Width) != ilutCurImage->Width || ilNextPower2(ilutCurImage->Height) != ilutCurImage->Height || ilNextPower2(ilutCurImage->Depth) != ilutCurImage->Depth) { Scaled = iluScale_(Converted, ilNextPower2(ilutCurImage->Width), ilNextPower2(ilutCurImage->Height), ilNextPower2(ilutCurImage->Depth)); if (Converted != ilutCurImage) { ilCloseImage(Converted); } if (Scaled == NULL) { return NULL; } Converted = Scaled; } return Converted; } ILboolean iD3D9CreateMipmaps(IDirect3DTexture9 *Texture, ILimage *Image) { D3DLOCKED_RECT Rect; D3DSURFACE_DESC Desc; ILuint NumMips, srcMips, Width, Height, i; ILimage *CurImage, *MipImage, *Temp; ILenum DXTCFormat; ILuint Size; ILubyte *Buffer; ILboolean useDXTC = IL_FALSE; NumMips = IDirect3DTexture9_GetLevelCount(Texture); Width = Image->Width; Height = Image->Height; if (NumMips == 1) return IL_TRUE; CurImage = ilGetCurImage(); MipImage = Image; iGetIntegervImage(MipImage, IL_NUM_MIPMAPS, (ILint*) &srcMips); if ( srcMips != NumMips-1) { MipImage = ilCopyImage_(Image); ilSetCurImage(MipImage); if (!iluBuildMipmaps()) { ilCloseImage(MipImage); ilSetCurImage(CurImage); return IL_FALSE; } } // ilSetCurImage(CurImage); Temp = MipImage->Mipmaps; if (ilutGetBoolean(ILUT_D3D_USE_DXTC) && FormatsDX9supported[3] && FormatsDX9supported[4] && FormatsDX9supported[5]) useDXTC = IL_TRUE; // Counts the base texture as 1. for (i = 1; i < NumMips && Temp != NULL; i++) { ilSetCurImage(Temp); if (FAILED(IDirect3DTexture9_LockRect(Texture, i, &Rect, NULL, 0))) return IL_FALSE; Width = IL_MAX(1, Width / 2); Height = IL_MAX(1, Height / 2); IDirect3DTexture9_GetLevelDesc(Texture, i, &Desc); if (Desc.Width != Width || Desc.Height != Height) { IDirect3DTexture9_UnlockRect(Texture, i); return IL_FALSE; } if (useDXTC) { if (Temp->DxtcData != NULL && Temp->DxtcSize != 0) { memcpy(Rect.pBits, Temp->DxtcData, Temp->DxtcSize); } else if (ilutGetBoolean(ILUT_D3D_GEN_DXTC)) { DXTCFormat = ilutGetInteger(ILUT_DXTC_FORMAT); Size = ilGetDXTCData(NULL, 0, DXTCFormat); if (Size != 0) { Buffer = (ILubyte*)ialloc(Size); if (Buffer == NULL) { IDirect3DTexture9_UnlockRect(Texture, i); return IL_FALSE; } Size = ilGetDXTCData(Buffer, Size, DXTCFormat); if (Size == 0) { ifree(Buffer); IDirect3DTexture9_UnlockRect(Texture, i); return IL_FALSE; } memcpy(Rect.pBits, Buffer, Size); } else { IDirect3DTexture9_UnlockRect(Texture, i); return IL_FALSE; } } else { IDirect3DTexture9_UnlockRect(Texture, i); return IL_FALSE; } } else memcpy(Rect.pBits, Temp->Data, Temp->SizeOfData); IDirect3DTexture9_UnlockRect(Texture, i); Temp = Temp->Mipmaps; } if (MipImage != Image) ilCloseImage(MipImage); ilSetCurImage(CurImage); return IL_TRUE; } // // SaveSurfaceToFile.cpp // // Copyright (c) 2001 <NAME> // // Permission to use, copy, modify and distribute this software // is hereby granted, provided that both the copyright notice and // this permission notice appear in all copies of the software, // derivative works or modified versions. // // THE AUTHOR ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" // CONDITION AND DISCLAIMS ANY LIABILITY OF ANY KIND FOR ANY DAMAGES // WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. // ILAPI ILboolean ILAPIENTRY ilutD3D9LoadSurface(IDirect3DDevice9 *Device, IDirect3DSurface9 *Surface) { HRESULT hr; D3DSURFACE_DESC d3dsd; LPDIRECT3DSURFACE9 SurfaceCopy; D3DLOCKED_RECT d3dLR; ILboolean bHasAlpha; ILubyte *Image, *ImageAux, *Data; ILuint y, x; ILushort dwColor; IDirect3DSurface9_GetDesc(Surface, &d3dsd); bHasAlpha = (ILboolean)(d3dsd.Format == D3DFMT_A8R8G8B8 || d3dsd.Format == D3DFMT_A1R5G5B5); if (bHasAlpha) { if (!ilTexImage(d3dsd.Width, d3dsd.Height, 1, 4, IL_BGRA, IL_UNSIGNED_BYTE, NULL)) { return IL_FALSE; } } else { if (!ilTexImage(d3dsd.Width, d3dsd.Height, 1, 3, IL_BGR, IL_UNSIGNED_BYTE, NULL)) { return IL_FALSE; } } hr = IDirect3DDevice9_CreateOffscreenPlainSurface(Device, d3dsd.Width, d3dsd.Height, d3dsd.Format, D3DPOOL_SCRATCH, &SurfaceCopy, NULL); if (FAILED(hr)) { ilSetError(ILUT_ILLEGAL_OPERATION); return IL_FALSE; } hr = IDirect3DDevice9_StretchRect(Device, Surface, NULL, SurfaceCopy, NULL, D3DTEXF_NONE); if (FAILED(hr)) { ilSetError(ILUT_ILLEGAL_OPERATION); return IL_FALSE; } hr = IDirect3DSurface9_LockRect(SurfaceCopy, &d3dLR, NULL, D3DLOCK_NO_DIRTY_UPDATE | D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY); if (FAILED(hr)) { IDirect3DSurface9_Release(SurfaceCopy); ilSetError(ILUT_ILLEGAL_OPERATION); return IL_FALSE; } Image = (ILubyte*)d3dLR.pBits; Data = ilutCurImage->Data; for (y = 0; y < d3dsd.Height; y++) { if (d3dsd.Format == D3DFMT_X8R8G8B8) { ImageAux = Image; for (x = 0; x < d3dsd.Width; x++) { Data[0] = ImageAux[0]; Data[1] = ImageAux[1]; Data[2] = ImageAux[2]; Data += 3; ImageAux += 4; } } else if (d3dsd.Format == D3DFMT_A8R8G8B8) { memcpy(Data, Image, d3dsd.Width * 4); } else if (d3dsd.Format == D3DFMT_R5G6B5) { ImageAux = Image; for (x = 0; x < d3dsd.Width; x++) { dwColor = *((ILushort*)ImageAux); Data[0] = (ILubyte)((dwColor&0x001f)<<3); Data[1] = (ILubyte)(((dwColor&0x7e0)>>5)<<2); Data[2] = (ILubyte)(((dwColor&0xf800)>>11)<<3); Data += 3; ImageAux += 2; } } else if (d3dsd.Format == D3DFMT_X1R5G5B5) { ImageAux = Image; for (x = 0; x < d3dsd.Width; x++) { dwColor = *((ILushort*)ImageAux); Data[0] = (ILubyte)((dwColor&0x001f)<<3); Data[1] = (ILubyte)(((dwColor&0x3e0)>>5)<<3); Data[2] = (ILubyte)(((dwColor&0x7c00)>>10)<<3); Data += 3; ImageAux += 2; } } else if (d3dsd.Format == D3DFMT_A1R5G5B5) { ImageAux = Image; for (x = 0; x < d3dsd.Width; x++) { dwColor = *((ILushort*)ImageAux); Data[0] = (ILubyte)((dwColor&0x001f)<<3); Data[1] = (ILubyte)(((dwColor&0x3e0)>>5)<<3); Data[2] = (ILubyte)(((dwColor&0x7c00)>>10)<<3); Data[3] = (ILubyte)(((dwColor&0x8000)>>15)*255); Data += 4; ImageAux += 2; } } Image += d3dLR.Pitch; } IDirect3DSurface9_UnlockRect(SurfaceCopy); IDirect3DSurface9_Release(SurfaceCopy); return IL_TRUE; } #endif//ILUT_USE_DIRECTX9
harigad/Car_Keys_UI
app/controllers/testdrives/testdrives.js
$.header.openWindow($.testdrives); $.header.setTitle("test drives"); var header_row = Ti.UI.createTableViewRow(); var header_label = Ti.UI.createLabel({ height:Ti.UI.SIZE, left:20, text: "+ new test drive", color:"#40a3ff", font:{ fontSize:40 } }); header_row.addEventListener("click",function(){ var signup = Alloy.createController("testdrives/request/testdrive_find_car",{_callBack:function(){ //refresh(); }}); }); header_row.add(header_label); $.main.setData([header_row]);
inodeman/kie-tools
scripts/unpack-maven-packages.js
<gh_stars>10-100 #!/usr/bin/env node /* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const decompress = require("decompress"); const http = require("http"); const https = require("https"); const fs = require("fs"); const path = require("path"); const download = function (url, dest, cb) { const file = fs.createWriteStream(dest); (url.startsWith("https://") ? https : http) .get(url, function (response) { response.pipe(file); file.on("finish", function () { file.close(cb(dest)); }); }) .on("error", function (err) { console.error("[ERROR] Error downloading file", err); if (cb) cb(dest); }); }; const urls = process.argv.slice(2); fs.mkdirSync("unpacked"); urls.forEach((url) => download(url, path.join(".", "unpacked", url.substring(url.lastIndexOf("/") + 1)), (file) => { console.log(`${file} downloaded. Uncompressing it...`); decompress(file, `${file.replace(/\./g, "_")}`).then( () => console.log(`File ${file} unpacked.`), (error) => console.error(`Error unpackaging file ${file}.`, error) ); }) );
kokizzu/UVa
929/929.go
// UVa 929 - Number Maze package main import ( "container/heap" "fmt" "math" "os" ) type ( node struct{ y, x, cost int } priorityQueue []*node ) var directions = [][2]int{{0, -1}, {1, 0}, {0, 1}, {-1, 0}} func (pq priorityQueue) Len() int { return len(pq) } func (pq priorityQueue) Less(i, j int) bool { return pq[i].cost < pq[j].cost } func (pq priorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *priorityQueue) Push(x interface{}) { *pq = append(*pq, x.(*node)) } func (pq *priorityQueue) Pop() interface{} { item := (*pq)[pq.Len()-1] *pq = (*pq)[0 : pq.Len()-1] return item } func dijkstra(n, m int, maze [][]int) int { visited := make([][]bool, n) cost := make([][]int, n) for i := range cost { visited[i] = make([]bool, m) cost[i] = make([]int, m) for j := range cost[i] { cost[i][j] = math.MaxInt32 } } cost[0][0], visited[0][0] = maze[0][0], true var pq priorityQueue for heap.Push(&pq, &node{0, 0, cost[0][0]}); pq.Len() > 0; { curr := heap.Pop(&pq).(*node) for _, direction := range directions { if newY, newX := curr.y+direction[0], curr.x+direction[1]; newY >= 0 && newY < n && newX >= 0 && newX < m && !visited[newY][newX] { if newCost := curr.cost + maze[newY][newX]; newCost < cost[newY][newX] { cost[newY][newX], visited[newY][newX] = newCost, true heap.Push(&pq, &node{newY, newX, newCost}) } } } } return cost[n-1][m-1] } func main() { in, _ := os.Open("929.in") defer in.Close() out, _ := os.Create("929.out") defer out.Close() var kase, n, m int for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- { fmt.Fscanf(in, "%d\n%d", &n, &m) maze := make([][]int, n) for i := range maze { maze[i] = make([]int, m) for j := range maze[i] { fmt.Fscanf(in, "%d", &maze[i][j]) } } fmt.Fprintln(out, dijkstra(n, m, maze)) } }
Diez37/elastic-migrate
index/aliase.go
package index import "github.com/olivere/elastic/v7" type Alias struct { alias string routing *string filter elastic.Query } func NewAlias(alias string) *Alias { return &Alias{alias: alias} } func (alias *Alias) Alias() string { return alias.alias } func (alias *Alias) SetRouting(routing string) *Alias { alias.routing = &routing return alias } func (alias *Alias) SetFilter(filter elastic.Query) *Alias { alias.filter = filter return alias } func (alias *Alias) Source() (interface{}, error) { source := map[string]interface{}{} if alias.routing != nil { source["routing"] = *alias.routing } if alias.filter != nil { filter, err := alias.filter.Source() if err != nil { return nil, err } source["filter"] = filter } return source, nil }
youngzil/quickstart-application-container
quickstart-quickserver/src/main/libsrc/QuickServerV2.1.0/src/main/org/quickserver/util/io/JarFileList.java
/* * This file is part of the QuickServer library * Copyright (C) QuickServer.org * * Use, modification, copying and distribution of this software is subject to * the terms and conditions of the GNU Lesser General Public License. * You should have received a copy of the GNU LGP License along with this * library; if not, you can download a copy from <http://www.quickserver.org/>. * * For questions, suggestions, bug-reports, enhancement-requests etc. * visit http://www.quickserver.org * */ package org.quickserver.util.io; import java.io.*; /** * JarFileList Class * @author <NAME> * @version 1.3.2 */ public class JarFileList implements java.io.FileFilter { public boolean accept(File file) { if(file.getName().toLowerCase().endsWith(".jar")) return true; else return false; } }
TencentCloud/tencentcloud-sdk-go-intl-en
tencentcloud/tcr/v20190924/models.go
// Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v20190924 import ( "encoding/json" tcerr "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/errors" tchttp "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/http" ) type CheckInstanceRequest struct { *tchttp.BaseRequest // ID of the instance to be verified. RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` } func (r *CheckInstanceRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CheckInstanceRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "CheckInstanceRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type CheckInstanceResponse struct { *tchttp.BaseResponse Response *struct { // Verification result. true: valid, false: invalid IsValidated *bool `json:"IsValidated,omitempty" name:"IsValidated"` // ID of the region where the instance is located. RegionId *uint64 `json:"RegionId,omitempty" name:"RegionId"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *CheckInstanceResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CheckInstanceResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type CreateImmutableTagRulesRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Namespace NamespaceName *string `json:"NamespaceName,omitempty" name:"NamespaceName"` // Rule Rule *ImmutableTagRule `json:"Rule,omitempty" name:"Rule"` } func (r *CreateImmutableTagRulesRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateImmutableTagRulesRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "NamespaceName") delete(f, "Rule") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "CreateImmutableTagRulesRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type CreateImmutableTagRulesResponse struct { *tchttp.BaseResponse Response *struct { // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *CreateImmutableTagRulesResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateImmutableTagRulesResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type CreateMultipleSecurityPolicyRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Security group policy SecurityGroupPolicySet []*SecurityPolicy `json:"SecurityGroupPolicySet,omitempty" name:"SecurityGroupPolicySet"` } func (r *CreateMultipleSecurityPolicyRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateMultipleSecurityPolicyRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "SecurityGroupPolicySet") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "CreateMultipleSecurityPolicyRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type CreateMultipleSecurityPolicyResponse struct { *tchttp.BaseResponse Response *struct { // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *CreateMultipleSecurityPolicyResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateMultipleSecurityPolicyResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type CreateReplicationInstanceRequest struct { *tchttp.BaseRequest // Master instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Region ID of the replication instance ReplicationRegionId *uint64 `json:"ReplicationRegionId,omitempty" name:"ReplicationRegionId"` // Region name of the replication instance ReplicationRegionName *string `json:"ReplicationRegionName,omitempty" name:"ReplicationRegionName"` } func (r *CreateReplicationInstanceRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateReplicationInstanceRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "ReplicationRegionId") delete(f, "ReplicationRegionName") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "CreateReplicationInstanceRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type CreateReplicationInstanceResponse struct { *tchttp.BaseResponse Response *struct { // Enterprise Registry Instance ID ReplicationRegistryId *string `json:"ReplicationRegistryId,omitempty" name:"ReplicationRegistryId"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *CreateReplicationInstanceResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *CreateReplicationInstanceResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DeleteImmutableTagRulesRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Namespace NamespaceName *string `json:"NamespaceName,omitempty" name:"NamespaceName"` // Rule ID RuleId *int64 `json:"RuleId,omitempty" name:"RuleId"` } func (r *DeleteImmutableTagRulesRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DeleteImmutableTagRulesRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "NamespaceName") delete(f, "RuleId") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DeleteImmutableTagRulesRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DeleteImmutableTagRulesResponse struct { *tchttp.BaseResponse Response *struct { // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DeleteImmutableTagRulesResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DeleteImmutableTagRulesResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DeleteMultipleSecurityPolicyRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Security group policy SecurityGroupPolicySet []*SecurityPolicy `json:"SecurityGroupPolicySet,omitempty" name:"SecurityGroupPolicySet"` } func (r *DeleteMultipleSecurityPolicyRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DeleteMultipleSecurityPolicyRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "SecurityGroupPolicySet") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DeleteMultipleSecurityPolicyRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DeleteMultipleSecurityPolicyResponse struct { *tchttp.BaseResponse Response *struct { // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DeleteMultipleSecurityPolicyResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DeleteMultipleSecurityPolicyResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DescribeImmutableTagRulesRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` } func (r *DescribeImmutableTagRulesRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeImmutableTagRulesRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DescribeImmutableTagRulesRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DescribeImmutableTagRulesResponse struct { *tchttp.BaseResponse Response *struct { // Rule list // Note: this field may return `null`, indicating that no valid value can be obtained. Rules []*ImmutableTagRule `json:"Rules,omitempty" name:"Rules"` // Namespace with no rules created // Note: this field may return `null`, indicating that no valid value can be obtained. EmptyNs []*string `json:"EmptyNs,omitempty" name:"EmptyNs"` // Total rules Total *int64 `json:"Total,omitempty" name:"Total"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DescribeImmutableTagRulesResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeImmutableTagRulesResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstanceCreateTasksRequest struct { *tchttp.BaseRequest // Replication instance ID ReplicationRegistryId *string `json:"ReplicationRegistryId,omitempty" name:"ReplicationRegistryId"` // Region ID of the replication instance ReplicationRegionId *uint64 `json:"ReplicationRegionId,omitempty" name:"ReplicationRegionId"` } func (r *DescribeReplicationInstanceCreateTasksRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstanceCreateTasksRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "ReplicationRegistryId") delete(f, "ReplicationRegionId") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DescribeReplicationInstanceCreateTasksRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstanceCreateTasksResponse struct { *tchttp.BaseResponse Response *struct { // Task details TaskDetail []*TaskDetail `json:"TaskDetail,omitempty" name:"TaskDetail"` // Overall task status Status *string `json:"Status,omitempty" name:"Status"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DescribeReplicationInstanceCreateTasksResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstanceCreateTasksResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstanceSyncStatusRequest struct { *tchttp.BaseRequest // Master instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Replication instance ID ReplicationRegistryId *string `json:"ReplicationRegistryId,omitempty" name:"ReplicationRegistryId"` // Region ID of the replication instance ReplicationRegionId *uint64 `json:"ReplicationRegionId,omitempty" name:"ReplicationRegionId"` // Whether to show the synchronization log ShowReplicationLog *bool `json:"ShowReplicationLog,omitempty" name:"ShowReplicationLog"` // Page offset for log display. Default value: 0 Offset *int64 `json:"Offset,omitempty" name:"Offset"` // Maximum number of output entries. Default value: 5, maximum value: 20. Limit *int64 `json:"Limit,omitempty" name:"Limit"` } func (r *DescribeReplicationInstanceSyncStatusRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstanceSyncStatusRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "ReplicationRegistryId") delete(f, "ReplicationRegionId") delete(f, "ShowReplicationLog") delete(f, "Offset") delete(f, "Limit") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DescribeReplicationInstanceSyncStatusRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstanceSyncStatusResponse struct { *tchttp.BaseResponse Response *struct { // Synchronization status ReplicationStatus *string `json:"ReplicationStatus,omitempty" name:"ReplicationStatus"` // Synchronization completion time ReplicationTime *string `json:"ReplicationTime,omitempty" name:"ReplicationTime"` // Synchronization log // Note: this field may return `null`, indicating that no valid values can be obtained. ReplicationLog *ReplicationLog `json:"ReplicationLog,omitempty" name:"ReplicationLog"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DescribeReplicationInstanceSyncStatusResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstanceSyncStatusResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstancesRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Offset. Default value: 0 Offset *int64 `json:"Offset,omitempty" name:"Offset"` // Maximum number of output entries. Default value: 20, maximum value: 100. Limit *int64 `json:"Limit,omitempty" name:"Limit"` } func (r *DescribeReplicationInstancesRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstancesRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "Offset") delete(f, "Limit") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "DescribeReplicationInstancesRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type DescribeReplicationInstancesResponse struct { *tchttp.BaseResponse Response *struct { // Total number of instances TotalCount *int64 `json:"TotalCount,omitempty" name:"TotalCount"` // Replication instance list // Note: this field may return `null`, indicating that no valid values can be obtained. ReplicationRegistries []*ReplicationRegistry `json:"ReplicationRegistries,omitempty" name:"ReplicationRegistries"` // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *DescribeReplicationInstancesResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *DescribeReplicationInstancesResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type ImmutableTagRule struct { // Repository matching rule RepositoryPattern *string `json:"RepositoryPattern,omitempty" name:"RepositoryPattern"` // Tag matching rule TagPattern *string `json:"TagPattern,omitempty" name:"TagPattern"` // repoMatches or repoExcludes RepositoryDecoration *string `json:"RepositoryDecoration,omitempty" name:"RepositoryDecoration"` // matches or excludes TagDecoration *string `json:"TagDecoration,omitempty" name:"TagDecoration"` // Disabling rule Disabled *bool `json:"Disabled,omitempty" name:"Disabled"` // Rule ID RuleId *int64 `json:"RuleId,omitempty" name:"RuleId"` // Namespace NsName *string `json:"NsName,omitempty" name:"NsName"` } type ManageReplicationRequest struct { *tchttp.BaseRequest // Source instance ID SourceRegistryId *string `json:"SourceRegistryId,omitempty" name:"SourceRegistryId"` // Destination instance ID DestinationRegistryId *string `json:"DestinationRegistryId,omitempty" name:"DestinationRegistryId"` // Synchronization rule Rule *ReplicationRule `json:"Rule,omitempty" name:"Rule"` // Rule description Description *string `json:"Description,omitempty" name:"Description"` // Region ID of the destination instance. For example, `1` represents Guangzhou DestinationRegionId *uint64 `json:"DestinationRegionId,omitempty" name:"DestinationRegionId"` // Configuration of the synchronization rule PeerReplicationOption *PeerReplicationOption `json:"PeerReplicationOption,omitempty" name:"PeerReplicationOption"` } func (r *ManageReplicationRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ManageReplicationRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "SourceRegistryId") delete(f, "DestinationRegistryId") delete(f, "Rule") delete(f, "Description") delete(f, "DestinationRegionId") delete(f, "PeerReplicationOption") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "ManageReplicationRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type ManageReplicationResponse struct { *tchttp.BaseResponse Response *struct { // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *ManageReplicationResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ManageReplicationResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type ModifyImmutableTagRulesRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Namespace NamespaceName *string `json:"NamespaceName,omitempty" name:"NamespaceName"` // Rule ID RuleId *int64 `json:"RuleId,omitempty" name:"RuleId"` // Rule Rule *ImmutableTagRule `json:"Rule,omitempty" name:"Rule"` } func (r *ModifyImmutableTagRulesRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ModifyImmutableTagRulesRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "NamespaceName") delete(f, "RuleId") delete(f, "Rule") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "ModifyImmutableTagRulesRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type ModifyImmutableTagRulesResponse struct { *tchttp.BaseResponse Response *struct { // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *ModifyImmutableTagRulesResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ModifyImmutableTagRulesResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type ModifyInstanceRequest struct { *tchttp.BaseRequest // Instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Instance specification RegistryType *string `json:"RegistryType,omitempty" name:"RegistryType"` } func (r *ModifyInstanceRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ModifyInstanceRequest) FromJsonString(s string) error { f := make(map[string]interface{}) if err := json.Unmarshal([]byte(s), &f); err != nil { return err } delete(f, "RegistryId") delete(f, "RegistryType") if len(f) > 0 { return tcerr.NewTencentCloudSDKError("ClientError.BuildRequestError", "ModifyInstanceRequest has unknown keys!", "") } return json.Unmarshal([]byte(s), &r) } type ModifyInstanceResponse struct { *tchttp.BaseResponse Response *struct { // The unique request ID, which is returned for each request. RequestId is required for locating a problem. RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *ModifyInstanceResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } // FromJsonString It is highly **NOT** recommended to use this function // because it has no param check, nor strict type check func (r *ModifyInstanceResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type PeerReplicationOption struct { // UIN of the destination instance PeerRegistryUin *string `json:"PeerRegistryUin,omitempty" name:"PeerRegistryUin"` // Permanent access Token for the destination instance PeerRegistryToken *string `json:"PeerRegistryToken,omitempty" name:"PeerRegistryToken"` // Whether to enable cross-account synchronization EnablePeerReplication *bool `json:"EnablePeerReplication,omitempty" name:"EnablePeerReplication"` } type ReplicationFilter struct { // Type (`name`, `tag` and `resource`) Type *string `json:"Type,omitempty" name:"Type"` // It is left blank by default Value *string `json:"Value,omitempty" name:"Value"` } type ReplicationLog struct { // Resource type // Note: this field may return `null`, indicating that no valid values can be obtained. ResourceType *string `json:"ResourceType,omitempty" name:"ResourceType"` // Path of the source resource // Note: this field may return `null`, indicating that no valid values can be obtained. Source *string `json:"Source,omitempty" name:"Source"` // Path of the destination resource // Note: this field may return `null`, indicating that no valid values can be obtained. Destination *string `json:"Destination,omitempty" name:"Destination"` // Synchronization status // Note: this field may return `null`, indicating that no valid values can be obtained. Status *string `json:"Status,omitempty" name:"Status"` // Start time // Note: this field may return `null`, indicating that no valid values can be obtained. StartTime *string `json:"StartTime,omitempty" name:"StartTime"` // End time // Note: this field may return `null`, indicating that no valid values can be obtained. EndTime *string `json:"EndTime,omitempty" name:"EndTime"` } type ReplicationRegistry struct { // Master instance ID RegistryId *string `json:"RegistryId,omitempty" name:"RegistryId"` // Replication instance ID ReplicationRegistryId *string `json:"ReplicationRegistryId,omitempty" name:"ReplicationRegistryId"` // Region ID of the replication instance ReplicationRegionId *uint64 `json:"ReplicationRegionId,omitempty" name:"ReplicationRegionId"` // Region name of the replication instance ReplicationRegionName *string `json:"ReplicationRegionName,omitempty" name:"ReplicationRegionName"` // Status of the replication instance Status *string `json:"Status,omitempty" name:"Status"` // Creation time CreatedAt *string `json:"CreatedAt,omitempty" name:"CreatedAt"` } type ReplicationRule struct { // Name of synchronization rule Name *string `json:"Name,omitempty" name:"Name"` // Destination namespace DestNamespace *string `json:"DestNamespace,omitempty" name:"DestNamespace"` // Whether to override Override *bool `json:"Override,omitempty" name:"Override"` // Synchronization filters Filters []*ReplicationFilter `json:"Filters,omitempty" name:"Filters"` } type SecurityPolicy struct { // Policy index PolicyIndex *int64 `json:"PolicyIndex,omitempty" name:"PolicyIndex"` // Remarks Description *string `json:"Description,omitempty" name:"Description"` // The public network IP address of the access source CidrBlock *string `json:"CidrBlock,omitempty" name:"CidrBlock"` // The version of the security policy PolicyVersion *string `json:"PolicyVersion,omitempty" name:"PolicyVersion"` } type TaskDetail struct { // Task TaskName *string `json:"TaskName,omitempty" name:"TaskName"` // Task UUID TaskUUID *string `json:"TaskUUID,omitempty" name:"TaskUUID"` // Task status TaskStatus *string `json:"TaskStatus,omitempty" name:"TaskStatus"` // Task details // Note: this field may return `null`, indicating that no valid values can be obtained. TaskMessage *string `json:"TaskMessage,omitempty" name:"TaskMessage"` // Start time of the task CreatedTime *string `json:"CreatedTime,omitempty" name:"CreatedTime"` // End time of the task // Note: this field may return `null`, indicating that no valid values can be obtained. FinishedTime *string `json:"FinishedTime,omitempty" name:"FinishedTime"` }
qqizai/Func_Js_Crack
Funny_Js_Crack/138-中华英才网(RSA)/chinahr_login.py
# -*- coding: utf-8 -*- # @Time: 2019/12/24 9:36 # @Version: 1.0 # @Email: <EMAIL> # 代码千万条,整洁第一条,代码不规范,调试两行泪 import json import re import requests import execjs class ChinahrLogin: def __init__(self): self.username = 'username' self.password = 'password' self.index_url = 'https://passport.58.com/' self.login_url = 'https://passport.58.com/login/pc/dologin?' self.token_path = '/login/init?callback=jQuery111305697932980020528_1577152074902&_=1577152074906' self.data_path = '/frontend/data?callback=jQuery111305697932980020528_1577152074902&_=1577152074905' self.headers = { 'authority': 'passport.58.com', 'method': 'GET', 'scheme': 'https', 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9', 'referer': 'https://www.chinahr.com/home/bj/', 'sec-fetch-mode': 'no-cors', 'sec-fetch-site': 'cross-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36', } def extract_result(self,html): information = re.search('data":(\{.*}),"msg',html).group(1) return json.loads(information) def getPwd(self): self.headers.update({'path': self.data_path}) resp_data = requests.get(self.index_url + self.data_path, headers=self.headers) data = self.extract_result(resp_data.text) rsaModulus = data['rsaModulus'] rsaExponent = data['rsaExponent'] with open('./chinahr_login.js','r') as f: enc_pwd = execjs.compile(f.read()).call('getPwd',self.password,rsaModulus,rsaExponent) return enc_pwd def getToken(self): self.headers.update({'path':self.token_path}) resp_token = requests.get(self.index_url+self.token_path,headers=self.headers) token = self.extract_result(resp_token.text) token = token['token'] return token def run(self): enc_pwd = self.getPwd() token = self.getToken() login_formdata = { 'password': <PASSWORD>, 'isremember': '', 'callback': 'window.CL.AsyncModules.successFun', 'fingerprint': 'D44E43B69446C35066274E7EBDB46106BCA8636910C6DF11_010', 'finger2': 'zh-CN|24|1|4|1920_1080|1920_1040|-480|1|1|1|undefined|1|unknown|Win32|unknown|3|true|false|false|false|false|0_false_false|d41d8cd98f00b204e9800998ecf8427e|f7bc91acfdafdfa98b7636d86db4a2f4', 'token': token, 'source': 'chinahrzp-pc', 'path': 'https://www.chinahr.com/', 'username': self.username, 'passwordInputEmpty': '', 'passwordInput': '', 'validcode': '', 'vcodekey': '', 'btnSubmit': '登录中...', } login_headers = { 'authority': 'passport.58.com', 'method': 'POST', 'path': '/login/pc/dologin?', 'scheme': 'https', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9', 'cache-control': 'max-age=0', 'content-length': '843', 'content-type': 'application/x-www-form-urlencoded', 'cookie': 'id58=c5/nn14AhigxeOoisYiwAg==; ppStore_fingerprint=05E460B6111B487630F9712EF9C2CD8E1C69045443D3F578; finger_session=Dma1hHi8fsAznvuWGOXgZISdYYO3pF5M; PPU="UID=34226077324298&UN=%E6%9F%B4er061&TT=207a27e7b141b06f05e4d6bcca89fdc2&PBODY=AhnVDB9shOqYp853wLdecGLfWBnVKvcro7b-OkKZbNsVvXztlS6zgW2VEkH5-PVmC_y9LptBmQ_fdloJ3NZ_wZXgx4vwOG4gb5UCUS_deJ7prv2WW25_PUzIy475NtkRFHZpG4sp-LuYdqbkaH64ZO0rDAR2MDrCaX3DMPnYkUg&VER=1"; www58com="UserID=34226077324298&UserName=%E6%9<PASSWORD>"; 58cooper="userid=34226077324298&username=%E6%<PASSWORD>061"; 58uname=%E6%9F%B4er061; cloudpassport="TT=207a27e7b141b06f05e4d6bcca89fdc2&TS=1577155273369&PBODY=fzAhLxkAEs4D5z1lpxeaj6UhC1XyMO0hCbfLoSD67j0kqGCML3je4FGfRIsB1L-4Csn14KDAOLxuqDUcrSPubPKu2l9uX7NsgGozihCaSoGKxdPX9ckGQpqn9Fmy1jMoTfBPjHR-tSKgp6Gn6rnsnE-tSkw6aatSZou-jqVhb2Q&VER=1"; 58tj_uuid=b723c447-26d0-4d3f-9e4b-c0d3307d7c35; new_uv=1; utm_source=; spm=; init_refer=; als=0; new_session=0', 'origin': 'https://www.chinahr.com', 'referer': 'https://www.chinahr.com/home/bj/', 'sec-fetch-mode': 'nested-navigate', 'sec-fetch-site': 'cross-site', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36', } resp_login = requests.post(self.login_url,headers=login_headers,data=login_formdata) if '"msg":"成功"' in resp_login.text: print('登陆成功') if __name__ == '__main__': ChinahrLogin().run()
fairhopeweb/isotope-mail
client/src/services/image.js
const dataUrlToBlob = dataUrl => { const dataUrlParts = dataUrl.split(','); const mime = dataUrlParts[0].match(/:(.*?);/)[1]; const binStr = atob(dataUrlParts[1]); const len = binStr.length; const u8arr = new Uint8Array(len); for (let i = 0; i < len; i++) { u8arr[i] = binStr.charCodeAt(i); } return new Blob([u8arr], {type: mime}); }; export const compressImage = (imageBlob, type = 'image/jpeg', quality = 0.85) => new Promise(resolve => { const imageUrl = URL.createObjectURL(imageBlob); const image = new Image(); image.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); ctx.imageSmoothingQuality = 'high'; ctx.imageSmoothingEnabled = true; ctx.mozImageSmoothingEnabled = true; ctx.oImageSmoothingEnabled = true; ctx.webkitImageSmoothingEnabled = true; canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(imageUrl); resolve(dataUrlToBlob(canvas.toDataURL(type, quality))); }; image.src = imageUrl; });
ziwa-gangwang/AndroidDemo
app/src/main/java/com/zhou/android/ui/PwdEditText.java
<filename>app/src/main/java/com/zhou/android/ui/PwdEditText.java package com.zhou.android.ui; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.text.InputType; import android.util.AttributeSet; import android.view.inputmethod.EditorInfo; import android.widget.EditText; /** * Created by ZhOu on 2017/2/10. */ public class PwdEditText extends EditText { private Context mContext; private Paint paintBg, paintLine, paintCircle; private float mWidth, mHeight; private int pwd_length = 6, input_length = 0; private float pwd_width; private float pwd_size = 12; private float padding = 8; public PwdEditText(Context context) { this(context, null); } public PwdEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PwdEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; padding = context.getResources().getDisplayMetrics().density * padding; paintBg = new Paint(); paintBg.setColor(Color.WHITE); paintBg.setAntiAlias(true); paintBg.setStyle(Paint.Style.FILL); paintLine = new Paint(); paintLine.setColor(Color.GRAY); paintLine.setAntiAlias(true); paintLine.setStyle(Paint.Style.STROKE); paintCircle = new Paint(); paintLine.setColor(Color.BLACK); paintLine.setAntiAlias(true); paintLine.setStyle(Paint.Style.FILL); setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED); setImeOptions(EditorInfo.IME_ACTION_DONE); setSingleLine(true); setFocusable(true); setFocusableInTouchMode(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); RectF rectf = new RectF(0, 0, mWidth, mHeight); canvas.drawRoundRect(rectf, 10, 10, paintBg); paintLine.setStyle(Paint.Style.STROKE); canvas.drawRoundRect(new RectF(padding, padding, mWidth - padding, padding + pwd_width), 10, 10, paintLine); paintLine.setStyle(Paint.Style.FILL); for (int i = 1; i < pwd_length; i++) { float _x = i * pwd_width + padding; canvas.drawLine(_x, padding, _x, padding + pwd_width, paintLine); } float _halfWidth = pwd_width / 2; for (int i = 0; i < input_length; i++) { canvas.drawCircle(padding + _halfWidth + pwd_width * i, padding + _halfWidth, pwd_size, paintCircle); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = MeasureSpec.getSize(widthMeasureSpec); pwd_width = (mWidth - 2 * padding) / pwd_length; mHeight = pwd_width + 2 * padding; pwd_size = pwd_width / 4; setMeasuredDimension((int) mWidth, (int) mHeight); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); this.input_length = text.toString().length(); if (input_length <= pwd_length) invalidate(); if (pwd_length == input_length) { if (onFinishListener != null) { onFinishListener.onFinish(text.toString()); } } } public interface OnFinishListener { void onFinish(String pwd); } private OnFinishListener onFinishListener; public void setOnFinishListener(OnFinishListener onFinishListener) { this.onFinishListener = onFinishListener; } }
craftyguy/u-root
pkg/acpi/rsdp_linux_test.go
<reponame>craftyguy/u-root // Copyright 2019 the u-root Authors. All rights reserved // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package acpi import ( "testing" "github.com/craftyguy/u-root/pkg/testutil" ) // TestRSDP tests whether any method for getting an RSDP works. func TestRSDP(t *testing.T) { testutil.SkipIfNotRoot(t) _, err := GetRSDP() if err != nil { t.Fatalf("GetRSDP: got %v, want nil", err) } }
solidfire/solidfire-sdk-java
src/generated/java/com/solidfire/element/api/DriveStats.java
<gh_stars>1-10 /* * Copyright &copy 2014-2016 NetApp, 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. */ /* * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen. */ package com.solidfire.element.api; import com.solidfire.gson.Gson; import com.solidfire.core.client.Attributes; import com.solidfire.gson.annotations.SerializedName; import com.solidfire.core.annotation.Since; import com.solidfire.core.javautil.Optional; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; /** * DriveStats **/ public class DriveStats implements Serializable { public static final long serialVersionUID = -7934400888090609919L; @SerializedName("activeSessions") private Optional<Long> activeSessions; @SerializedName("driveID") private Optional<Long> driveID; @SerializedName("failedDieCount") private Long failedDieCount; @SerializedName("lifeRemainingPercent") private Long lifeRemainingPercent; @SerializedName("lifetimeReadBytes") private Long lifetimeReadBytes; @SerializedName("lifetimeWriteBytes") private Long lifetimeWriteBytes; @SerializedName("powerOnHours") private Long powerOnHours; @SerializedName("readBytes") private Long readBytes = 0L; @SerializedName("readOps") private Long readOps = 0L; @SerializedName("reallocatedSectors") private Long reallocatedSectors; @SerializedName("reserveCapacityPercent") private Long reserveCapacityPercent; @SerializedName("timestamp") private String timestamp; @SerializedName("totalCapacity") private Long totalCapacity; @SerializedName("usedCapacity") private Optional<Long> usedCapacity; @SerializedName("usedMemory") private Long usedMemory; @SerializedName("writeBytes") private Long writeBytes = 0L; @SerializedName("writeOps") private Long writeOps = 0L; // empty constructor @Since("7.0") public DriveStats() {} // parameterized constructor @Since("7.0") public DriveStats( Optional<Long> activeSessions, Optional<Long> driveID, Long failedDieCount, Long lifeRemainingPercent, Long lifetimeReadBytes, Long lifetimeWriteBytes, Long powerOnHours, Long readBytes, Long readOps, Long reallocatedSectors, Long reserveCapacityPercent, String timestamp, Long totalCapacity, Optional<Long> usedCapacity, Long usedMemory, Long writeBytes, Long writeOps ) { this.activeSessions = (activeSessions == null) ? Optional.<Long>empty() : activeSessions; this.driveID = (driveID == null) ? Optional.<Long>empty() : driveID; this.failedDieCount = failedDieCount; this.lifeRemainingPercent = lifeRemainingPercent; this.lifetimeReadBytes = lifetimeReadBytes; this.lifetimeWriteBytes = lifetimeWriteBytes; this.powerOnHours = powerOnHours; this.readBytes = readBytes; this.readOps = readOps; this.reallocatedSectors = reallocatedSectors; this.reserveCapacityPercent = reserveCapacityPercent; this.timestamp = timestamp; this.totalCapacity = totalCapacity; this.usedCapacity = (usedCapacity == null) ? Optional.<Long>empty() : usedCapacity; this.usedMemory = usedMemory; this.writeBytes = writeBytes; this.writeOps = writeOps; } /** * **/ public Optional<Long> getActiveSessions() { return this.activeSessions; } public void setActiveSessions(Optional<Long> activeSessions) { this.activeSessions = (activeSessions == null) ? Optional.<Long>empty() : activeSessions; } /** * **/ public Optional<Long> getDriveID() { return this.driveID; } public void setDriveID(Optional<Long> driveID) { this.driveID = (driveID == null) ? Optional.<Long>empty() : driveID; } /** * **/ public Long getFailedDieCount() { return this.failedDieCount; } public void setFailedDieCount(Long failedDieCount) { this.failedDieCount = failedDieCount; } /** * **/ public Long getLifeRemainingPercent() { return this.lifeRemainingPercent; } public void setLifeRemainingPercent(Long lifeRemainingPercent) { this.lifeRemainingPercent = lifeRemainingPercent; } /** * **/ public Long getLifetimeReadBytes() { return this.lifetimeReadBytes; } public void setLifetimeReadBytes(Long lifetimeReadBytes) { this.lifetimeReadBytes = lifetimeReadBytes; } /** * **/ public Long getLifetimeWriteBytes() { return this.lifetimeWriteBytes; } public void setLifetimeWriteBytes(Long lifetimeWriteBytes) { this.lifetimeWriteBytes = lifetimeWriteBytes; } /** * **/ public Long getPowerOnHours() { return this.powerOnHours; } public void setPowerOnHours(Long powerOnHours) { this.powerOnHours = powerOnHours; } /** * **/ public Long getReadBytes() { return this.readBytes; } public void setReadBytes(Long readBytes) { this.readBytes = readBytes; } /** * **/ public Long getReadOps() { return this.readOps; } public void setReadOps(Long readOps) { this.readOps = readOps; } /** * **/ public Long getReallocatedSectors() { return this.reallocatedSectors; } public void setReallocatedSectors(Long reallocatedSectors) { this.reallocatedSectors = reallocatedSectors; } /** * **/ public Long getReserveCapacityPercent() { return this.reserveCapacityPercent; } public void setReserveCapacityPercent(Long reserveCapacityPercent) { this.reserveCapacityPercent = reserveCapacityPercent; } /** * **/ public String getTimestamp() { return this.timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } /** * **/ public Long getTotalCapacity() { return this.totalCapacity; } public void setTotalCapacity(Long totalCapacity) { this.totalCapacity = totalCapacity; } /** * **/ public Optional<Long> getUsedCapacity() { return this.usedCapacity; } public void setUsedCapacity(Optional<Long> usedCapacity) { this.usedCapacity = (usedCapacity == null) ? Optional.<Long>empty() : usedCapacity; } /** * **/ public Long getUsedMemory() { return this.usedMemory; } public void setUsedMemory(Long usedMemory) { this.usedMemory = usedMemory; } /** * **/ public Long getWriteBytes() { return this.writeBytes; } public void setWriteBytes(Long writeBytes) { this.writeBytes = writeBytes; } /** * **/ public Long getWriteOps() { return this.writeOps; } public void setWriteOps(Long writeOps) { this.writeOps = writeOps; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DriveStats that = (DriveStats) o; return Objects.equals(activeSessions, that.activeSessions) && Objects.equals(driveID, that.driveID) && Objects.equals(failedDieCount, that.failedDieCount) && Objects.equals(lifeRemainingPercent, that.lifeRemainingPercent) && Objects.equals(lifetimeReadBytes, that.lifetimeReadBytes) && Objects.equals(lifetimeWriteBytes, that.lifetimeWriteBytes) && Objects.equals(powerOnHours, that.powerOnHours) && Objects.equals(readBytes, that.readBytes) && Objects.equals(readOps, that.readOps) && Objects.equals(reallocatedSectors, that.reallocatedSectors) && Objects.equals(reserveCapacityPercent, that.reserveCapacityPercent) && Objects.equals(timestamp, that.timestamp) && Objects.equals(totalCapacity, that.totalCapacity) && Objects.equals(usedCapacity, that.usedCapacity) && Objects.equals(usedMemory, that.usedMemory) && Objects.equals(writeBytes, that.writeBytes) && Objects.equals(writeOps, that.writeOps); } @Override public int hashCode() { return Objects.hash( activeSessions,driveID,failedDieCount,lifeRemainingPercent,lifetimeReadBytes,lifetimeWriteBytes,powerOnHours,readBytes,readOps,reallocatedSectors,reserveCapacityPercent,timestamp,totalCapacity,usedCapacity,usedMemory,writeBytes,writeOps ); } public java.util.Map<String, Object> toMap() { java.util.Map<String, Object> map = new HashMap<>(); map.put("activeSessions", activeSessions); map.put("driveID", driveID); map.put("failedDieCount", failedDieCount); map.put("lifeRemainingPercent", lifeRemainingPercent); map.put("lifetimeReadBytes", lifetimeReadBytes); map.put("lifetimeWriteBytes", lifetimeWriteBytes); map.put("powerOnHours", powerOnHours); map.put("readBytes", readBytes); map.put("readOps", readOps); map.put("reallocatedSectors", reallocatedSectors); map.put("reserveCapacityPercent", reserveCapacityPercent); map.put("timestamp", timestamp); map.put("totalCapacity", totalCapacity); map.put("usedCapacity", usedCapacity); map.put("usedMemory", usedMemory); map.put("writeBytes", writeBytes); map.put("writeOps", writeOps); return map; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); Gson gson = new Gson(); sb.append( "{ " ); if(null != activeSessions && activeSessions.isPresent()){ sb.append(" activeSessions : ").append(gson.toJson(activeSessions)).append(","); } else{ sb.append(" activeSessions : ").append("null").append(","); } if(null != driveID && driveID.isPresent()){ sb.append(" driveID : ").append(gson.toJson(driveID)).append(","); } else{ sb.append(" driveID : ").append("null").append(","); } sb.append(" failedDieCount : ").append(gson.toJson(failedDieCount)).append(","); sb.append(" lifeRemainingPercent : ").append(gson.toJson(lifeRemainingPercent)).append(","); sb.append(" lifetimeReadBytes : ").append(gson.toJson(lifetimeReadBytes)).append(","); sb.append(" lifetimeWriteBytes : ").append(gson.toJson(lifetimeWriteBytes)).append(","); sb.append(" powerOnHours : ").append(gson.toJson(powerOnHours)).append(","); sb.append(" readBytes : ").append(gson.toJson(readBytes)).append(","); sb.append(" readOps : ").append(gson.toJson(readOps)).append(","); sb.append(" reallocatedSectors : ").append(gson.toJson(reallocatedSectors)).append(","); sb.append(" reserveCapacityPercent : ").append(gson.toJson(reserveCapacityPercent)).append(","); sb.append(" timestamp : ").append(gson.toJson(timestamp)).append(","); sb.append(" totalCapacity : ").append(gson.toJson(totalCapacity)).append(","); if(null != usedCapacity && usedCapacity.isPresent()){ sb.append(" usedCapacity : ").append(gson.toJson(usedCapacity)).append(","); } else{ sb.append(" usedCapacity : ").append("null").append(","); } sb.append(" usedMemory : ").append(gson.toJson(usedMemory)).append(","); sb.append(" writeBytes : ").append(gson.toJson(writeBytes)).append(","); sb.append(" writeOps : ").append(gson.toJson(writeOps)).append(","); sb.append( " }" ); if(sb.lastIndexOf(", }") != -1) sb.deleteCharAt(sb.lastIndexOf(", }")); return sb.toString(); } public static Builder builder() { return new Builder(); } public final Builder asBuilder() { return new Builder().buildFrom(this); } public static class Builder { private Optional<Long> activeSessions; private Optional<Long> driveID; private Long failedDieCount; private Long lifeRemainingPercent; private Long lifetimeReadBytes; private Long lifetimeWriteBytes; private Long powerOnHours; private Long readBytes; private Long readOps; private Long reallocatedSectors; private Long reserveCapacityPercent; private String timestamp; private Long totalCapacity; private Optional<Long> usedCapacity; private Long usedMemory; private Long writeBytes; private Long writeOps; private Builder() { } public DriveStats build() { return new DriveStats ( this.activeSessions, this.driveID, this.failedDieCount, this.lifeRemainingPercent, this.lifetimeReadBytes, this.lifetimeWriteBytes, this.powerOnHours, this.readBytes, this.readOps, this.reallocatedSectors, this.reserveCapacityPercent, this.timestamp, this.totalCapacity, this.usedCapacity, this.usedMemory, this.writeBytes, this.writeOps); } private DriveStats.Builder buildFrom(final DriveStats req) { this.activeSessions = req.activeSessions; this.driveID = req.driveID; this.failedDieCount = req.failedDieCount; this.lifeRemainingPercent = req.lifeRemainingPercent; this.lifetimeReadBytes = req.lifetimeReadBytes; this.lifetimeWriteBytes = req.lifetimeWriteBytes; this.powerOnHours = req.powerOnHours; this.readBytes = req.readBytes; this.readOps = req.readOps; this.reallocatedSectors = req.reallocatedSectors; this.reserveCapacityPercent = req.reserveCapacityPercent; this.timestamp = req.timestamp; this.totalCapacity = req.totalCapacity; this.usedCapacity = req.usedCapacity; this.usedMemory = req.usedMemory; this.writeBytes = req.writeBytes; this.writeOps = req.writeOps; return this; } public DriveStats.Builder optionalActiveSessions(final Long activeSessions) { this.activeSessions = (activeSessions == null) ? Optional.<Long>empty() : Optional.of(activeSessions); return this; } public DriveStats.Builder optionalDriveID(final Long driveID) { this.driveID = (driveID == null) ? Optional.<Long>empty() : Optional.of(driveID); return this; } public DriveStats.Builder failedDieCount(final Long failedDieCount) { this.failedDieCount = failedDieCount; return this; } public DriveStats.Builder lifeRemainingPercent(final Long lifeRemainingPercent) { this.lifeRemainingPercent = lifeRemainingPercent; return this; } public DriveStats.Builder lifetimeReadBytes(final Long lifetimeReadBytes) { this.lifetimeReadBytes = lifetimeReadBytes; return this; } public DriveStats.Builder lifetimeWriteBytes(final Long lifetimeWriteBytes) { this.lifetimeWriteBytes = lifetimeWriteBytes; return this; } public DriveStats.Builder powerOnHours(final Long powerOnHours) { this.powerOnHours = powerOnHours; return this; } public DriveStats.Builder readBytes(final Long readBytes) { this.readBytes = readBytes; return this; } public DriveStats.Builder readOps(final Long readOps) { this.readOps = readOps; return this; } public DriveStats.Builder reallocatedSectors(final Long reallocatedSectors) { this.reallocatedSectors = reallocatedSectors; return this; } public DriveStats.Builder reserveCapacityPercent(final Long reserveCapacityPercent) { this.reserveCapacityPercent = reserveCapacityPercent; return this; } public DriveStats.Builder timestamp(final String timestamp) { this.timestamp = timestamp; return this; } public DriveStats.Builder totalCapacity(final Long totalCapacity) { this.totalCapacity = totalCapacity; return this; } public DriveStats.Builder optionalUsedCapacity(final Long usedCapacity) { this.usedCapacity = (usedCapacity == null) ? Optional.<Long>empty() : Optional.of(usedCapacity); return this; } public DriveStats.Builder usedMemory(final Long usedMemory) { this.usedMemory = usedMemory; return this; } public DriveStats.Builder writeBytes(final Long writeBytes) { this.writeBytes = writeBytes; return this; } public DriveStats.Builder writeOps(final Long writeOps) { this.writeOps = writeOps; return this; } } }
HoffmanAufs/retrieval_test
pkg/api/export_test.go
// Copyright 2020 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package api import "github.com/gauss-project/aurorafs/pkg/boson" type Server = server type ( BytesPostResponse = bytesPostResponse ChunkAddressResponse = chunkAddressResponse SocPostResponse = socPostResponse FileUploadResponse = fileUploadResponse ) var ( ContentTypeTar = contentTypeTar ) var ( ManifestRootPath = manifestRootPath ManifestWebsiteIndexDocumentSuffixKey = manifestWebsiteIndexDocumentSuffixKey ManifestWebsiteErrorDocumentPathKey = manifestWebsiteErrorDocumentPathKey ) var ( ErrNoResolver = errNoResolver ErrInvalidNameOrAddress = errInvalidNameOrAddress ) func (s *Server) ResolveNameOrAddress(str string) (boson.Address, error) { return s.resolveNameOrAddress(str) } func CalculateNumberOfChunks(contentLength int64, isEncrypted bool) int64 { return calculateNumberOfChunks(contentLength, isEncrypted) }
INC-PSTORE/pstore
frontend/app/containers/unshielding-page/actions.js
/* * Unshield Page actions */ import { CHANGE_SELECTED_PTOKEN, CHANGE_AMOUNT_TO_UNSHIELD, UPDATE_STEP, DO_NOTHING, CHANGE_ETH_ADDRESS_TO_UNSHIELD, GET_LATEST_UNSUCCESSFUL_UNSHIELD_SUCCESS, GET_LATEST_UNSUCCESSFUL_UNSHIELD_FAILURE, REFRESH_UNSHIELD_FAILURE, UPDATE_INC_TX_INFO, UPDATE_ETH_TX_INFO, UPDATE_VALIDATE_INPUT, SKIP_FORM, TOOL_TIP_HANDLER, } from './constants'; // using name as key temporary export function changeSelectedToken(tokenId) { return { type: CHANGE_SELECTED_PTOKEN, tokenId, }; } export function changeStep(stepNumber) { return { type: UPDATE_STEP, stepNumber, } } export function changeAmount(amount) { if(!isNaN(parseFloat(amount))) { return { type: CHANGE_AMOUNT_TO_UNSHIELD, amount, } } else { return { type: DO_NOTHING, } } } export function changeEthAddress(ethAddress) { return { type: CHANGE_ETH_ADDRESS_TO_UNSHIELD, ethAddress, } } // export function getLatestUnsuccessfulUnshield() { // return { // type: GET_LATEST_UNSUCCESSFUL_UNSHIELD, // }; // } export function getLatestUnsuccessfulUnshieldSuccess(unshield) { return { type: GET_LATEST_UNSUCCESSFUL_UNSHIELD_SUCCESS, unshield, }; } export function getLatestUnsuccessfulUnshieldFailed(error) { return { type: GET_LATEST_UNSUCCESSFUL_UNSHIELD_FAILURE, error, } } export function refreshUnsieldFailure(error) { return { type: REFRESH_UNSHIELD_FAILURE, error, } } export function updateEthTxInfo(ethTxInfo) { return { type: UPDATE_ETH_TX_INFO, ethTxInfo, } } export function updateIncTxInfo(incTxInfo) { return { type: UPDATE_INC_TX_INFO, incTxInfo, } } export function updateValidateForm(validateForm) { return { type: UPDATE_VALIDATE_INPUT, validateForm, } } export function updateSkipForm(skipForm) { return { type: SKIP_FORM, skipForm, } } export function updateToolTip(isOpenToolTip) { return { type: TOOL_TIP_HANDLER, isOpenToolTip, } }
erikpe/traci
src/se/ejp/traci/gui/BufferedImageDrawArea.java
<reponame>erikpe/traci package se.ejp.traci.gui; import java.awt.image.BufferedImage; import se.ejp.traci.model.Color; public class BufferedImageDrawArea extends AbstractDrawArea { private final BufferedImage image; public BufferedImageDrawArea(final int width, final int height) { super(width, height); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } @Override public void draw(final long x, final long y, final Color color) { long r = (long) (color.r * 255); long g = (long) (color.g * 255); long b = (long) (color.b * 255); r = (r > 255 ? 255 : r); g = (g > 255 ? 255 : g); b = (b > 255 ? 255 : b); r = (r < 0 ? 0 : r); g = (g < 0 ? 0 : g); b = (b < 0 ? 0 : b); final int intColor = 0xff000000 | (int) (r << 16) | (int) (g << 8) | (int) b; image.getRaster().setDataElements((int) x, (int) y, image.getColorModel().getDataElements(intColor, null)); } public BufferedImage getBufferedImage() { return image; } }
Arodev76/L2Advanced
dist/gameserver/data/scripts/ai/Elpy.java
package ai; import l2f.commons.util.Rnd; import l2f.gameserver.ai.Fighter; import l2f.gameserver.geodata.GeoEngine; import l2f.gameserver.model.Creature; import l2f.gameserver.model.instances.NpcInstance; import l2f.gameserver.utils.Location; public class Elpy extends Fighter { public Elpy(NpcInstance actor) { super(actor); } @Override protected void onEvtAttacked(Creature attacker, int damage) { NpcInstance actor = getActor(); if (attacker != null && Rnd.chance(50)) { Location pos = Location.findPointToStay(actor, 150, 200); if (GeoEngine.canMoveToCoord(actor.getX(), actor.getY(), actor.getZ(), pos.x, pos.y, pos.z, actor.getGeoIndex())) { actor.setRunning(); addTaskMove(pos, false); } } } @Override protected boolean checkAggression(Creature target, boolean avoidAttack) { return false; } @Override protected void onEvtAggression(Creature target, int aggro) { } }
T0UGH/zady-micro
zady-micro-report/src/main/java/com/edu/neu/zadymicroreport/controller/StatisticController.java
<reponame>T0UGH/zady-micro package com.edu.neu.zadymicroreport.controller; import com.edu.neu.zadymicrocommon.annotation.Auth; import com.edu.neu.zadymicrocommon.exception.NotFoundException; import com.edu.neu.zadymicrocommon.pojo.Bornout; import com.edu.neu.zadymicrocommon.pojo.DashBoard; import com.edu.neu.zadymicrocommon.pojo.Role; import com.edu.neu.zadymicroreport.service.BornoutService; import com.edu.neu.zadymicroreport.service.DashBoardService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.Date; import java.util.List; @RestController public class StatisticController { @Resource DashBoardService dashBoardService; @Resource BornoutService bornoutService; @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @GetMapping("/dashBoard/project/{projectId}") public DashBoard getDashBoardByProject(@PathVariable Integer projectId) { DashBoard dashBoard = dashBoardService.selectByProject(projectId); if(dashBoard == null){ throw new NotFoundException("给定project[" + projectId +"]对应dashboard未找到"); } return dashBoard; } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @GetMapping("dashBoard/sprint/{sprintId}") public DashBoard getDashBoardBySprint(@PathVariable Integer sprintId) { DashBoard dashBoard = dashBoardService.selectBySprint(sprintId); if(dashBoard == null){ throw new NotFoundException("给定sprint[" + sprintId +"]对应dashboard未找到"); } return dashBoard; } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @GetMapping("bornout/sprint/{sprintId}") public List<Bornout> getBornoutBySprint(@PathVariable Integer sprintId) { List<Bornout> bornoutList = bornoutService.selectBySprint(sprintId); if(bornoutList == null){ throw new NotFoundException("给定sprint[" + sprintId +"]对应bornout未找到"); } return bornoutList; } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PostMapping("bornout") Integer addBornout(Integer sprintId, Date createDate){ return bornoutService.addBornout(sprintId, createDate); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PostMapping("dashboard/{sprintId}") public Integer insert(@PathVariable Integer sprintId){ return dashBoardService.insert(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/backlogNum/add/{sprintId}") public Integer addBacklogNum(@PathVariable Integer sprintId){ return dashBoardService.addBacklogNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/backlogNum/sub/{sprintId}") public Integer subBacklogNum(@PathVariable Integer sprintId){ return dashBoardService.subBacklogNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/finishedBacklogNum/add/{sprintId}") public Integer addFinishedBacklogNum(@PathVariable Integer sprintId){ return dashBoardService.addFinishedBacklogNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/storyNum/add/{sprintId}") public Integer addStoryNum(@PathVariable Integer sprintId){ return dashBoardService.addStoryNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/storyNum/sub/{sprintId}") public Integer subStoryNum(@PathVariable Integer sprintId){ return dashBoardService.subStoryNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/inTimeStoryNum/add/{sprintId}") public Integer addInTimeStoryNum(@PathVariable Integer sprintId){ return dashBoardService.addInTimeStoryNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/outTimeStoryNum/add/{sprintId}") public Integer addOutTimeStoryNum(@PathVariable Integer sprintId){ return dashBoardService.addOutTimeStoryNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/bugNum/add/{sprintId}") public Integer addBugNum(@PathVariable Integer sprintId){ return dashBoardService.addBugNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/bugNum/sub/{sprintId}") public Integer subBugNum(@PathVariable Integer sprintId){ return dashBoardService.subStoryNum(sprintId); } @Auth(sameProject = true, role = {Role.RoleEnum.master, Role.RoleEnum.owner, Role.RoleEnum.developer, Role.RoleEnum.tester}) @PutMapping("dashboard/solvedBugNum/add/{sprintId}") public Integer addSolvedBugNum(@PathVariable Integer sprintId){ return dashBoardService.addSolvedBugNum(sprintId); } }
hatbui345/yng-fishjoy
room/app/cmd/gateCmd.js
const SysCmd = require('../consts/sysCmd') /** * 网关接口定义 */ class GateCmd extends SysCmd{ constructor(){ super() this.initReq(); this.initPush(); } initReq(){ super.initReq(); /** * 分配登录服务器 * @type {{route: string, msg: {enc: string, data: {token: string}}, res: {}}} */ this._req.queryEntry = { route:'gate.gateHandler.queryEntry', msg:{ enc:'aes', data:{ token:'<KEY>' } }, res:{} }; } initPush(){ super.initPush() } } module.exports = new GateCmd();
vnma0/hestia
src/app/problemList/problemLauncher.js
<reponame>vnma0/hestia<filename>src/app/problemList/problemLauncher.js import React from 'react'; import { ListItemIcon, ListItemText } from '@material-ui/core'; import Description from '@material-ui/icons/Assignment'; import { withNamespaces } from 'react-i18next'; /** * @name ProblemLauncher * @description Element to be rendered in the sidenav, responsible for launching submission table */ class ProblemLauncher extends React.Component { render() { const { t } = this.props; return ( <> <ListItemIcon> <Description /> </ListItemIcon> <ListItemText>{t('problems.launcher')}</ListItemText> </> ); } } export default withNamespaces()(ProblemLauncher);
sergeishay/Screenters
source-pack/pro/ControlledSelect/ControlledSelectInput/index.js
<filename>source-pack/pro/ControlledSelect/ControlledSelectInput/index.js export { default } from './ControlledSelectInput'; export * from './ControlledSelectInput';
ckamtsikis/cmssw
DQM/SiStripMonitorSummary/interface/SiStripCablingDQM.h
<filename>DQM/SiStripMonitorSummary/interface/SiStripCablingDQM.h #ifndef SiStripMonitorSummary_SiStripCablingDQM_h #define SiStripMonitorSummary_SiStripCablingDQM_h #include "CalibFormats/SiStripObjects/interface/SiStripDetCabling.h" #include "CalibTracker/Records/interface/SiStripDetCablingRcd.h" #include "DQM/SiStripMonitorSummary/interface/SiStripBaseCondObjDQM.h" class SiStripCablingDQM : public SiStripBaseCondObjDQMGet<SiStripDetCabling, SiStripDetCablingRcd> { public: SiStripCablingDQM(edm::ESGetToken<SiStripDetCabling, SiStripDetCablingRcd> token, edm::RunNumber_t iRun, edm::ParameterSet const &hPSet, edm::ParameterSet const &fPSet, const TrackerTopology *tTopo, const TkDetMap *tkDetMap); ~SiStripCablingDQM() override; void fillModMEs(const std::vector<uint32_t> &selectedDetIds) override { ; } void fillSummaryMEs(const std::vector<uint32_t> &selectedDetIds) override { ; } void fillMEsForDet(const ModMEs &selModME_, uint32_t selDetId_) override { ; } void fillMEsForLayer( /*std::map<uint32_t, ModMEs> selModMEsMap_, */ uint32_t selDetId_) override { ; } void getActiveDetIds(const edm::EventSetup &eSetup) override; }; #endif
MarcusJones/udacity_blockchain
PROJECT7_flight_surety_FINAL/src/server/server.js
import FlightSuretyApp from '../../build/contracts/FlightSuretyApp.json'; // import FlightSuretyData from '../../build/contracts/FlightSuretyData.json'; import Config from './config.json'; import Web3 from 'web3'; import express from 'express'; import { start } from 'repl'; let config = Config['localhost']; let web3 = new Web3(new Web3.providers.WebsocketProvider(config.url.replace('http', 'ws'))); web3.eth.defaultAccount = web3.eth.accounts[0]; let flightSuretyApp = new web3.eth.Contract(FlightSuretyApp.abi, config.appAddress); // let flightSuretyData = new web3.eth.Contract(FlightSuretyData.abi, config.dataAddress); const ORACLES_COUNT = 21; let oracle_accounts = []; let fee = 1000000000000000000;// 1 ether in wei. const STATUS_CODE_UNKNOWN = 0; const STATUS_CODE_ON_TIME = 10; const STATUS_CODE_LATE_AIRLINE = 20; const STATUS_CODE_LATE_WEATHER = 30; const STATUS_CODE_LATE_TECHNICAL = 40; const STATUS_CODE_LATE_OTHER = 50; const STATUS_CODES = [STATUS_CODE_UNKNOWN, STATUS_CODE_ON_TIME, STATUS_CODE_LATE_AIRLINE, STATUS_CODE_LATE_WEATHER, STATUS_CODE_LATE_TECHNICAL, STATUS_CODE_LATE_OTHER]; function getRandomStatusCode() { // All choices: // let choice = STATUS_CODES[Math.floor(Math.random() * STATUS_CODES.length)]; // console.log('Random idx;',choice); // return choice; // return STATUS_CODES[Math.floor(Math.random() * STATUS_CODES.length)]; // For testing, simulate randomly ON_TIME or LATE let coinFlip = (Math.floor(Math.random() * 2) == 0); // console.log(coinFlip); if (coinFlip) { return STATUS_CODE_LATE_AIRLINE; } else { return STATUS_CODE_ON_TIME; } } web3.eth.getAccounts((err, accounts) => { // flightSuretyData.methods // .authorizeCaller(config.appAddress) // .send({ from: accounts[0] }, (err, result) => { // if(err) { // console.log(err); // } else { // console.log("App authorized."); // } // }); let startAcct = 25; let endAcct = 50 for (let idx = startAcct; idx < endAcct; idx++) { flightSuretyApp.methods .registerOracle() .send({ from: accounts[idx], value: fee, gas: 6721975 }, (err, reg_result) => { if (err) { console.log('ERROR IN GET ACCOUNTS'); // console.log(err); } else { flightSuretyApp.methods .getMyIndexes() .call({ from: accounts[idx] }, (err, res) => { if (err) { // console.log(err); console.log('ERROR IN GET INDICES'); } else { let oracle = { address: accounts[idx], indexes: res }; oracle_accounts.push(oracle); console.log(idx, "Oracle registered: " + JSON.stringify(oracle)); } }); } }); } }); flightSuretyApp.events.OracleRequest({ fromBlock: 0 }, function (err, event) { if (err) { console.log('ERROR HERE'); // console.log(err); } else { // let tsnow = new Date(); console.log(Date(), 'Received event!'); let index = event.returnValues.index; let airline = event.returnValues.airline; let flight = event.returnValues.flight; let timestamp = event.returnValues.timestamp; let statusCode = getRandomStatusCode(); console.log(`The oracles are simulating a status code of ${statusCode}`); for (let idx = 0; idx < oracle_accounts.length; idx++) { if (oracle_accounts[idx].indexes.includes(index)) { // console.log("This oracle matches, sending update: " + JSON.stringify(oracle_accounts[idx])); flightSuretyApp.methods .submitOracleResponse(index, airline, flight, timestamp, statusCode) .send({ from: oracle_accounts[idx].address, gas: 200000 }, (err, res) => { if (err) { console.log(err); // console.log('No match'); } else { console.log(idx, "Oracle Response " + JSON.stringify(oracle_accounts[idx]) + " Status Code: " + statusCode); } }); } else { console.log(idx, `(Oracle does not match indices)`); } } } }); const app = express(); app.get('/api', (req, res) => { res.send({ message: 'An API for use with your Dapp!' }) }) export default app;
verdantyang/janusgraph
janusgraph-backend-testutils/src/main/java/org/janusgraph/graphdb/GraphDatabaseConfigurationInstanceExecutorServiceTest.java
<filename>janusgraph-backend-testutils/src/main/java/org/janusgraph/graphdb/GraphDatabaseConfigurationInstanceExecutorServiceTest.java // Copyright 2021 JanusGraph Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.janusgraph.graphdb; import org.apache.commons.configuration2.MapConfiguration; import org.janusgraph.diskstorage.configuration.ExecutorServiceBuilder; import org.janusgraph.diskstorage.configuration.ExecutorServiceConfiguration; import org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration; import org.janusgraph.graphdb.configuration.builder.GraphDatabaseConfigurationBuilder; import org.janusgraph.graphdb.database.StandardJanusGraph; import org.janusgraph.util.system.ConfigurationUtil; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.PARALLEL_BACKEND_EXECUTOR_SERVICE_CORE_POOL_SIZE; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.PARALLEL_BACKEND_EXECUTOR_SERVICE_KEEP_ALIVE_TIME; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.PARALLEL_BACKEND_OPS; import static org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_HOSTNAME; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public abstract class GraphDatabaseConfigurationInstanceExecutorServiceTest { public abstract Map<String, Object> getStorageConfiguration(); @Test public void shouldCreateCustomBackendFixedThreadPoolSize() { final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CORE_POOL_SIZE.toStringWithoutRoot(), 15); final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(map); assertDoesNotThrow(() -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); } @Test public void shouldCreateCustomBackendCachedThreadPoolSize() { final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), ExecutorServiceBuilder.CACHED_THREAD_POOL_CLASS); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CORE_POOL_SIZE.toStringWithoutRoot(), 15); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_KEEP_ALIVE_TIME.toStringWithoutRoot(), 30000); final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(map); assertDoesNotThrow(() -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); } @Test public void shouldCreateCustomBackendExecutorServiceWithExecutorServiceConfigurationConstructor() { final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CORE_POOL_SIZE.toStringWithoutRoot(), 15); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), CustomExecutorServiceImplementation.class.getName()); final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(map); assertDoesNotThrow(() -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); } @Test public void shouldCreateCustomBackendExecutorServiceWithoutExecutorServiceConfigurationConstructor() { final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), CustomParameterlessExecutorServiceImplementation.class.getName()); final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(map); assertDoesNotThrow(() -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); } @Test public void shouldCreateCustomBackendExecutorServiceWithoutBothExecutorServiceConfigurationConstructors() { final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CORE_POOL_SIZE.toStringWithoutRoot(), 15); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), CustomExecutorServiceWithBothConstructorsImplementation.class.getName()); final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(map); assertDoesNotThrow(() -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); } @Test public void shouldNotCreateBackendExecutorServiceIfClassNotExists() { String configurationClass = "not-existing-class"; final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), configurationClass); checkExceptionIsThrownDuringInit(IllegalArgumentException.class, map, "No ExecutorService class found with class name: "+configurationClass); } @Test public void shouldNotCreateBackendExecutorServiceIfClassHasNoNecessaryConstructor() { String configurationClass = CustomExecutorServiceImplementationWithoutNecessaryConstructor.class.getName(); final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), configurationClass); checkExceptionIsThrownDuringInit(IllegalArgumentException.class, map, configurationClass + " has neither public constructor which accepts " + ExecutorServiceConfiguration.class.getName() + " nor parameterless public constructor."); } @Test public void shouldNotCreateBackendExecutorServiceIfClassNotImplementsExecutorService() { String configurationClass = HashSet.class.getName(); final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), configurationClass); checkExceptionIsThrownDuringInit(IllegalArgumentException.class, map, configurationClass + "isn't a subclass of "+ ExecutorService.class.getName()); } @Test public void shouldNotCreateBackendExecutorServiceIfClassHasNoPublicConstructor() { String configurationClass = CustomExecutorServiceImplementationWithoutPublicConstructor.class.getName(); final Map<String, Object> map = getStorageConfiguration(); map.put(UNIQUE_INSTANCE_ID_HOSTNAME.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_OPS.toStringWithoutRoot(), true); map.put(PARALLEL_BACKEND_EXECUTOR_SERVICE_CLASS.toStringWithoutRoot(), configurationClass); checkExceptionIsThrownDuringInit(IllegalStateException.class, map, "Couldn't create a new instance of "+configurationClass + ". Please, check that the constructor which accepts "+ExecutorServiceConfiguration.class.getName() +" is public or there is a public parameterless constructor. If the necessary public constructor exists, " + "please, check that invocation of this constructor doesn't throw an exception."); } private <T extends Exception> void checkExceptionIsThrownDuringInit(Class<T> exceptionType, Map<String, Object> configMap, String message){ final MapConfiguration config = ConfigurationUtil.loadMapConfiguration(configMap); T exception = assertThrows(exceptionType, () -> { final StandardJanusGraph graph = new StandardJanusGraph(new GraphDatabaseConfigurationBuilder().build(new CommonsConfiguration(config))); graph.traversal().V().hasNext(); graph.close(); }); assertEquals(message, exception.getMessage()); } public static class CustomExecutorServiceImplementation extends ThreadPoolExecutor { public CustomExecutorServiceImplementation(ExecutorServiceConfiguration executorServiceConfiguration){ super(executorServiceConfiguration.getCorePoolSize(), executorServiceConfiguration.getMaxPoolSize(), executorServiceConfiguration.getKeepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } } public static class CustomParameterlessExecutorServiceImplementation extends ThreadPoolExecutor { public CustomParameterlessExecutorServiceImplementation(){ super(1, 2, 3, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } } public static class CustomExecutorServiceWithBothConstructorsImplementation extends ThreadPoolExecutor { public CustomExecutorServiceWithBothConstructorsImplementation(){ super(1, 2, 3, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } public CustomExecutorServiceWithBothConstructorsImplementation(ExecutorServiceConfiguration executorServiceConfiguration){ super(executorServiceConfiguration.getCorePoolSize(), executorServiceConfiguration.getMaxPoolSize(), executorServiceConfiguration.getKeepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } } public static class CustomExecutorServiceImplementationWithoutNecessaryConstructor extends ThreadPoolExecutor { public CustomExecutorServiceImplementationWithoutNecessaryConstructor(int corePoolSize){ super(corePoolSize, 2, 3, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } } public static class CustomExecutorServiceImplementationWithoutPublicConstructor extends ThreadPoolExecutor { private CustomExecutorServiceImplementationWithoutPublicConstructor(){ super(1, 2, 3, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); } } }
rekeiri/slogo
src/model/commands/control/StringVar.java
<filename>src/model/commands/control/StringVar.java package model.commands.control; import java.util.List; import model.commands.Command; import model.commands.CommandException; import model.state.State; public class StringVar extends Command { private String name; @Override public List<State> execute(List<State> states) throws CommandException { return states; } @Override public double getReturnValue() { System.out.println(name); return variableDictionary.get(name); } public String getString() { return name; } public void setString(String s) { name = s; } }
insphereapplication/rhodes
platform/bb/Hsqldb/src/com/rho/db/HsqlDBResult.java
<gh_stars>0 package com.rho.db; import org.hsqldb.Record; import org.hsqldb.Result; import org.hsqldb.Trace; import org.hsqldb.Types; import org.hsqldb.HsqlException; import com.xruby.runtime.builtin.ObjectFactory; import com.xruby.runtime.lang.*; import j2me.math.Number; public class HsqlDBResult implements IDBResult { private Result m_result; private Record m_current; // private int m_nCurIndex; public HsqlDBResult(Result res){ m_result = res; reset(); } public HsqlDBResult(){ } public void close() { } /* public int getCount(){ return m_result != null ? m_result.getSize() : 0; }*/ public boolean isNonUnique() { if ( m_result != null && m_result.getException() != null && m_result.getException() instanceof HsqlException ) { HsqlException e = (HsqlException)m_result.getException(); return e.getErrorCode() == -Trace.VIOLATION_OF_UNIQUE_INDEX || e.getErrorCode() == -Trace.VIOLATION_OF_UNIQUE_CONSTRAINT; } return false; } public int getColCount(){ return m_result != null ? m_result.getColumnCount() : 0; } public String getColName(int nCol){ Result.ResultMetaData md = m_result.metaData; if ( md.tableNames[nCol] != null && md.tableNames[nCol].length() > 0 ) return md.colNames[nCol];//.toLowerCase(); //AS alias return md.colNames[nCol]; } public String getOrigColName(int nCol){ Result.ResultMetaData md = m_result.metaData; if ( md.tableNames[nCol] != null && md.tableNames[nCol].length() > 0 ) { if ( md.colOrigNames[nCol] != null ) return md.colOrigNames[nCol]; return md.colNames[nCol];//.toLowerCase(); } //AS alias return md.colNames[nCol]; } public Result getResult(){ return m_result; } /* public RubyValue getRubyValueByIdx(int nItem, int nCol) { Object val = getColvalueByIdx(nItem,nCol); if (val == null) return RubyConstant.QNIL; switch( m_result.metaData.colTypes[nCol] ) { case Types.NULL : return RubyConstant.QNIL; case Types.VARCHAR : case Types.LONGVARCHAR : case Types.CHAR : case Types.VARCHAR_IGNORECASE : return ObjectFactory.createString((String)val); case Types.TINYINT : case Types.SMALLINT : case Types.INTEGER : return ObjectFactory.createInteger(Number.intValue(val)); case Types.BIGINT : return ObjectFactory.createInteger(Number.longValue(val)); case Types.REAL : case Types.FLOAT : case Types.DOUBLE : return ObjectFactory.createFloat(Number.doubleValue(val)); case Types.BOOLEAN : return ObjectFactory.createBoolean(((Boolean) val).booleanValue()); case Types.NUMERIC : case Types.DECIMAL : case Types.DATE : case Types.TIME : case Types.TIMESTAMP : case Types.BINARY : case Types.VARBINARY : case Types.LONGVARBINARY : case Types.OTHER : return ObjectFactory.createString(val.toString()); } throw new java.lang.RuntimeException("HsqlDBResult: unknown type :" + m_result.metaData.colTypes[nCol] ); // return ObjectFactory.createString(); } public long getLongByIdx(int nItem, int nCol) { Object val = getColvalueByIdx(nItem,nCol); return val != null ? Number.longValue(val) : 0; } public int getIntByIdx(int nItem, int nCol) { Object val = getColvalueByIdx(nItem,nCol); return val != null ? Number.intValue(val) : 0; } public String getStringByIdx(int nItem, int nCol) { Object val = getColvalueByIdx(nItem,nCol); return val != null ? val.toString() : ""; } public RubyValue getRubyValue(int nItem, String colname){ return getRubyValueByIdx(nItem, findColIndex(colname) ); } public long getLong(int nItem, String colname){ return getLongByIdx(nItem, findColIndex(colname) ); } public int getInt(int nItem, String colname){ return getIntByIdx(nItem, findColIndex(colname) ); } public String getString(int nItem, String colname){ return getStringByIdx(nItem, findColIndex(colname) ); } Object getColvalueByIdx(int nItem, int nCol) { if ( nCol < 0 || nCol >= getColCount() ) throw new IndexOutOfBoundsException("HsqlDBResult.getStringByIdx : " + nCol + ". Count : " + getColCount() ); Object[] item = getItem(nItem); if ( item != null ) return item[nCol]; return null; }*/ private void reset(){ m_current = m_result.rRoot; // m_nCurIndex = 0; } /* Object[] getItem(int nItem){ if ( m_current == null || nItem < 0 || nItem >= getCount() ) return null; if ( m_nCurIndex > nItem ) reset(); if ( m_nCurIndex < nItem ){ for ( ; m_nCurIndex < nItem; m_nCurIndex++ ) m_current = m_current.next; } return m_current.data; } int findColIndex(String colname ) { for( int i = 0; i < getColCount(); i++ ) { if ( m_result.metaData.colNames[i].equalsIgnoreCase(colname) ) return i; } return -1; }*/ //New public boolean isEnd() { return m_current == null; } public boolean isOneEnd() { return m_current == null; } public void next() throws DBException { if ( m_current != null ) m_current = m_current.next; } protected Object getCurValue(int nCol) { return m_current.data[nCol]; } public Object[] getCurData() throws DBException { return m_current.data; } public boolean isNullByIdx(int nCol) { Object val = getCurValue(nCol); return val == null; } public String getStringByIdx(int nCol) { Object val = getCurValue(nCol); return val != null ? val.toString() : ""; } public int getIntByIdx(int nCol) { Object val = getCurValue(nCol); return val != null ? Number.intValue(val) : 0; } public long getLongByIdx(int nCol) { Object val = getCurValue(nCol); return val != null ? Number.longValue(val) : 0; } public String getUInt64ByIdx(int nCol) { return getStringByIdx(nCol); } public RubyValue getRubyValueByIdx(int nCol) { Object val = getCurValue(nCol); if (val == null) return RubyConstant.QNIL; switch( m_result.metaData.colTypes[nCol] ) { case Types.NULL : return RubyConstant.QNIL; case Types.VARCHAR : case Types.LONGVARCHAR : case Types.CHAR : case Types.VARCHAR_IGNORECASE : return ObjectFactory.createString((String)val); case Types.TINYINT : case Types.SMALLINT : case Types.INTEGER : return ObjectFactory.createInteger(Number.intValue(val)); case Types.BIGINT : return ObjectFactory.createInteger(Number.longValue(val)); case Types.REAL : case Types.FLOAT : case Types.DOUBLE : return ObjectFactory.createFloat(Number.doubleValue(val)); case Types.BOOLEAN : //return ObjectFactory.createBoolean(((Boolean) val).booleanValue()); case Types.NUMERIC : case Types.DECIMAL : case Types.DATE : case Types.TIME : case Types.TIMESTAMP : case Types.BINARY : case Types.VARBINARY : case Types.LONGVARBINARY : case Types.OTHER : return ObjectFactory.createString(val.toString()); } throw new java.lang.RuntimeException("HsqlDBResult: unknown type :" + m_result.metaData.colTypes[nCol] ); // return ObjectFactory.createString(); } public RubyValue getRubyValue(String colname){ return getRubyValueByIdx( findColIndex(colname) ); } public int getInt(String colname){ return getIntByIdx( findColIndex(colname) ); } public String getString(String colname){ return getStringByIdx(findColIndex(colname) ); } int findColIndex(String colname ) { for( int i = 0; i < getColCount(); i++ ) { if ( m_result.metaData.colNames[i].equalsIgnoreCase(colname) ) return i; } return -1; } }
bifeldy/PM-Mingguan
Week13_13536/app/src/main/java/id/ac/umn/week13_13536/SignedInActivity.java
package id.ac.umn.week13_13536; import android.content.Intent; import android.os.PersistableBundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class SignedInActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signed_in); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if(currentUser == null) { startActivity(new Intent(this, MainActivity.class)); finish(); return; } TextView tvUid = findViewById(R.id.signedin_text_uid); TextView tvName = findViewById(R.id.signedin_text_user); tvUid.setText(currentUser.getUid()); tvName.setText(currentUser.getDisplayName()); Button btnSignout = findViewById(R.id.signedin_button_signout); btnSignout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AuthUI.getInstance() .signOut(SignedInActivity.this) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { startActivity( new Intent( SignedInActivity.this, MainActivity.class)); finish(); } else { // Apabila error } } }); } }); Button btnDelete = findViewById(R.id.signedin_button_delete); btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AuthUI.getInstance() .delete( SignedInActivity.this) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { startActivity( new Intent( SignedInActivity.this, MainActivity.class) ); finish(); } else { // Apabila error ... } } }) ; } }) ; } }
leffss/go-admin
cmd/var.go
<reponame>leffss/go-admin package cmd var ( password string mode string )
best08618/asylo
gcc-gcc-7_3_0-release/libgomp/testsuite/libgomp.oacc-c-c++-common/data-1.c
<reponame>best08618/asylo<filename>gcc-gcc-7_3_0-release/libgomp/testsuite/libgomp.oacc-c-c++-common/data-1.c /* { dg-do run } */ #include <stdlib.h> #include <openacc.h> int i; int is_mapped (void *p, size_t n) { #if ACC_MEM_SHARED return 1; #else return acc_is_present (p, n); #endif } int main(void) { int j; i = -1; j = -2; #pragma acc data copyin (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } if (i != 2 || j != 1) abort (); i = -1; j = -2; #pragma acc data copyout (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); #pragma acc parallel present (i, j) { i = 4; j = 2; } } if (i != 4 || j != 2) abort (); i = -1; j = -2; #pragma acc data create (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } if (i != 2 || j != 1) abort (); i = -1; j = -2; #pragma acc data present_or_copyin (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } if (i != 2 || j != 1) abort (); i = -1; j = -2; #pragma acc data present_or_copyout (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); #pragma acc parallel present (i, j) { i = 4; j = 2; } } if (i != 4 || j != 2) abort (); i = -1; j = -2; #pragma acc data present_or_copy (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } #if ACC_MEM_SHARED if (i != 2 || j != 1) abort (); #else if (i != -1 || j != -2) abort (); #endif i = -1; j = -2; #pragma acc data present_or_create (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } if (i != 2 || j != 1) abort (); i = -1; j = -2; #pragma acc data copyin (i, j) { #pragma acc data present (i, j) { if (!is_mapped (&i, sizeof (i)) || !is_mapped (&j, sizeof (j))) abort (); if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } } if (i != 2 || j != 1) abort (); i = -1; j = -2; #pragma acc data { #if !ACC_MEM_SHARED if (is_mapped (&i, sizeof (i)) || is_mapped (&j, sizeof (j))) abort (); #endif if (i != -1 || j != -2) abort (); i = 2; j = 1; if (i != 2 || j != 1) abort (); } if (i != 2 || j != 1) abort (); return 0; }
TigerBSD/FreeBSD-Custom-ThinkPad
FreeBSD/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp
<filename>FreeBSD/contrib/llvm/tools/lldb/source/Plugins/DynamicLoader/POSIX-DYLD/AuxVector.cpp //===-- AuxVector.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> // C++ Includes // Other libraries and framework includes #include "lldb/Core/DataBufferHeap.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Log.h" #include "lldb/Target/Process.h" #if defined(__linux__) || defined(__FreeBSD__) #include "Plugins/Process/elf-core/ProcessElfCore.h" #endif #include "AuxVector.h" using namespace lldb; using namespace lldb_private; static bool GetMaxU64(DataExtractor &data, lldb::offset_t *offset_ptr, uint64_t *value, unsigned int byte_size) { lldb::offset_t saved_offset = *offset_ptr; *value = data.GetMaxU64(offset_ptr, byte_size); return *offset_ptr != saved_offset; } static bool ParseAuxvEntry(DataExtractor &data, AuxVector::Entry &entry, lldb::offset_t *offset_ptr, unsigned int byte_size) { if (!GetMaxU64(data, offset_ptr, &entry.type, byte_size)) return false; if (!GetMaxU64(data, offset_ptr, &entry.value, byte_size)) return false; return true; } DataBufferSP AuxVector::GetAuxvData() { if (m_process) return m_process->GetAuxvData (); else return DataBufferSP (); } void AuxVector::ParseAuxv(DataExtractor &data) { const unsigned int byte_size = m_process->GetAddressByteSize(); lldb::offset_t offset = 0; for (;;) { Entry entry; if (!ParseAuxvEntry(data, entry, &offset, byte_size)) break; if (entry.type == AT_NULL) break; if (entry.type == AT_IGNORE) continue; m_auxv.push_back(entry); } } AuxVector::AuxVector(Process *process) : m_process(process) { DataExtractor data; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); data.SetData(GetAuxvData()); data.SetByteOrder(m_process->GetByteOrder()); data.SetAddressByteSize(m_process->GetAddressByteSize()); ParseAuxv(data); if (log) DumpToLog(log); } AuxVector::iterator AuxVector::FindEntry(EntryType type) const { for (iterator I = begin(); I != end(); ++I) { if (I->type == static_cast<uint64_t>(type)) return I; } return end(); } void AuxVector::DumpToLog(Log *log) const { if (!log) return; log->PutCString("AuxVector: "); for (iterator I = begin(); I != end(); ++I) { log->Printf(" %s [%" PRIu64 "]: %" PRIx64, GetEntryName(*I), I->type, I->value); } } const char * AuxVector::GetEntryName(EntryType type) { const char *name = "AT_???"; #define ENTRY_NAME(_type) _type: name = #_type switch (type) { case ENTRY_NAME(AT_NULL); break; case ENTRY_NAME(AT_IGNORE); break; case ENTRY_NAME(AT_EXECFD); break; case ENTRY_NAME(AT_PHDR); break; case ENTRY_NAME(AT_PHENT); break; case ENTRY_NAME(AT_PHNUM); break; case ENTRY_NAME(AT_PAGESZ); break; case ENTRY_NAME(AT_BASE); break; case ENTRY_NAME(AT_FLAGS); break; case ENTRY_NAME(AT_ENTRY); break; case ENTRY_NAME(AT_NOTELF); break; case ENTRY_NAME(AT_UID); break; case ENTRY_NAME(AT_EUID); break; case ENTRY_NAME(AT_GID); break; case ENTRY_NAME(AT_EGID); break; case ENTRY_NAME(AT_CLKTCK); break; case ENTRY_NAME(AT_PLATFORM); break; case ENTRY_NAME(AT_HWCAP); break; case ENTRY_NAME(AT_FPUCW); break; case ENTRY_NAME(AT_DCACHEBSIZE); break; case ENTRY_NAME(AT_ICACHEBSIZE); break; case ENTRY_NAME(AT_UCACHEBSIZE); break; case ENTRY_NAME(AT_IGNOREPPC); break; case ENTRY_NAME(AT_SECURE); break; case ENTRY_NAME(AT_BASE_PLATFORM); break; case ENTRY_NAME(AT_RANDOM); break; case ENTRY_NAME(AT_EXECFN); break; case ENTRY_NAME(AT_SYSINFO); break; case ENTRY_NAME(AT_SYSINFO_EHDR); break; case ENTRY_NAME(AT_L1I_CACHESHAPE); break; case ENTRY_NAME(AT_L1D_CACHESHAPE); break; case ENTRY_NAME(AT_L2_CACHESHAPE); break; case ENTRY_NAME(AT_L3_CACHESHAPE); break; } #undef ENTRY_NAME return name; }
cameronbraid/zephyr
kernel-core/src/main/java/io/zephyr/common/io/Checker.java
<gh_stars>10-100 package io.zephyr.common.io; @FunctionalInterface public interface Checker<T> { boolean check(T value); }
SmartElect/SmartElect
audit/tests/test_message_uuid.py
from uuid import uuid4 from django.conf import settings from register.tests.base import LibyaRapidTest from register.models import SMS class MessageUUID(LibyaRapidTest): def setUp(self): self.uuid = uuid4().hex self.conn = self.create_connection() def test_incoming_message(self): # all incoming messages should be accounted for in our DB self.receive("incoming", self.conn, fields={'external_id': self.uuid, 'to_addr': settings.REGISTRATION_SHORT_CODE}) # a SMS should be created in our SMS table sms = SMS.objects.order_by('creation_date')[0] # the uuid for the sms, should be the same as the one vumi used self.assertEqual(sms.uuid, self.uuid) def test_outgoing_message(self): # all outgoing messages should be accounted for in our DB self.send("outgoing", self.conn) sms = SMS.objects.order_by('creation_date')[0] self.assertEqual(1, len(self.outbound)) outgoing = self.outbound[0] # the uuid for the sms should be equal to the uuid from the outgoing msg self.assertEqual(sms.uuid, outgoing.id)
fossabot/goradd
pkg/page/control/repeater.go
<gh_stars>1-10 package control import ( "bytes" "context" "github.com/goradd/gengen/pkg/maps" "github.com/goradd/goradd/pkg/html" "github.com/goradd/goradd/pkg/log" "github.com/goradd/goradd/pkg/page" ) type RepeaterI interface { PagedControlI DrawItem(ctx context.Context, i int, data interface{}, buf *bytes.Buffer) (err error) SetItemHtmler(h RepeaterHtmler) RepeaterI } type Repeater struct { page.ControlBase PagedControl DataManager itemHtmler RepeaterHtmler itemHtmlerId string // only used for serialization } type RepeaterHtmler interface { RepeaterHtml(ctx context.Context, r RepeaterI, i int, data interface{}, buf *bytes.Buffer) error } // NewTable creates a new table func NewRepeater(parent page.ControlI, id string) *Repeater { r := &Repeater{} r.Self = r r.Init(parent, id) return r } // Init is an internal function that enables the object-oriented pattern of calling virtual functions used by the // goradd controls. func (r *Repeater) Init(parent page.ControlI, id string) { r.ControlBase.Init(parent, id) r.Tag = "div" } // this returns the RepeaterI interface for calling into "virtual" functions. This allows us to call functions defined // by a subclass. func (r *Repeater) this() RepeaterI { return r.Self.(RepeaterI) } // SetItemHtmler sets the htmler that provides the html for each item in the repeater. func (r *Repeater) SetItemHtmler(h RepeaterHtmler) RepeaterI { r.itemHtmler = h return r.this() } // DrawTag is called by the framework to draw the tag. The Repeater overrides this to call into the DataProvider // to load the table's data into memory just before drawing. The data will be unloaded after drawing. func (r *Repeater) DrawTag(ctx context.Context) string { log.FrameworkDebug("Drawing repeater tag") if r.HasDataProvider() { log.FrameworkDebug("Getting repeater data") r.this().LoadData(ctx, r.this()) defer r.ResetData() } return r.ControlBase.DrawTag(ctx) } // DrawingAttributes is an override to add attributes to the table, including not showing the table at all if there // is no data to show. This will hide header and footer cells and potentially the outline of the table when there is no // data in the table. func (r *Repeater) DrawingAttributes(ctx context.Context) html.Attributes { a := r.ControlBase.DrawingAttributes(ctx) a.SetDataAttribute("grctl", "repeater") return a } // DrawInnerHtml is an override to draw the individual items of the repeater. func (r *Repeater) DrawInnerHtml(ctx context.Context, buf *bytes.Buffer) (err error) { var this = r.this() // Get the sub class so we call into its hooks for drawing r.RangeData(func(index int, value interface{}) bool { err = this.DrawItem(ctx, index, value, buf) if err != nil { return false } return true }) if err != nil { return } return nil } func (r *Repeater) DrawItem(ctx context.Context, i int, data interface{}, buf *bytes.Buffer) (err error) { if r.itemHtmler != nil { if err = r.itemHtmler.RepeaterHtml(ctx, r, i, data, buf); err != nil { return } } return } // MarshalState is an internal function to save the state of the control func (r *Repeater) MarshalState(m maps.Setter) { r.PagedControl.MarshalState(m) } // UnmarshalState is an internal function to restore the state of the control func (r *Repeater) UnmarshalState(m maps.Loader) { r.PagedControl.UnmarshalState(m) } func (r *Repeater) Serialize(e page.Encoder) (err error) { if err = r.ControlBase.Serialize(e); err != nil { return } if err = r.PagedControl.Serialize(e); err != nil { return } if err = r.DataManager.Serialize(e); err != nil { return } // If itemHtmler is a control, we will just serialize the control's id, since the control will get // serialized elsewhere. Otherwise, we serialize the itemHtmler itself. var htmler interface{} = r.itemHtmler if ctrl, ok := r.itemHtmler.(page.ControlI); ok { htmler = ctrl.ID() } if err = e.Encode(&htmler); err != nil { return err } return } func (r *Repeater) Deserialize(dec page.Decoder) (err error) { if err = r.ControlBase.Deserialize(dec); err != nil { panic(err) } if err = r.PagedControl.Deserialize(dec); err != nil { panic(err) } if err = r.DataManager.Deserialize(dec); err != nil { panic(err) } var htmler interface{} if err = dec.Decode(&htmler); err != nil { panic(err) } if id,ok := htmler.(string); ok { r.itemHtmlerId = id } else { r.itemHtmler = htmler.(RepeaterHtmler) } return } func (r *Repeater) Restore() { r.ControlBase.Restore() if r.itemHtmlerId != "" { r.itemHtmler = r.Page().GetControl(r.itemHtmlerId).(RepeaterHtmler) } return } // PagedTableCreator creates a table that can be paged type RepeaterCreator struct { // ID is the control id ID string // ItemHtmler is the object that provides the html for each item ItemHtmler RepeaterHtmler // DataProvider is the data binder for the table. It can be either a control id or a DataBinder DataProvider DataBinder // DataProviderID is the control id of the data binder for the table. DataProviderID string // Data is the actual data for the table, and should be a slice of objects Data interface{} page.ControlOptions // PageSize is the number of rows to include in a page PageSize int // SaveState will cause the table to remember what page it was on SaveState bool } // Create is called by the framework to create a new control from the Creator. You // do not normally need to call this. func (c RepeaterCreator) Create(ctx context.Context, parent page.ControlI) page.ControlI { ctrl := NewRepeater(parent, c.ID) c.Init(ctx, ctrl) return ctrl } func (c RepeaterCreator) Init(ctx context.Context, ctrl RepeaterI) { if c.ItemHtmler != nil { ctrl.SetItemHtmler(c.ItemHtmler) } if c.DataProvider != nil { ctrl.SetDataProvider(c.DataProvider) } else if c.DataProviderID != "" { provider := ctrl.Page().GetControl(c.DataProviderID).(DataBinder) ctrl.SetDataProvider(provider) } if c.Data != nil { ctrl.SetData(c.Data) } ctrl.ApplyOptions(ctx, c.ControlOptions) if c.PageSize != 0 { ctrl.SetPageSize(c.PageSize) } if c.SaveState { ctrl.SaveState(ctx, true) } } // GetRepeater is a convenience method to return the repeater with the given id from the page. func GetRepeater(c page.ControlI, id string) *Repeater { return c.Page().GetControl(id).(*Repeater) } func init() { page.RegisterControl(&Repeater{}) }
ncl427/openair-cn
SRC/NAS/API/NETWORK/nas_message_xml.h
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ /*! \file nas_message_xml.h \brief \author <NAME> \date 2016 \email: <EMAIL> */ #ifndef FILE_NAS_MESSAGE_XML_SEEN #define FILE_NAS_MESSAGE_XML_SEEN #define SECURITY_PROTECTED_NAS_MESSAGE_IE_XML_STR "security_protected_nas_message" #define PLAIN_NAS_MESSAGE_IE_XML_STR "plain_nas_message" bool nas_message_plain_from_xml ( xmlDocPtr xml_doc, xmlXPathContextPtr xpath_ctx, nas_message_plain_t * const nas_message); bool nas_message_protected_from_xml ( xmlDocPtr xml_doc, xmlXPathContextPtr xpath_ctx, nas_message_t * const nas_message); bool nas_pdu_from_xml ( xmlDocPtr xml_doc, xmlXPathContextPtr xpath_ctx, bstring const *bnas_pdu); void nas_pdu_to_xml (bstring bnas_pdu, xmlTextWriterPtr writer); #endif /* FILE_NAS_MESSAGE_XML_SEEN*/
johnapost/overwatch-league-fantasy
src/app/shared/hasErrors.js
// @flow export default (fieldsError: Object) => Object.keys(fieldsError).some(field => fieldsError[field]);
CrankySupertoon/VoidCraft-Community-Edition
src/main/java/tamaized/dalquor/common/vademecum/IVadeMecumCrafting.java
<reponame>CrankySupertoon/VoidCraft-Community-Edition<filename>src/main/java/tamaized/dalquor/common/vademecum/IVadeMecumCrafting.java package tamaized.dalquor.common.vademecum; import net.minecraft.client.gui.FontRenderer; import tamaized.dalquor.client.gui.VadeMecumGUI; public interface IVadeMecumCrafting { public void render(VadeMecumGUI gui, FontRenderer render, int x, int y, int mx, int my); }
iagerogiannis/numerical-analysis
numerical_analysis/splines/__init__.py
from .bezier import Bezier from .composite_bezier import CompositeBezier, CompositeQuadraticBezier, CompositeCubicBezier
Versal/cdnjs
ajax/libs/rimg/0.3.5/rimg.js
<filename>ajax/libs/rimg/0.3.5/rimg.js 'use strict'; !function(){ if(!console){ console = { log: function(){}, error: function(){} } } var Rimg = function() { var hidden = { status : 'init', observer : null, breakpoints : [], resizeWait: null, resizeDimensions: '', disableIntrospection: false }; function parseBreakpoints(value){ //custom: (once) -small 640w 1x, -retina-small 640w 2x, -medium 1280w 1x, -retina-medium 1280w 2x //custom: (per image) data-src="image.jpg" if(typeof value === 'string'){ var breakpoints = value.split(','); if(breakpoints.length === 0){ //invalid hidden.status = 'error'; console.error('Rimg: your breakpoint-definition '+ value +' is invalid, check the documentation.'); return null; } var definition = []; var i = 0; var il = breakpoints.length; while(i<il){ var bp = breakpoints[i]; var bpDefinition = { src: [], width: -1, height: -1, pixelRatio: [], getSrc: function(value){ var ratios = this.pixelRatio.length; if(ratios === 0){ hidden.status = 'error'; console.error('Rimg: missing a pixelRatio definition, check the documentation.'); return ''; }else if(ratios === 1){ return this.src[0]; }else if(ratios === 2){ if(value <= 1){ return this.src[0]; }else{ return this.src[1]; } }else{ //determine which pixelRatio matches most closely with current device pixel ratio. var s = 0; var sl = this.pixelRatio.length; while(s<sl){ //possible that pixelRatio is 1.5 or 2.25 if(value == this.pixelRatio[s] || Math.round(value) == this.pixelRatio[s]){ return this.src[s]; } s++; } //use last reference return this.src[ratios-1]; } } }; var parts = bp.split(' '); var p = 0; var pl = parts.length; while(p<pl){ var part = parts[p]; if(part.replace(' ','') === ''){ //ignore, empty = typo }else{ if(part.match(/^[0-9]{0,4}w/gi) != null){ bpDefinition.width = Number(part.substr(0,part.length-1)); }else if(part.match(/^[0-9]{0,4}h/gi) != null){ bpDefinition.height = Number(part.substr(0,part.length-1)); }else if(part.match(/[0-9]{1}x/gi) != null){ bpDefinition.pixelRatio.push(Number(part.substr(0,part.length-1))); }else{ bpDefinition.src.push(part); } } p++; } //check if already defined (pixelRatio) var d = 0; var dl = definition.length; var found = false; while(d<dl){ var def = definition[d]; if((def.width === bpDefinition.width && def.width != -1) || (def.height === bpDefinition.height && def.height != -1)){ //a match def.pixelRatio.push(bpDefinition.pixelRatio[0]); def.src.push(bpDefinition.src[0]); found = true; break; } d++; } if(!found){ //new breakpoint definition definition.push(bpDefinition); } i++; } if(definition.length > 0){ return definition; }else{ hidden.status = 'error'; console.error('Rimg: your breakpoint-definition misses valid breakpoints, check the documentation.'); return null; } }else{ //invalid hidden.status = 'error'; console.error('Rimg: your breakpoint-definition is not a String, check the documentation.'); return null; } } //discover initial settings if(typeof RimgBreakpoint !== 'undefined'){ //validate var bpts = parseBreakpoints(RimgBreakpoint); if(bpts != null){ hidden.breakpoints = bpts; } //TODO put on window also? //clean reference RimgBreakpoint = undefined; }else{ console.log('(remark) Rimg: no breakpoints defined, check the documentation.'); } function event(type,evt,func,target){ //add/remote event listeners if(target === undefined){ target = document; } if(evt === 'resize'){ target = window; } if(type == 'add'){ target.addEventListener(evt,func,false); }else{ target.removeEventListener(evt,func,false); } } function adjust(value){ //change src property when appropriate var ratio = window.devicePixelRatio || 1; var data = value.getAttribute('data-src'); if(data != null){ //only adjust images with data-src property var file = data.substr(0,data.lastIndexOf('.')); var extension = data.substr(data.lastIndexOf('.')); var size = {x:value.width,y:value.height}; //firefox presents width/height with 0, so check getComputedStyle if necessary: if(value.width == 0){ size.x = window.getComputedStyle(value,null).maxWidth; size.x = size.x.replace('px',''); size.x = Number(size.x); } if(value.height == 0){ size.y = window.getComputedStyle(value,null).maxHeight; size.y = size.y.replace('px',''); size.y = Number(size.y); } var i = 0; var il = hidden.breakpoints.length; var breakpoint; while(i<il){ var bp = hidden.breakpoints[i]; var wd = size.x; if(size.x < size.y){ wd = size.y; } if(wd <= bp.width){ breakpoint = bp; break; } i++; } if(breakpoint === undefined){ //use latest breakpoint = hidden.breakpoints[hidden.breakpoints.length-1]; } if(value.getAttribute('src') != file+breakpoint.getSrc(ratio)+extension){ //set the appropriate version of the image value.setAttribute('src',file+breakpoint.getSrc(ratio)+extension); } } } function inspect(value){ //check node itself if it is an image or has children if(value.nodeName.toLowerCase() === 'img'){ adjust(value); }else{ //walk through all node children until you find img files var i = 0; var il = value.children.length; while(i<il){ var item = value.children[i]; inspect(item); i++; } } } function resize(){ //window is resized, execute checkup, if necessary clearInterval(hidden.resizeWait); //execute only with different window dimensions (on mobile executed twice!) var nw = window.innerWidth+'x'+window.innerHeight; if(hidden.resizeDimensions !== nw){ hidden.resizeDimensions = nw; this.execute(document); } } function nodeInserted(e){ this.execute(e.target); } return { version: '0.3.5', execute: function(target){ //only possible when DOM is loaded and no errors appeared if(hidden.status === 'error'){ console.error('Rimg.execute(): error-status so no actions can be executed, check your code.'); return; }else if(target === undefined){ console.error('Rimg.execute(): undefined value, check your code to add a valid DOM element to this function.'); return; } if(target.nodeName === '#document'){ if(target.childNodes.length > 1){ //use html node inspect(target.childNodes[1].children[1]); }else{ console.error('Rimg.execute(): not a valid DOM representation, check your code.'); } }else{ if(target != undefined && target.nodeName != undefined && target.nodeName.toLowerCase() === 'img'){ //direct reference inspect(target); }else if(target[0] != undefined && target[0].nodeName.toLowerCase() === 'img'){ //child reference (after add) inspect(target[0]); }else{ //no <img> element found } } }, configure: function(value){ var breakpoints = parseBreakpoints(value); if(breakpoints != null){ hidden.breakpoints = breakpoints; } if(hidden.status === 'ready' && !hidden.disableIntrospection){ //if DOM loaded, execute right away this.execute(document); } }, resized: function(e){ if(hidden.status != 'ready'){ //not available anymore return; } //cleanup if(hidden.resizeWait != null){ clearInterval(hidden.resizeWait); } //wait 100ms to ensure performant and not a blocking script execution hidden.resizeWait = setInterval(resize.bind(this),100); }, loaded: function(e){ if(hidden.status != 'progress'){ //not available anymore return; } //cleanup listener event('remove','DOMContentLoaded',this.loaded); //initial DOM checkup if(!hidden.disableIntrospection){ // DOM content loaded if (hidden.observer === null) { //check the whole page before any changes happen this.execute(e.target); }else{ hidden.observer.observe(document.body, { attributes: true, childList: true, characterData: true, subtree: true, attributeFilter: ['data-src'] }); //check full DOM this.execute(document); } //listen for browser resize event('add','resize',this.resized.bind(this)); } hidden.status = 'ready'; }, disableIntrospection: function(){ hidden.disableIntrospection = true; //remove mutation listeners if(hidden.observer){ hidden.observer.disconnect(); }else{ event('remove','DOMNodeInserted',nodeInserted); } }, initialize: function(){ if(hidden.status != 'init'){ if(hidden.status != 'error'){ console.error('Rimg.initialize(): Already initialized. No forced initialization supported, check your code.'); } return; } //listen for DOM & change events var base = this; var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; if (MutationObserver === undefined) { event('add','DOMAttrModified',function(e){ //DOM attribute modified, not supported in webkit //TODO Safari 5.0+ MutationObserver support, Chrome 18 }); //TODO issues with IE9 - http://help.dottoro.com/ljmcxjla.php event('add','DOMNodeInserted',nodeInserted.bind(base)); event('add','DOMSubtreeModified',function(e){ //TODO nothing? //console.debug('Rimg:','DOM subtree modified',e.target); }); }else{ hidden.observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if(mutation.addedNodes.length > 0){ base.execute(mutation.addedNodes); }else if(mutation.attributeName === 'data-src'){ base.execute(mutation.target); } }); }); } hidden.status = 'progress'; // wait until DOM is loaded event('add','DOMContentLoaded',this.loaded.bind(this)); } }; }; // browser window.Rimg = Object.create(Rimg()); // start listening window.Rimg.initialize(); }();
tonko2/AtCoder
abc/abc249/b/main.py
<filename>abc/abc249/b/main.py import sys import math from collections import defaultdict, deque sys.setrecursionlimit(10 ** 6) stdin = sys.stdin INF = float('inf') ni = lambda: int(ns()) na = lambda: list(map(int, stdin.readline().split())) ns = lambda: stdin.readline().strip() S = ns() alpha = set() lower_flag = False for i, c in enumerate(S.lower()): if S[i] == c: lower_flag = True upper_flag = False for i, c in enumerate(S.upper()): if S[i] == c: upper_flag = True for i, c in enumerate(S): alpha.add(c) if len(alpha) != len(S) or lower_flag == False or upper_flag == False: print("No") else: print("Yes")
gtorvald/gauge3panel
node_modules/@iconscout/react-unicons/icons/uil-money-withdraw.js
<reponame>gtorvald/gauge3panel import React from 'react'; import PropTypes from 'prop-types'; const UilMoneyWithdraw = (props) => { const { color, size, ...otherProps } = props return React.createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: color, ...otherProps }, React.createElement('path', { d: 'M12,12a3,3,0,1,0,3,3A3,3,0,0,0,12,12Zm0,4a1,1,0,1,1,1-1A1,1,0,0,1,12,16Zm-.71-6.29a1,1,0,0,0,.33.21.94.94,0,0,0,.76,0,1,1,0,0,0,.33-.21L15,7.46A1,1,0,1,0,13.54,6L13,6.59V3a1,1,0,0,0-2,0V6.59L10.46,6A1,1,0,0,0,9,7.46ZM19,15a1,1,0,1,0-1,1A1,1,0,0,0,19,15Zm1-7H17a1,1,0,0,0,0,2h3a1,1,0,0,1,1,1v8a1,1,0,0,1-1,1H4a1,1,0,0,1-1-1V11a1,1,0,0,1,1-1H7A1,1,0,0,0,7,8H4a3,3,0,0,0-3,3v8a3,3,0,0,0,3,3H20a3,3,0,0,0,3-3V11A3,3,0,0,0,20,8ZM5,15a1,1,0,1,0,1-1A1,1,0,0,0,5,15Z' })); }; UilMoneyWithdraw.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; UilMoneyWithdraw.defaultProps = { color: 'currentColor', size: '24', }; export default UilMoneyWithdraw;
onnohaldar/istd-ld-voorbeelden
pub-examples/iWmo_Jw_Eb_Splits/data/view_28315_data.js
var viewData = {"id":28315,"isExpandedObject":false}; var objectRelations = { "28315" : [{"via": "is geassocieerd met","to": ["28314"]}] }; var objectData = { "28315" : { "id":28315, "typeIconPath":"data/icons/UML/UML_ClassDiagram.png", "data" : [ { "lang":"nl", "name":"WMO315", "type":"Klassendiagram", "categories":[] } ] } , "28314" : { "id":28314, "typeIconPath":"data/icons/ArchiMate/ApplicationDataObject.png", "data" : [ { "lang":"nl", "name":"WMO315", "type":"Dataobject", "categories":[{"type":"documentation","title":"documentatie","content":{"type":"rtf","value":"<span style=\" font-size: 9pt;\">Voor meer informatie over het bericht, klik hieronder bij &quot;Relaties&quot; op &quot;WMO315&quot;.&nbsp;<p style=\"margin-top: 3pt;\"></span>"}}] } ] } }; var viewReferences = {"39727":27964,"39695":28387,"39697":29618,"39699":29997,"39719":28031,"39722":30200,"39725":28222}; var objectReferences = { "39625" : 27936 , "39639" : 28761 , "39653" : 28637 , "39659" : 37118 , "39645" : 37115 , "39651" : 29258 , "39657" : 37117 , "39649" : 28822 , "39655" : 37116 , "39643" : 28445 , "39647" : 28392 , "39641" : 28087 , "39661" : 32051 , "39669" : 32057 , "39663" : 32055 , "39665" : 29086 , "39667" : 32062 , "39673" : 29679 , "39671" : 29754 , "39675" : 32060 , "39627" : 37178 , "39635" : 37121 , "39629" : 37119 , "39637" : 37123 , "39633" : 37120 , "39631" : 29271 , "39679" : 37221 , "39677" : 37223 , "39681" : 37222 , "39685" : 39685 , "39727" : 27964 , "39695" : 28387 , "39697" : 29618 , "39699" : 29997 , "39719" : 28031 , "39722" : 30200 , "39725" : 28222 , "39683" : 39683 , "39763" : 39763 , "39769" : 39769 , "39771" : 39771 , "39765" : 39765 , "39767" : 39767 }; var viewpointsData = [ {"id":"viewpoint56742","name":"Bericht details view","presentationType":"FmtLabelView"} ]; var vp_legends = { "viewpoint56742": { "labels" : new Array(), "content" : new Array() } }; vp_legends.viewpoint56742.labels[0] = "Labelview"; vp_legends.viewpoint56742.content[0] = new Array(); vp_legends.viewpoint56742.content[0][0] = {value1: "1) ", value2: "Getoond worden informatie over het bericht en de regels die op dit niveau gekoppeld zijn"};
dyna-mis/Hilabeling
src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp
<reponame>dyna-mis/Hilabeling /*************************************************************************** qgseditorwidgetautoconf.cpp --------------------- begin : July 2016 copyright : (C) 2016 by <NAME> email : <EMAIL>.<EMAIL>cchi at camptocamp.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 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgseditorwidgetautoconf.h" #include "qgseditorwidgetregistry.h" #include "qgsvectordataprovider.h" #include "qgsgui.h" /** * \ingroup gui * Widget auto conf plugin that guesses what widget type to use in function of what the widgets support. * * \note not available in Python bindings * \since QGIS 3.0 */ class FromFactoriesPlugin: public QgsEditorWidgetAutoConfPlugin { public: QgsEditorWidgetSetup editorWidgetSetup( const QgsVectorLayer *vl, const QString &fieldName, int &score ) const override { int bestScore = 0; QString bestType; const QMap<QString, QgsEditorWidgetFactory *> factories = QgsGui::editorWidgetRegistry()->factories(); for ( QMap<QString, QgsEditorWidgetFactory *>::const_iterator i = factories.begin(); i != factories.end(); ++i ) { const int index = vl->fields().lookupField( fieldName ); if ( index >= 0 ) { const int score = i.value()->fieldScore( vl, index ); if ( score > bestScore ) { bestType = i.key(); bestScore = score; } } } if ( bestScore > 0 ) { score = 10; return QgsEditorWidgetSetup( bestType, QVariantMap() ); } return QgsEditorWidgetSetup(); } }; /** * \ingroup gui * Widget auto conf plugin that reads the widget setup to use from what the data provider says. * * \note not available in Python bindings * \since QGIS 3.0 */ class FromDbTablePlugin: public QgsEditorWidgetAutoConfPlugin { public: QgsEditorWidgetSetup editorWidgetSetup( const QgsVectorLayer *vl, const QString &fieldName, int &score ) const override { QgsField field = vl->fields().field( fieldName ); if ( !field.editorWidgetSetup().isNull() ) { score = 20; return field.editorWidgetSetup(); } else { return QgsEditorWidgetSetup(); } } }; ///@cond PRIVATE QgsEditorWidgetAutoConf::QgsEditorWidgetAutoConf() { registerPlugin( new FromFactoriesPlugin() ); registerPlugin( new FromDbTablePlugin() ); } QgsEditorWidgetSetup QgsEditorWidgetAutoConf::editorWidgetSetup( const QgsVectorLayer *vl, const QString &fieldName ) const { QgsEditorWidgetSetup result( QStringLiteral( "TextEdit" ), QVariantMap() ); int fieldIndex = vl->fields().indexFromName( fieldName ); if ( fieldIndex >= 0 ) { if ( vl->fields().fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) { // important check - for provider fields, we CANNOT use auto configured widgets if the field // uses a default value clause - otherwise the widget will obliterate the default value clause // (e.g., by trying to convert it to a number/date/etc). Instead we have to use a text edit // widget so that the clause remains intact int providerOrigin = vl->fields().fieldOriginIndex( fieldIndex ); if ( !vl->dataProvider()->defaultValueClause( providerOrigin ).isEmpty() ) return result; } int bestScore = 0; for ( const std::shared_ptr<QgsEditorWidgetAutoConfPlugin> &cur : mPlugins ) { int score = 0; const QgsEditorWidgetSetup curResult = cur->editorWidgetSetup( vl, fieldName, score ); if ( score > bestScore ) { result = curResult; bestScore = score; } } } return result; } void QgsEditorWidgetAutoConf::registerPlugin( QgsEditorWidgetAutoConfPlugin *plugin ) { mPlugins.append( std::shared_ptr<QgsEditorWidgetAutoConfPlugin>( plugin ) ); } ///@endcond
rob-duewer/caf-common
util-naming/src/main/test/com/hpe/caf/naming/NameTest.java
<gh_stars>0 /* * Copyright 2015-2017 Hewlett Packard Enterprise Development LP. * * 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.hpe.caf.naming; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Iterator; import java.util.NoSuchElementException; public class NameTest { @Test public void testBasicName() { String input = "a/b/c"; Name name = new Name(input); Assert.assertEquals(input, name.toString()); Assert.assertEquals(3, name.size()); } @Test public void testTrailingSlash() { String input = "a/b/c"; Name name = new Name("/" + input + "/"); Assert.assertEquals(input, name.toString()); Assert.assertEquals(3, name.size()); } @Test public void testGetIndex() { String input = "/a/b/c"; Name name = new Name(input); Assert.assertEquals("a", name.getIndex(0)); Assert.assertEquals("b", name.getIndex(1)); Assert.assertEquals("c", name.getIndex(2)); } @Test(expected = IllegalArgumentException.class) public void testGetIndexLowerBound() { String input = "/a/b/c"; Name name = new Name(input); name.getIndex(-1); } @Test(expected = IllegalArgumentException.class) public void testGetIndexUpperBound() { String input = "/a/b/c"; Name name = new Name(input); name.getIndex(3); } @Test public void testIterator() { String input = "/a/b/c"; Name name = new Name(input); Iterator<String> it = name.iterator(); Assert.assertTrue(it.hasNext()); Assert.assertEquals("a", it.next()); Assert.assertTrue(it.hasNext()); Assert.assertEquals("b", it.next()); Assert.assertTrue(it.hasNext()); Assert.assertEquals("c", it.next()); Assert.assertFalse(it.hasNext()); } @Test(expected = NoSuchElementException.class) public void testIteratorBounds() { String input = "/a/b/c"; Name name = new Name(input); Iterator<String> it = name.iterator(); it.next(); it.next(); it.next(); it.next(); } @Test public void testGetPrefix() { String input = "/a/b/c"; Name name = new Name(input); Name subName = name.getPrefix(2); Assert.assertEquals(2, subName.size()); Assert.assertEquals("a/b", subName.toString()); } @Test(expected = IllegalArgumentException.class) public void getGetPrefixLowerBound() { String input = "/a/b/c"; Name name = new Name(input); name.getPrefix(-1); } @Test(expected = IllegalArgumentException.class) public void getGetPrefixUpperBound() { String input = "/a/b/c"; Name name = new Name(input); name.getPrefix(4); } @Test public void testEquals() { String input = "/a/b/c"; Name name = new Name(input); Name otherName = new Name(input); Assert.assertTrue(name.equals(otherName)); } }
SQuAT-Team/SQuAT-docker
squat.modifiability/src/main/java/io/github/squat_team/modifiability/kamp/KAMPPCMBot.java
package io.github.squat_team.modifiability.kamp; import java.util.ArrayList; import java.util.List; import edu.squat.transformations.ArchitecturalVersion; import io.github.squat_team.AbstractPCMBot; import io.github.squat_team.model.PCMArchitectureInstance; import io.github.squat_team.model.PCMScenarioResult; import io.github.squat_team.modifiability.ModifiabilityPCMScenario; import io.github.squat_team.util.PCMHelper; /** * A implementation of a modifiability bot. The analysis is based on KAMP and * the search for alternatives is based on Henshin transformations. * <p> * Only a minimal result is returned. This means that the current implementation * does not return all information specified by the SQuAT Bot interface. * However, it is enough for the negotiator to work * </p> */ public class KAMPPCMBot extends AbstractPCMBot { private EvaluationType evaluationType = EvaluationType.COMPLEXITY; public KAMPPCMBot(ModifiabilityPCMScenario scenario) { super(scenario); } public EvaluationType getEvaluationType() { return evaluationType; } public void setEvaluationType(EvaluationType evaluationType) { this.evaluationType = evaluationType; } @Override public PCMScenarioResult analyze(PCMArchitectureInstance currentArchitecture) { // Run the propagation and create the result PCMScenarioResult scenarioResult = new PCMScenarioResult(this); // Register the initial architecture // There is no tactic, because this is just an evaluation scenarioResult.setAppliedTactic(null); // The resulting architecture is just the original one, because we did not make // changes scenarioResult.setResultingArchitecture(currentArchitecture); // Run the analyzer KAMPAnalyzer analyzer = new KAMPAnalyzer((ModifiabilityPCMScenario) scenario, evaluationType); scenarioResult.setResult(analyzer.analyze(currentArchitecture)); if (KAMPPCMBotTriggers.DEBUG) { java.lang.System.out .println("The goal of scenario: " + scenario.getExpectedResult().getResponse().toString()); java.lang.System.out.println("The evaluation type is: " + evaluationType); String satisfaction_alt1; try { satisfaction_alt1 = scenarioResult.isSatisfied() >= 0 ? "SATISFIED" : "NOT SATISFIED"; java.lang.System.out.println("The scenario satisfaction with " + currentArchitecture.getName() + " is: " + satisfaction_alt1); } catch (Exception e) { // The debug print out should not let the bot fail } } return scenarioResult; } @Override public List<PCMScenarioResult> searchForAlternatives(PCMArchitectureInstance currentArchitecture) { ArchitecturalVersion architecture = PCMHelper.createArchitecture(currentArchitecture); List<ArchitecturalVersion> transformationResults = (new ModifiabilityTransformationsFactory()) .runModifiabilityTransformationsInAModel(architecture); List<PCMScenarioResult> results = new ArrayList<>(); for (ArchitecturalVersion transformationResult : transformationResults) { results.add(analyze(PCMHelper.createArchitecture(transformationResult))); } return results; } }
jessamynsmith/django-opendebates
opendebates/tests/test_headlines.py
from functools import partial from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from django.test import TestCase import mock from ..models import Submission from .factories import SubmissionFactory, UserFactory, VoterFactory, SiteFactory, DebateFactory # Force the reverse() used here in the tests to always use the full # urlconf, despite whatever machinations have taken place due to the # DebateMiddleware. old_reverse = reverse reverse = partial(old_reverse, urlconf='opendebates.urls') class HeadlineTest(TestCase): def setUp(self): self.site = SiteFactory() self.debate = DebateFactory(site=self.site) self.submission = SubmissionFactory() def tearDown(self): Site.objects.clear_cache() def test_headline_in_recent_events(self): mock_cache = mock.MagicMock() mock_cache.get.return_value = [ self.submission ] with mock.patch('opendebates.views.cache', new=mock_cache): rsp = self.client.get(reverse('recent_activity', kwargs={'prefix': self.debate.prefix})) html = rsp.content.decode('UTF-8') self.assertIn(self.submission.headline, html) def test_headline_contributes_to_search(self): rsp = self.client.get( reverse('search_ideas', kwargs={'prefix': self.debate.prefix}) + '?q=%s' % self.submission.headline) html = rsp.content.decode('UTF-8') self.assertIn(self.submission.get_absolute_url(), html) def test_headline_contributes_to_merge(self): submission2 = SubmissionFactory() user = UserFactory(password='<PASSWORD>', is_staff=True, is_superuser=True) VoterFactory(user=user, email=user.email) assert self.client.login(username=user.username, password='<PASSWORD>') merge_url = reverse('moderation_merge', kwargs={'prefix': self.debate.prefix}) self.client.post(merge_url, data={ "action": "merge", "to_remove": self.submission.id, "duplicate_of": submission2.id, }) remaining = Submission.objects.get(id=submission2.id) self.assertIn(self.submission.headline, remaining.keywords)
Master-LC/Java-Utils
src/main/java/com/hz/tgb/crypto/sign/SignatureUtil.java
<filename>src/main/java/com/hz/tgb/crypto/sign/SignatureUtil.java package com.hz.tgb.crypto.sign; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.lang.reflect.Field; import java.util.*; import com.hz.tgb.crypto.MD5Util; import com.hz.tgb.reflect.ReflectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HTTP接口签名工具类 * * Created by hezhao on 2018-07-02 19:41 */ public class SignatureUtil { private static final Logger logger = LoggerFactory.getLogger(SignatureUtil.class); private static final String SIGN_STR = "sign"; public static List<String> getBaseString(Object target, Set<String> exclusiveField) { Preconditions.checkNotNull(target); Map<String, Field> fields = ReflectUtils.getBeanPropertyFields(target.getClass()); LinkedList<String> list = Lists.newLinkedList(); try { if (fields != null) { for (Map.Entry<String, Field> each : fields.entrySet()) { String fieldName = (String)each.getKey(); if ((exclusiveField == null) || (!exclusiveField.contains(fieldName))) { Field field = (Field)each.getValue(); field.setAccessible(true); Object fieldValue = field.get(target); if ((fieldValue != null) && (!"".equals(fieldValue))) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(fieldName); stringBuilder.append("="); stringBuilder.append(fieldValue); stringBuilder.append("&"); list.add(stringBuilder.toString()); } } } } } catch (IllegalArgumentException e) { logger.error("get source list IllegalArgumentException error.", e); } catch (IllegalAccessException e) { logger.error("get source list IllegalAccessException error.", e); } return list; } public static String getKeySortedBaseString(Object target, Set<String> exclusiveField, Comparator<String> comparator) { Preconditions.checkNotNull(target); Preconditions.checkNotNull(comparator); Map<String, Field> fields = ReflectUtils.getBeanPropertyFields(target.getClass()); TreeMap<String, Object> map = Maps.newTreeMap(comparator); try { if (fields != null) { for (Map.Entry<String, Field> each : fields.entrySet()) { String fieldName = (String)each.getKey(); if ((exclusiveField == null) || (!exclusiveField.contains(fieldName))) { Field field = (Field)each.getValue(); field.setAccessible(true); Object fieldValue = field.get(target); if ((fieldValue != null) && (!"".equals(fieldValue))) { map.put(fieldName, fieldValue); } } } } } catch (IllegalArgumentException e) { logger.error("get source list IllegalArgumentException error.", e); } catch (IllegalAccessException e) { logger.error("get source list IllegalAccessException error.", e); } StringBuilder sb = new StringBuilder(128); if (!map.isEmpty()) { for (Map.Entry<String, Object> each : map.entrySet()) { sb.append((String)each.getKey()); sb.append("="); sb.append(each.getValue()); sb.append("&"); } } return sb.toString(); } public static String getSortedBaseString(Object target, Set<String> exclusiveField) { List<String> baseString = getBaseString(target, exclusiveField); if (baseString != null) { int size = baseString.size(); String[] arrayToSort = (String[])baseString.toArray(new String[size]); // 按自然排序 Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER); StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { sb.append(arrayToSort[i]); } String result = sb.toString(); return result; } return null; } public static String getSortedBaseString(Object target, String signFieldName) { return getSortedBaseString(target, Sets.newHashSet(new String[] { signFieldName })); } public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("name", "jack"); map.put("age", 22); String APPSECRET = "123456"; //签名 String baseString = SignatureUtil.getSortedBaseString(map, "sign"); baseString += "key=" + APPSECRET; String md5 = MD5Util.md5(baseString); map.put("sign", md5); System.out.println(md5); } }
AccelByte/accelbyte-services-api
platform-sdk/pkg/platformclient/i_a_p/delete_i_a_p_item_config_responses.go
<gh_stars>1-10 // Code generated by go-swagger; DO NOT EDIT. package i_a_p // 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/ioutil" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" ) // DeleteIAPItemConfigReader is a Reader for the DeleteIAPItemConfig structure. type DeleteIAPItemConfigReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *DeleteIAPItemConfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 204: result := NewDeleteIAPItemConfigNoContent() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: data, err := ioutil.ReadAll(response.Body()) if err != nil { return nil, err } return nil, fmt.Errorf("Requested DELETE /admin/namespaces/{namespace}/iap/config/item returns an error %d: %s", response.Code(), string(data)) } } // NewDeleteIAPItemConfigNoContent creates a DeleteIAPItemConfigNoContent with default headers values func NewDeleteIAPItemConfigNoContent() *DeleteIAPItemConfigNoContent { return &DeleteIAPItemConfigNoContent{} } /*DeleteIAPItemConfigNoContent handles this case with default header values. Delete successfully */ type DeleteIAPItemConfigNoContent struct { } func (o *DeleteIAPItemConfigNoContent) Error() string { return fmt.Sprintf("[DELETE /admin/namespaces/{namespace}/iap/config/item][%d] deleteIAPItemConfigNoContent ", 204) } func (o *DeleteIAPItemConfigNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil }
royyau41/presentation
app/lib/getData.js
<gh_stars>0 var db=require('db').db; exports.propGroup={ getLastPropgroupNo:function(){ var $sql='select max(number) number from propgroup where deletedate =0 '; var res=runSql($sql); return res[0].number||0; } }; exports.property={ getList:function(propgroup,specClause,orderBy){ if (typeof orderBy=='object'){} if (!orderBy)orderBy=''; var $sql='select p.* from property as p where PROPGROUPNO='+propgroup+ ' '+orderBy; return runSql($sql); }, getFieldList:function(type,lang){ var field={}; var lang= Ti.App.Properties.getString('lang','c'); switch(type.toLowerCase()){ case 'propdetail': case 'propertydetail': var field={ 'narea' :{field:'netarea'}, 'garea' :{field:'grossarea'}, 'price' :{field:'price',fieldType:'number',base:1000000,tool:'mortagageTool'}, 'rent' :{field:'rent',fieldType:'number'}, 'possession':{field:lang+'_possession'}, 'availability':{field:lang+'_availability'}, 'floor' :{field:'c_floor'}, 'decoration':{field:'decoration'}, 'carpark' :{field:'carparks', returnType:'boolean'}, 'remarks' :{field:lang+'_remarks',width:'100%'} }; break; case 'propsearch': case 'propertysearch': var field={ //'district' :{field:lang+'_district'}, 'narea' :{field:'netarea',fieldType:'number'}, 'price' :{field:'price',fieldType:'number',base:1000000}, 'garea' :{field:'grossarea',fieldType:'number'}, 'rent' :{field:'rent',fieldType:'number'}, 'remarks' :{field:lang+'_remarks',width:'100%'} }; break; }; return field; }, getDetail:function(number,propgroup){ var $sql="select *,"+ "availability as c_availability,"+ "englishavail as e_availability,"+ "(case possession when 1 then '交吉' when 2 then '連約' else '其他' end) as c_possession, "+ "(case possession when 1 then 'Vacant' when 2 then 'TA' else 'Others' end) as e_possession "+ "from property "+ "where number="+number+" and propgroupno="+propgroup; var res=runSql($sql); return res[0]; } ,getDetailById:function(id){ var $sql="select *,"+ "availability as c_availability,"+ "englishavail as e_availability,"+ "(case possession when 1 then '交吉' when 2 then '連約' else '其他' end) as c_possession, "+ "(case possession when 1 then 'Vacant' when 2 then 'TA' else 'Others' end) as e_possession "+ "from property "+ "where id="+id+""; var res=runSql($sql); return res[0]; } ,getImage:function(numberXML,propgroup){ var $sql='select attachment as image from propertyfile where '+ 'propertyno=(select propertyno from property where number = '+numberXML+' and propgroupno='+propgroup+')'+ 'and attachment is not null '+ 'and propgroupno = '+propgroup; return runSql($sql); } ,updateRead:function(clause){ if (clause){ var $sql='update property set read=1 where '+clause; console.log($sql); return runSql($sql); } else return false; } }; exports.trans={ getList:function(obj){ $where=''; for (var k in obj){ if (obj[k]!=''){ if ($where !=''){ $where =$where +' and '; } $where = $where + k +' not in ('+obj[k]+') '; } } if ($where !=''){ $where =' where ' + $where ; } var $sql='select * from trans'+$where; return runSql($sql); } ,getDistEst:function(){ var $sql='select c_district,c_estate,e_district,e_estate from trans group by c_district,c_estate,e_district,e_estate order by c_district'; return runSql($sql); } }; exports.doc={ getList:function(){ var $sql='select * from document where deletedate =0 '; return runSql($sql); } ,getDocument:function(number){ var $sql='select * from document where '+ ' DOCUMENTTYPE = '+number +' '+ ' and deletedate=0'; return runSql($sql); } }; function runSql(sql){ var res=db.getObjResultSet(sql); return res||{}; }
wolflion/Code2018
C/DS-LCB/chap02LinearList/0202LinkList/LinkList.h
<gh_stars>0 #include <stdio.h> #include <malloc.h> #define MaxSize 50 typedef char ElemType; typedef struct LNode { ElemType data; struct LNode *next; }LinkList; void InitList(LinkList * &L); void DestoryList(LinkList *L); int ListEmpty(LinkList *L); int ListLength(LinkList *L); void DispList(LinkList *L); int GetElem(LinkList *L, int i, ElemType &e); int LocateElem(LinkList *L, ElemType e); int ListInsert(LinkList * &L, int i, ElemType e); int ListDelete(LinkList *&L, int i, ElemType &e);
smagill/opensphere-desktop
open-sphere-base/core/src/main/java/io/opensphere/core/math/WGS84EarthConstants.java
<reponame>smagill/opensphere-desktop package io.opensphere.core.math; import io.opensphere.core.util.MathUtil; /** Earth constants. */ public final class WGS84EarthConstants { /** Circumference around the equator. */ public static final double CIRCUMFERENCE_EQUATORIAL_M; /** Mean circumference. */ public static final double CIRCUMFERENCE_MEAN_M; /** Circumference passing through the poles. */ public static final double CIRCUMFERENCE_MERIDIAN_M; /** First eccentricity squared. */ public static final double FIRST_ECCENTRICITY_SQ; /** First eccentricity ^ 4. */ public static final double FIRST_ECCENTRICITY_FOURTH; /** First eccentricity ^ 6. */ public static final double FIRST_ECCENTRICITY_SIXTH; /** Flattening. */ public static final double FLATTENING; /** Reciprocal of flattening as defined by WGS84. */ public static final double INVERSE_FLATTENING = 298.257223563; /** One minus the flattening squared. */ public static final double ONE_MINUS_FLATTENING_SQ; /** Equatorial radius. */ public static final double RADIUS_EQUATORIAL_M; /** Mean radius. */ public static final double RADIUS_MEAN_M; /** Polar radius. */ public static final double RADIUS_POLAR_M; /** Second eccentricity squared. */ public static final double SECOND_ECCENTRICITY_SQ; /** Semi-major axis. */ public static final double SEMI_MAJOR_AXIS_M = 6378137.0; /** Semi-major axis squared. */ public static final double SEMI_MAJOR_AXIS_M_SQ; /** Semi-minor axis. */ public static final double SEMI_MINOR_AXIS_M; /** Semi-minor axes squared. */ public static final double SEMI_MINOR_AXIS_M_SQ; static { FLATTENING = 1 / INVERSE_FLATTENING; SEMI_MINOR_AXIS_M = SEMI_MAJOR_AXIS_M - SEMI_MAJOR_AXIS_M / INVERSE_FLATTENING; SEMI_MAJOR_AXIS_M_SQ = SEMI_MAJOR_AXIS_M * SEMI_MAJOR_AXIS_M; SEMI_MINOR_AXIS_M_SQ = SEMI_MINOR_AXIS_M * SEMI_MINOR_AXIS_M; FIRST_ECCENTRICITY_SQ = (SEMI_MAJOR_AXIS_M_SQ - SEMI_MINOR_AXIS_M_SQ) / SEMI_MAJOR_AXIS_M_SQ; SECOND_ECCENTRICITY_SQ = (SEMI_MAJOR_AXIS_M_SQ - SEMI_MINOR_AXIS_M_SQ) / SEMI_MINOR_AXIS_M_SQ; ONE_MINUS_FLATTENING_SQ = (1 - FLATTENING) * (1 - FLATTENING); FIRST_ECCENTRICITY_FOURTH = FIRST_ECCENTRICITY_SQ * FIRST_ECCENTRICITY_SQ; FIRST_ECCENTRICITY_SIXTH = FIRST_ECCENTRICITY_FOURTH * FIRST_ECCENTRICITY_SQ; RADIUS_EQUATORIAL_M = SEMI_MAJOR_AXIS_M; RADIUS_POLAR_M = SEMI_MINOR_AXIS_M; RADIUS_MEAN_M = (1 - FLATTENING / 3) * RADIUS_EQUATORIAL_M; CIRCUMFERENCE_MERIDIAN_M = RADIUS_POLAR_M * MathUtil.TWO_PI; CIRCUMFERENCE_EQUATORIAL_M = RADIUS_EQUATORIAL_M * MathUtil.TWO_PI; CIRCUMFERENCE_MEAN_M = RADIUS_MEAN_M * MathUtil.TWO_PI; } /** Disallow instantiation. */ private WGS84EarthConstants() { } }
evgenyvinnik/jvsc-android-apps
FluteHero2/src/ca/jvsh/flute/scoreloop/UserActivity.java
<reponame>evgenyvinnik/jvsc-android-apps /* * In derogation of the Scoreloop SDK - License Agreement concluded between * Licensor and Licensee, as defined therein, the following conditions shall * apply for the source code contained below, whereas apart from that the * Scoreloop SDK - License Agreement shall remain unaffected. * * Copyright: Scoreloop AG, Germany (Licensor) * * 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 ca.jvsh.flute.scoreloop; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import ca.jvsh.flute.R; import ca.jvsh.flute.activity.FluteHeroApplication; import com.scoreloop.client.android.core.controller.RequestController; import com.scoreloop.client.android.core.controller.RequestControllerObserver; import com.scoreloop.client.android.core.controller.UserController; import com.scoreloop.client.android.core.model.Entity; import com.scoreloop.client.android.core.model.EntityFactory; import com.scoreloop.client.android.core.model.Session; import com.scoreloop.client.android.core.model.User; public class UserActivity extends Activity { // constants that define the dialogs neeeded on this activity private final static int DIALOG_PROGRESS = 0; private final static int DIALOG_ERROR = 1; private final static int DIALOG_CHALLENGE = 2; // stores the error message to be shown private String dialogErrorMessage; // stores the displayed user private User user; // references to our buttons private Button challengeButton; private Button addButton; private Button removeButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user); // find our buttons challengeButton = ((Button)findViewById(R.id.user_dialog_challenge)); addButton = (Button)findViewById(R.id.user_dialog_add); removeButton = (Button)findViewById(R.id.user_dialog_remove); // set up the challenge Button challengeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check if there's a saved game in the shared preferences SharedPreferences prefs = getSharedPreferences(FluteHeroApplication.GAME_STATE_PREFERENCES, MODE_PRIVATE); if(GameState.hasSavedGame(prefs)) { // can't start another game right now, so we can't accept the challenge dialogErrorMessage = getString(R.string.challenge_error_paused_game); showDialog(DIALOG_ERROR); return; } // alright, we can challenge the user. the following dialog // asks the user for the game mode and stake for the challenge. showDialog(DIALOG_CHALLENGE); } }); // set up the "add as friend" button addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RequestControllerObserver observer = new RequestControllerObserver() { @Override public void requestControllerDidReceiveResponse(RequestController controller) { // user was added - show a toast and refresh Toast.makeText(UserActivity.this, getString(R.string.user_added, user.getDisplayName()), Toast.LENGTH_LONG).show(); // this is a shortcut, because the current user's list // of friends is not automatically updated. removeButton.setVisibility(View.VISIBLE); addButton.setVisibility(View.GONE); dismissDialog(DIALOG_PROGRESS); } @Override public void requestControllerDidFail(RequestController aRequestController, Exception anException) { dismissDialog(DIALOG_PROGRESS); dialogErrorMessage = getString(R.string.user_add_error); showDialog(DIALOG_ERROR); } }; showDialog(DIALOG_PROGRESS); // this is the "add user as friend" controller UserController userController = new UserController(observer); // insert the user we want to add userController.setUser(user); // and launch the request userController.addAsBuddy(); } }); // and the "remove friend" button removeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RequestControllerObserver observer = new RequestControllerObserver() { @Override public void requestControllerDidReceiveResponse(RequestController controller) { // user was added - show a toast and refresh Toast.makeText(UserActivity.this, getString(R.string.user_removed, user.getDisplayName()), Toast.LENGTH_LONG).show(); user = ((UserController)controller).getUser(); // this is a shortcut, because the current user's list // of friends is not automatically updated. removeButton.setVisibility(View.GONE); addButton.setVisibility(View.VISIBLE); dismissDialog(DIALOG_PROGRESS); } @Override public void requestControllerDidFail(RequestController aRequestController, Exception anException) { dismissDialog(DIALOG_PROGRESS); dialogErrorMessage = getString(R.string.user_remove_error); showDialog(DIALOG_ERROR); } }; showDialog(DIALOG_PROGRESS); // this is our "remove user as friend" controller UserController userController = new UserController(observer); // insert the user we want to remove userController.setUser(user); // and launch the request userController.removeAsBuddy(); } }); } @Override public void onResume() { super.onResume(); // we have to load the user, so show a loading dialog showDialog(DIALOG_PROGRESS); // hide all buttons for now - well show whichever makes sense later challengeButton.setVisibility(View.GONE); addButton.setVisibility(View.GONE); removeButton.setVisibility(View.GONE); // clear any old user that might still be here user = null; // the intent tells us which user to load Intent intent = getIntent(); // we pass around the user's identifier. see the FriendsActivity's List click listener // for an example on how the intent is sent. EntityFactory entityFactory = Session.getCurrentSession().getEntityFactory(); final Entity userEntity = entityFactory.createEntity("user", intent.getStringExtra(FluteHeroApplication.EXTRA_USER_ID)); // a request observer for the controller that loads the user final RequestControllerObserver loadUserObserver = new RequestControllerObserver() { @Override public void requestControllerDidReceiveResponse(RequestController controller) { // finished loading the user - retrieve him from the controller user = ((UserController)controller).getUser(); // update the view // set the window title to the username getWindow().setTitle(user.getDisplayName()); // laod the user's profile image in the background final ImageView profilePic = (ImageView)findViewById(R.id.user_dialog_image); (new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { Bitmap result = null; try { URLConnection urlConnection = new URL(params[0]).openConnection(); // use caching urlConnection.setUseCaches(true); result = BitmapFactory.decodeStream(urlConnection.getInputStream()); } catch (Exception e) { // do nothing } return result; } protected void onPreExecute() { profilePic.setImageResource(R.drawable.sl_icon_loading); } protected void onPostExecute(Bitmap result) { if(result != null) { profilePic.setImageBitmap(result); } else { profilePic.setImageResource(R.drawable.sl_icon_user); } } }).execute(user.getImageUrl()); // if it's ourselves, we can skip all the buttons... if(!user.equals(Session.getCurrentSession().getUser())) { if (user.isChallengable()) { // visibility & caption challengeButton.setVisibility(View.VISIBLE); challengeButton.setText(getString(R.string.challenge_user, user.getDisplayName())); } else { // can't challenge - hide the button challengeButton.setVisibility(View.GONE); } // set the button texts removeButton.setText(getString(R.string.user_remove_friend, user.getDisplayName())); addButton.setText(getString(R.string.user_add_friend, user.getDisplayName())); // depending on if we're already friends... if(Session.getCurrentSession().getUser().getBuddyUsers().contains(user)) { // we're friends! addButton.setVisibility(View.GONE); removeButton.setVisibility(View.VISIBLE); } else { // not friends yet! removeButton.setVisibility(View.GONE); addButton.setVisibility(View.VISIBLE); } } // done loading! dismissDialog(DIALOG_PROGRESS); } @Override public void requestControllerDidFail(RequestController aRequestController, Exception anException) { dismissDialog(DIALOG_PROGRESS); // couldn't load the user dialogErrorMessage = getString(R.string.user_load_error); showDialog(DIALOG_ERROR); } }; // set up the user controller that loads the user's detail final UserController userController = new UserController(loadUserObserver); userController.setUser(userEntity); // but we need to make sure the current user's list of friends is loaded, // to decide if they are already friends, and we need to show the add or the // remove button. RequestControllerObserver buddiesRequestObserver = new RequestControllerObserver() { @Override public void requestControllerDidReceiveResponse(RequestController aRequestController) { // friends list loaded, let's load the user we want to display... userController.loadUserDetail(); } @Override public void requestControllerDidFail(RequestController aRequestController, Exception anException) { // couldn't load the current user's buddy list... dismissDialog(DIALOG_PROGRESS); dialogErrorMessage = getString(R.string.friends_load_error); showDialog(DIALOG_ERROR); } }; // set up a controller UserController buddiesController = new UserController(buddiesRequestObserver); buddiesController.loadBuddies(); } @Override protected Dialog onCreateDialog(final int id) { switch (id) { case DIALOG_PROGRESS: return ProgressDialog.show(UserActivity.this, "", getString(R.string.loading)); case DIALOG_ERROR: return (new AlertDialog.Builder(this)) .setPositiveButton(R.string.too_bad, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (user == null) { // no user loaded, let's get out of here... finish(); } } }) .setMessage("") .setCancelable(false) .create(); case DIALOG_CHALLENGE: return ChallengeStartDialog.create(this); } return null; } /** * handler to update the success and error dialog with the corresponding message */ @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_ERROR: AlertDialog errorDialog = (AlertDialog)dialog; errorDialog.setMessage(dialogErrorMessage); break; case DIALOG_CHALLENGE: ChallengeStartDialog challengeStartDialog = (ChallengeStartDialog)dialog; challengeStartDialog.prepare(user); break; } } }
lhuard1A/origin
pkg/client/testclient/fake_identities.go
package testclient import ( ktestclient "k8s.io/kubernetes/pkg/client/unversioned/testclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" userapi "github.com/openshift/origin/pkg/user/api" ) // FakeIdentities implements IdentitiesInterface. Meant to be embedded into a struct to get a default // implementation. This makes faking out just the methods you want to test easier. type FakeIdentities struct { Fake *Fake } func (c *FakeIdentities) Get(name string) (*userapi.Identity, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootGetAction("identities", name), &userapi.Identity{}) if obj == nil { return nil, err } return obj.(*userapi.Identity), err } func (c *FakeIdentities) List(label labels.Selector, field fields.Selector) (*userapi.IdentityList, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootListAction("identities", label, field), &userapi.IdentityList{}) if obj == nil { return nil, err } return obj.(*userapi.IdentityList), err } func (c *FakeIdentities) Create(inObj *userapi.Identity) (*userapi.Identity, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootCreateAction("identities", inObj), inObj) if obj == nil { return nil, err } return obj.(*userapi.Identity), err } func (c *FakeIdentities) Update(inObj *userapi.Identity) (*userapi.Identity, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootUpdateAction("identities", inObj), inObj) if obj == nil { return nil, err } return obj.(*userapi.Identity), err } func (c *FakeIdentities) Delete(name string) error { _, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction("identities", name), nil) return err }
carpe-noctem-cassel/alica
alica_tests/src/test/test_task_assignment.cpp
#include "BehaviourCreator.h" #include "ConditionCreator.h" #include "ConstraintCreator.h" #include "UtilityFunctionCreator.h" #include "engine/AgentIDConstPtr.h" #include "engine/AlicaClock.h" #include "engine/AlicaEngine.h" #include "engine/IRoleAssignment.h" #include "engine/PlanBase.h" #include "engine/PlanRepository.h" #include "engine/RunningPlan.h" #include "engine/TeamObserver.h" #include "engine/collections/RobotEngineData.h" #include "engine/collections/RobotProperties.h" #include "engine/model/AbstractPlan.h" #include "engine/model/Plan.h" #include "engine/planselector/PlanSelector.h" #include "engine/teammanager/Agent.h" #include "engine/teammanager/TeamManager.h" #include <test_alica.h> #include <gtest/gtest.h> #include <list> #include <memory> #include <ros/ros.h> #include <vector> using alica::AlicaTime; class StillClock : public alica::AlicaClock { alica::AlicaTime now() const override { return AlicaTime::milliseconds(555); } }; class TaskAssignmentTest : public AlicaTestFixtureBase { protected: virtual void SetUp() { // determine the path to the test config ros::NodeHandle nh; std::string path; nh.param<std::string>("/rootPath", path, "."); // bring up the SystemConfig with the corresponding path sc = essentials::SystemConfig::getInstance(); sc->setRootPath(path); sc->setConfigPath(path + "/etc"); cout << sc->getConfigPath() << endl; sc->setHostname("nase"); ae = new alica::AlicaEngine(new essentials::AgentIDManager(new essentials::AgentIDFactory()), "RolesetTA", "MasterPlanTaskAssignment", false); bc = new alica::BehaviourCreator(); cc = new alica::ConditionCreator(); uc = new alica::UtilityFunctionCreator(); crc = new alica::ConstraintCreator(); ae->setAlicaClock(new StillClock()); ae->init(bc, cc, uc, crc); } virtual void TearDown() { ae->shutdown(); sc->shutdown(); delete bc; delete cc; delete uc; delete crc; } }; TEST_F(TaskAssignmentTest, constructTaskAssignment) { ASSERT_NO_SIGNAL // fake a list of existing robots alica::AgentGrp robots; for (int number = 8; number <= 11; number++) { alica::AgentIDConstPtr agentID = ae->getId<int>(number); robots.push_back(agentID); ae->getTeamManager()->setTimeLastMsgReceived(agentID, ae->getAlicaClock()->now()); } ae->getTeamObserver()->tick(nullptr); ae->getRoleAssignment()->tick(); // fake inform the team observer about roles of none existing robots const alica::PlanRepository::Accessor<alica::Plan>& planMap = ae->getPlanRepository()->getPlans(); alica::RunningPlan* rp = ae->getPlanBase()->makeRunningPlan(planMap.find(1407152758497)); alica::AbstractPlanGrp inputPlans; inputPlans.push_back(planMap.find(1407152758497)); alica::PlanSelector* ps = ae->getPlanBase()->getPlanSelector(); std::vector<alica::RunningPlan*> o_plans; bool ok = ps->getPlansForState(rp, inputPlans, robots, o_plans); EXPECT_TRUE(ok); EXPECT_EQ(o_plans.size(), 1); }
energonQuest/dtEarth
ext/include/applications/osgearth_shadercomp/osgearth_shadercomp.cpp
<filename>ext/include/applications/osgearth_shadercomp/osgearth_shadercomp.cpp /* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * This sample demonstrates a simple use of osgEarth's shader composition framework. * * By default, osgEarth uses GL shaders to render the terrain. Shader composition is a * mechanism by which you can inject custom shader code into osgEarth's shader program * pipeline. This gets around the problem of having to duplicate shader code in order * to add functionality. */ #include <osg/Notify> #include <osgDB/ReadFile> #include <osgGA/StateSetManipulator> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgEarthUtil/EarthManipulator> #include <osgEarth/VirtualProgram> #include <osgEarth/Registry> #include <osgEarthUtil/Controls> using namespace osgEarth; using namespace osgEarth::Util::Controls; int usage( const std::string& msg ) { OE_NOTICE << msg << "\n\n" << "USAGE: osgearth_shadercomp <earthfile> \n" << " [--test1] : Run the function injection test \n" << " [--test5] : Run the Program state set text \n" << std::endl; return -1; } //------------------------------------------------------------------------- // Simple function injection test -- turns the earth gray with a haze. namespace TEST_1 { char s_hazeVertShader[] = "#version " GLSL_VERSION_STR "\n" "varying vec3 v_pos; \n" "void setup_haze(inout vec4 VertexVIEW) \n" "{ \n" " v_pos = vec3(VertexVIEW); \n" "} \n"; char s_hazeFragShader[] = "#version " GLSL_VERSION_STR "\n" "varying vec3 v_pos; \n" "void apply_haze(inout vec4 color) \n" "{ \n" " float dist = clamp( length(v_pos)/1e7, 0.0, 0.75 ); \n" " color = mix(color, vec4(0.5, 0.5, 0.5, 1.0), dist); \n" "} \n"; osg::StateAttribute* createHaze() { osgEarth::VirtualProgram* vp = new osgEarth::VirtualProgram(); vp->setFunction( "setup_haze", s_hazeVertShader, osgEarth::ShaderComp::LOCATION_VERTEX_VIEW ); vp->setFunction( "apply_haze", s_hazeFragShader, osgEarth::ShaderComp::LOCATION_FRAGMENT_LIGHTING ); return vp; } osg::Group* run( osg::Node* earth ) { osg::Group* g = new osg::Group(); g->addChild( earth ); g->getOrCreateStateSet()->setAttributeAndModes( createHaze(), osg::StateAttribute::ON ); return g; } } //------------------------------------------------------------------------- namespace TEST_5 { char s_vert[] = "#version " GLSL_VERSION_STR "\n" "void main() { \n" " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; \n" "} \n"; char s_frag[] = "#version " GLSL_VERSION_STR "\n" "void main() { \n" " gl_FragColor = vec4(1.0,0.0,0.0,1.0); \n" "} \n"; char s_vp[] = "#version " GLSL_VERSION_STR "\n" "void test( inout vec4 color ) { color = vec4(1.0,0.0,0.0,1.0); } \n"; osg::Geode* makeGeom( float v ) { osg::Geode* geode = new osg::Geode(); osg::Geometry* geom = new osg::Geometry(); osg::Vec3Array* verts = new osg::Vec3Array(); verts->push_back( osg::Vec3(v-1, 0, 0) ); verts->push_back( osg::Vec3(v+1, 0, 0) ); verts->push_back( osg::Vec3( 0, 0, 2) ); geom->setVertexArray( verts ); geom->setUseDisplayList(false); geom->setUseVertexBufferObjects(true); osg::Vec4Array* colors = new osg::Vec4Array(); colors->push_back( osg::Vec4(0,0,1,1) ); geom->setColorArray(colors); geom->setColorBinding(osg::Geometry::BIND_OVERALL); geom->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLES,0,3)); geode->addDrawable(geom); return geode; } osg::Group* run() { osg::Node* n1 = makeGeom( -5 ); osg::Node* n2 = makeGeom( 5 ); #if 0 osg::Program* p = new osg::Program(); p->addShader( new osg::Shader(osg::Shader::VERTEX, s_vert) ); p->addShader( new osg::Shader(osg::Shader::FRAGMENT, s_frag) ); #else VirtualProgram* p = new VirtualProgram(); p->setFunction("test", s_vp, ShaderComp::LOCATION_FRAGMENT_LIGHTING); #endif n1->getOrCreateStateSet()->setAttributeAndModes( p, 1 ); osg::Group* root = new osg::Group(); root->getOrCreateStateSet()->setRenderBinDetails( 0, "TraversalOrderBin" ); root->getOrCreateStateSet()->setMode(GL_LIGHTING,0); root->addChild( n1 ); root->addChild( n2 ); return root; } } //------------------------------------------------------------------------- int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); osgViewer::Viewer viewer(arguments); bool test1 = arguments.read("--test1"); bool test5 = arguments.read("--test5"); bool ok = test1 || test5; if ( !ok ) { return usage(""); } if ( !test5 ) { osg::Node* earthNode = osgDB::readNodeFiles( arguments ); if (!earthNode) { return usage( "Unable to load earth model." ); } viewer.setCameraManipulator( new osgEarth::Util::EarthManipulator() ); LabelControl* label = new LabelControl(); if ( !test5 ) ControlCanvas::get(&viewer,true)->addControl(label); if ( test1 ) { viewer.setSceneData( TEST_1::run(earthNode) ); label->setText( "Function injection test: the map should appear hazy." ); } } else // if ( test5 ) { viewer.setSceneData( TEST_5::run() ); } // add some stock OSG handlers: viewer.addEventHandler(new osgViewer::StatsHandler()); viewer.addEventHandler(new osgViewer::WindowSizeHandler()); viewer.addEventHandler(new osgViewer::ThreadingHandler()); viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet())); return viewer.run(); }