repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ezeperez26/fiuba-campus-movil-ws
app/models/nationality.rb
# == Schema Information # # Table name: nationalities # # id :integer not null, primary key # nationality :string # created_at :datetime not null # updated_at :datetime not null # profile_id :integer # class Nationality < ActiveRecord::Base belongs_to :profile end
AM869/tyJAVA
source files/src/main/java/com/klsoukas/mavenproject8/customValidation/Matches.java
<reponame>AM869/tyJAVA package com.klsoukas.mavenproject8.customValidation; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Constraint(validatedBy = MatchesValidator.class) @Documented public @interface Matches { // String message() default "{com.moa.podium.util.constraints.matches}"; String message() default "The two fields do not match!"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String field(); String verifyField(); //declare this to make available multiple uses of same annotation for java 7 and below @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Documented @interface List { Matches[] value(); } }
OlafKolditz/ogs
ProcessLib/HeatTransportBHE/BoundaryConditions/BHEBottomDirichletBoundaryCondition.h
/** * \file * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once #include "NumLib/IndexValueVector.h" #include "ProcessLib/BoundaryCondition/BoundaryCondition.h" namespace ProcessLib::HeatTransportBHE { class BHEBottomDirichletBoundaryCondition final : public BoundaryCondition { public: explicit BHEBottomDirichletBoundaryCondition( std::pair<GlobalIndexType, GlobalIndexType>&& in_out_global_indices) : _in_out_global_indices(std::move(in_out_global_indices)) { } void getEssentialBCValues( const double t, GlobalVector const& x, NumLib::IndexValueVector<GlobalIndexType>& bc_values) const override; private: std::pair<GlobalIndexType, GlobalIndexType> const _in_out_global_indices; }; std::unique_ptr<BHEBottomDirichletBoundaryCondition> createBHEBottomDirichletBoundaryCondition( std::pair<GlobalIndexType, GlobalIndexType>&& in_out_global_indices); } // namespace ProcessLib::HeatTransportBHE
thomasverweij/iaf
core/src/main/java/nl/nn/adapterframework/receivers/JavaListener.java
/* Copyright 2013 Nationale-Nederlanden, 2020 WeAreFrank! 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 nl.nn.adapterframework.receivers; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import lombok.Getter; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.IMessageHandler; import nl.nn.adapterframework.core.IPipeLineSession; import nl.nn.adapterframework.core.IPushingListener; import nl.nn.adapterframework.core.ISecurityHandler; import nl.nn.adapterframework.core.IbisExceptionListener; import nl.nn.adapterframework.core.ListenerException; import nl.nn.adapterframework.core.PipeLineResult; import nl.nn.adapterframework.dispatcher.DispatcherManagerFactory; import nl.nn.adapterframework.dispatcher.RequestProcessor; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.http.HttpSecurityHandler; import nl.nn.adapterframework.stream.Message; import nl.nn.adapterframework.util.LogUtil; /** * * The JavaListener listens to java requests. * * @author <NAME> */ public class JavaListener implements IPushingListener<String>, RequestProcessor, HasPhysicalDestination { protected Logger log = LogUtil.getLogger(this); private @Getter ClassLoader configurationClassLoader = Thread.currentThread().getContextClassLoader(); private String name; private String serviceName; private boolean isolated=false; private boolean synchronous=true; private boolean opened=false; private boolean throwException = true; private boolean httpWsdl = false; private static Map<String, JavaListener> registeredListeners; private IMessageHandler<String> handler; @Override public void configure() throws ConfigurationException { if (isIsolated()) { throw new ConfigurationException("function of attribute 'isolated' is replaced by 'transactionAttribute' on PipeLine"); } try { if (handler==null) { throw new ConfigurationException("handler has not been set"); } if (StringUtils.isEmpty(getName())) { throw new ConfigurationException("name has not been set"); } } catch (Exception e){ throw new ConfigurationException(e); } } @Override public synchronized void open() throws ListenerException { try { // add myself to local list so that IbisLocalSenders can find me registerListener(); // // display transaction status, to force caching of UserTransaction. // // UserTransaction is not found in context if looked up from javalistener. // try { // String transactionStatus = JtaUtil.displayTransactionStatus(); // log.debug("transaction status at startup ["+transactionStatus+"]"); // } catch (Exception e) { // log.warn("could not get transaction status at startup",e); // } // add myself to global list so that other applications in this JVM (like Everest Portal) can find me. // (performed only if serviceName is not empty if (StringUtils.isNotEmpty(getServiceName())) { DispatcherManagerFactory.getDispatcherManager().register(getServiceName(), this); } opened=true; } catch (Exception e) { throw new ListenerException("error occured while starting listener [" + getName() + "]", e); } } @Override public synchronized void close() throws ListenerException { opened=false; try { // unregister from local list unregisterListener(); // unregister from global list if (StringUtils.isNotEmpty(getServiceName())) { // Current DispatcherManager (version 1.3) doesn't have an // unregister method, instead a call to register with a null // value is done. DispatcherManagerFactory.getDispatcherManager().register(getServiceName(), null); } } catch (Exception e) { throw new ListenerException("error occured while stopping listener [" + getName() + "]", e); } } @Override public String processRequest(String correlationId, String rawMessage, HashMap context) throws ListenerException { if (!isOpen()) { throw new ListenerException("JavaListener [" + getName() + "] is not opened"); } if (log.isDebugEnabled()) { log.debug("JavaListener [" + getName() + "] processing correlationId [" + correlationId + "]"); } if (context != null) { Object object = context.get("httpRequest"); if (object != null) { if (object instanceof HttpServletRequest) { ISecurityHandler securityHandler = new HttpSecurityHandler((HttpServletRequest)object); context.put(IPipeLineSession.securityHandlerKey, securityHandler); } else { log.warn("No securityHandler added for httpRequest [" + object.getClass() + "]"); } } } Message message = new Message(rawMessage); if (throwException) { try { return handler.processRequest(this, correlationId, rawMessage, message, (Map<String,Object>)context).asString(); } catch (IOException e) { throw new ListenerException("cannot convert stream", e); } } else { try { return handler.processRequest(this, correlationId, rawMessage, message, context).asString(); } catch (ListenerException | IOException e) { try { return handler.formatException(null,correlationId, message, e).asString(); } catch (IOException e1) { throw new ListenerException(e); } } } } /** * Register listener so that it can be used by a proxy */ private void registerListener() { getListeners().put(getName(), this); } private void unregisterListener() { getListeners().remove(getName()); } /** * Returns JavaListener registered under the given name */ public static JavaListener getListener(String name) { return (JavaListener)getListeners().get(name); } /** * Get all registered JavaListeners */ private static synchronized Map<String, JavaListener> getListeners() { if (registeredListeners == null) { registeredListeners = Collections.synchronizedMap(new HashMap<String,JavaListener>()); } return registeredListeners; } public static Set<String> getListenerNames() { return getListeners().keySet(); } @Override public void setExceptionListener(IbisExceptionListener listener) { // do nothing, no exceptions known } @Override public void afterMessageProcessed(PipeLineResult processResult, Object rawMessage, Map<String,Object> context) throws ListenerException { // do nothing } @Override public String getIdFromRawMessage(String rawMessage, Map<String,Object> context) throws ListenerException { // do nothing return null; } @Override public Message extractMessage(String rawMessage, Map<String,Object> context) throws ListenerException { return new Message(rawMessage); } @Override public String getPhysicalDestinationName() { if (StringUtils.isNotEmpty(getServiceName())) { return "external: "+getServiceName(); } else { return "internal: "+getName(); } } /** * The <code>toString()</code> method retrieves its value * by reflection. * @see org.apache.commons.lang.builder.ToStringBuilder#reflectionToString * **/ @Override public String toString() { return super.toString(); // This gives stack overflows: // return ToStringBuilder.reflectionToString(this); } @Override public void setHandler(IMessageHandler<String> handler) { this.handler = handler; } public IMessageHandler<String> getHandler() { return handler; } public void setServiceName(String jndiName) { this.serviceName = jndiName; } public String getServiceName() { return serviceName; } @IbisDoc({"name of the listener as known to the adapter. an {@link nl.nn.adapterframework.pipes.ibislocalsender ibislocalsender} refers to this name in its <code>javalistener</code>-attribute.", ""}) @Override public void setName(String name) { this.name = name; } @Override public String getName() { return name; } public void setLocal(String name) { throw new RuntimeException("do not set attribute 'local=true', just leave serviceName empty!"); } public void setIsolated(boolean b) { isolated = b; } public boolean isIsolated() { return isolated; } @IbisDoc({" when set <code>false</code>, the request is executed asynchronously. this implies <code>isolated=true</code>. n.b. be aware that there is no limit on the number of threads generated", "true"}) public void setSynchronous(boolean b) { synchronous = b; } public boolean isSynchronous() { return synchronous; } public synchronized boolean isOpen() { return opened; } @IbisDoc({"should the javalistener throw a listenerexception when it occurs or return an error message", "<code>true</code>"}) public void setThrowException(boolean throwException) { this.throwException = throwException; } public boolean isThrowException() { return throwException; } @IbisDoc({"when <code>true</code>, the wsdl of the service provided by this listener is available for download ", "<code>false</code>"}) public void setHttpWsdl(boolean httpWsdl) { this.httpWsdl = httpWsdl; } public boolean isHttpWsdl() { return httpWsdl; } }
MrKuzio/liquid-to-handlebars
lib/utils.js
'use strict'; const split = require('split-string'); const not = require('regex-not'); const utils = module.exports; const memo = {}; utils.last = function(arr) { return Array.isArray(arr) ? arr[arr.length - 1] : null; }; /** * String utils */ utils.toString = function(val) { return typeof val === 'string' ? val.trim() : ''; }; utils.isString = function(val) { return typeof val === 'string' && val.trim() !== ''; }; utils.stripChar = function(str, ch) { const re = new RegExp('\\' + ch + '( |$)'); return str.replace(re, '$1'); }; /** * Tags / expressions */ utils.textRegex = function() { if (memo.textRegex) return memo.textRegex; const regex = not('(?:\\{\\{|\\}\\}|\\{%|%\\})+?', {strictClose: false}); return (memo.textRegex = regex); }; utils.hasEndTag = function(name, str) { if (name.slice(0, 3) === 'end') { return true; } if (/^[{%}]+$/.test(name)) { return false; } if (utils.isExpression(name)) { return false; } if (utils.isTag(name)) { return true; } const re = new RegExp('{%-?\\s*end' + name + '\\s*-?%}'); return re.test(str); }; utils.isTag = function(name) { return /^(capture|case|comment|for|if|paginate|raw|tablerow|unless)$/.test(name); }; utils.isExpression = function(name) { return /^(assign|cycle|else|elsif|include)$/.test(name); }; utils.toRange = function(str) { const match = /(.*?)\(([^.]+)\.\.([^)]+?)\)(.*?)/.exec(str); if (match) { return match[1] + '(range ' + match[2] + ' ' + match[3] + ')' + (match[4] ? ' ' + match[4] : ''); } return str; }; utils.isKeyword = function(val) { return /^(break|continue|else|elsif)$/.test(val.trim()); }; utils.isDotProp = function(str) { return /^([-$\w]+(?:[. ][-$\w]+)*)+(?:\[[^\]]+\])?$/.test(str); }; /** * Namespacing */ utils.isNamespace = function(str, names) { let re = memo.namespaceRegex; if (!re) { re = new RegExp('(^| )(?:' + names.join('|') + ')\\.'); memo.namespaceRegex = re; } return utils.isDotProp(str) && re.test(str); }; utils.getPrefix = function(options) { options = options || {}; if (!options.prefix) { return ''; } if (options.prefix === true) { return '@'; } if (options.prefix) { return options.prefix; } }; utils.toHash = function(hash) { return Object.keys(hash || {}).reduce(function(acc, key) { return acc + ' ' + key + '=' + hash[key]; }, ''); }; /** * Args */ utils.escapeValue = function(prop) { prop = prop.trim(); if (!prop) return prop; if (utils.hasParens()) { return prop; } if (prop.length > 1 && utils.isQuoted(prop)) { return utils.addQuotes(prop); } if (/^[-\d.]+$/.test(prop) || /^[a-z@._'"]+$/i.test(prop)) { return prop; } if (/^[-a-z@._]+$/i.test(prop)) { return prop; } return utils.addQuotes(prop); }; utils.namespaceArgs = function(args, options) { const opts = Object.assign({}, options); // special variables supported by shopify const shopifyVariables = opts.shopifyVariables || [ 'article', 'blog', 'cart', 'collection', 'comment', 'linklist', 'page', 'post', 'product', 'shop', 'site' ]; const names = opts.namespace || shopifyVariables; const isString = typeof args === 'string'; const prefix = utils.getPrefix(options); if (!prefix) { return args; } if (isString) { args = utils.splitArgs(args, ' '); } for (let i = 0; i < args.length; i++) { const arg = args[i]; if (utils.isNamespace(arg, names)) { args[i] = prefix + arg.replace(/^@/, ''); } } if (isString) { return args.join(' '); } return args; }; utils.splitArgs = function(str, sep) { const args = split(str, {sep: sep || ',', keepQuotes: true, brackets: true}); const len = args.length; const acc = []; let idx = -1; while (++idx < len) { let arg = args[idx].trim(); if (arg === '') continue; if (/[\\/]/.test(arg) && !utils.isQuoted(arg)) { arg = utils.addQuotes(arg); } acc.push(arg); } return acc; }; utils.wrap = function(val) { if (Array.isArray(val)) { val = val.join(' '); } if (utils.isQuoted(val)) { return val; } if (utils.hasParens(val)) { return val; } return '(' + val + ')'; }; /** * Quotes */ utils.hasParens = function(val) { return typeof val === 'string' && val.charAt(0) === '(' && val.slice(-1) === ')'; }; utils.stripQuotes = str => str.replace(/^['"]|['"]$/g, ''); utils.hasSingleQuotes = str => /^'(.*)'/.test(str); utils.hasDoubleQuotes = str => /^"(.*)"/.test(str); utils.isQuoted = str => /^(['"])([^\1]*)\1$/.test(str); utils.addQuotes = function(str) { if (utils.hasParens(str)) { return str; } return '\'' + utils.stripQuotes(str).replace(/\\?'/g, '"') + '\''; };
PaaS-TA/PAAS-TA-CONTAINER-PLATFORM-COMMON-API
src/main/java/org/paasta/container/platform/common/api/exception/CpRuntimeException.java
package org.paasta.container.platform.common.api.exception; /** * Cp Runtime Exception 클래스 * * @author kjhoon * @version 1.0 * @since 2020.08.28 */ public class CpRuntimeException extends BaseBizException { private static final long serialVersionUID = -1288712633779609678L; public CpRuntimeException(int errorCode, String errorMessage) { super(errorCode, errorMessage); } public CpRuntimeException(String errorMessage) { super(errorMessage); } }
BaekSeungYeol/perpetmatch
src/main/java/com/perpetmatch/api/dto/Profile/ProfileDto.java
package com.perpetmatch.api.dto.Profile; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class ProfileDto { private Long id; private String nickname; private String email; }
my-references/coursemology2
client/app/bundles/course/pages/UserEmailSubscriptions/translations.intl.js
<reponame>my-references/coursemology2 import { defineMessages } from 'react-intl'; const translations = defineMessages({ component: { id: 'course.UserEmailSubscriptions.component', defaultMessage: 'Topic', }, setting: { id: 'course.UserEmailSubscriptions.setting', defaultMessage: 'Setting', }, description: { id: 'course.UserEmailSubscriptions.description', defaultMessage: 'Description', }, enabled: { id: 'course.UserEmailSubscriptions.enabled', defaultMessage: 'Enabled?', }, emailSubscriptions: { id: 'course.UserEmailSubscriptions.emailSubscriptions', defaultMessage: 'Email Subscriptions', }, updateSuccess: { id: 'course.UserEmailSubscriptions.updateSuccess', defaultMessage: 'Email subscription for "{topic}" has been {action}.', }, updateFailure: { id: 'course.UserEmailSubscriptions.updateFailure', defaultMessage: 'Failed to update email subscription for "{topic}".', }, unsubscribeSuccess: { id: 'course.UserEmailSubscriptions.unsubscribeSuccess', defaultMessage: 'You have successfully unsubscribed from the topics above.', }, noEmailSubscriptionSettings: { id: 'course.UserEmailSubscriptions.noEmailSubscriptionSettings', defaultMessage: 'There is no available email subscription setting.', }, viewAllEmailSubscriptionSettings: { id: 'course.UserEmailSubscriptions.viewAllEmailSubscriptionSettings', defaultMessage: 'View and manage all your other email subscriptions.', }, }); export const subscriptionComponents = defineMessages({ announcements: { id: 'course.UserEmailSubscriptions.subscriptionComponents.announcements', defaultMessage: 'Announcements', }, assessments: { id: 'course.UserEmailSubscriptions.subscriptionComponents.assessments', defaultMessage: 'Assessments', }, forums: { id: 'course.UserEmailSubscriptions.subscriptionComponents.forums', defaultMessage: 'Forums', }, surveys: { id: 'course.UserEmailSubscriptions.subscriptionComponents.surveys', defaultMessage: 'Surveys', }, users: { id: 'course.UserEmailSubscriptions.subscriptionComponents.users', defaultMessage: 'Users', }, videos: { id: 'course.UserEmailSubscriptions.subscriptionComponents.videos', defaultMessage: 'Videos', }, }); export const subscriptionTitles = defineMessages({ new_announcement: { id: 'course.UserEmailSubscriptions.subscriptionTitles.new_announcement', defaultMessage: 'New Announcement', }, opening_reminder: { id: 'course.UserEmailSubscriptions.subscriptionTitles.opening_reminder', defaultMessage: 'Opening Reminder', }, closing_reminder: { id: 'course.UserEmailSubscriptions.subscriptionTitles.closing_reminder', defaultMessage: 'Closing Reminder', }, closing_reminder_summary: { id: 'course.UserEmailSubscriptions.subscriptionTitles.closing_reminder_summary', defaultMessage: 'Closing Reminder Summary', }, grades_released: { id: 'course.UserEmailSubscriptions.subscriptionTitles.grades_released', defaultMessage: 'Grades Released', }, new_comment: { id: 'course.UserEmailSubscriptions.subscriptionTitles.new_comment', defaultMessage: 'Submission Comment', }, new_submission: { id: 'course.UserEmailSubscriptions.subscriptionTitles.new_submission', defaultMessage: 'New Submission', }, new_topic: { id: 'course.UserEmailSubscriptions.subscriptionTitles.new_topic', defaultMessage: 'New Topic', }, post_replied: { id: 'course.UserEmailSubscriptions.subscriptionTitles.post_replied', defaultMessage: 'New Post and Reply', }, new_enrol_request: { id: 'course.UserEmailSubscriptions.subscriptionTitles.new_enrol_request', defaultMessage: 'New Enrol Request', }, }); export const subscriptionDescriptions = defineMessages({ announcements_new_announcement: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.announcements_new_announcement', defaultMessage: 'Stay notified whenever a new announcement is made.', }, assessments_opening_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments_opening_reminder', defaultMessage: 'Be notified when a new assignment is available.', }, assessments_closing_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments_closing_reminder', defaultMessage: 'Be notified when an assignment about to be due.', }, assessments_closing_reminder_summary: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments', defaultMessage: 'Receive an email containing a list of students who receive closing reminders for an assignment.', }, assessments_grades_released: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments_grades_released', defaultMessage: 'Be notified when your submission has been graded.', }, assessments_new_comment: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments_new_comment', defaultMessage: 'Be notified when you receive comments and replies for an assignment.', }, assessments_new_submission: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.assessments_new_submission', defaultMessage: 'Be notified when your student creates a new submission.', }, forums_new_topic: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.forums_new_topic', defaultMessage: 'Be notified when there are new topics created for forums that you are subscribed to.', }, forums_post_replied: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.forums_post_replied', defaultMessage: 'Be notified when there are posts and replies for forum topics you are subscribed to.', }, surveys_opening_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.surveys_opening_reminder', defaultMessage: 'Be notified when a new survey is available.', }, surveys_closing_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.surveys_closing_reminder', defaultMessage: 'Be notified when a survey is about to expire.', }, surveys_closing_reminder_summary: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.surveys_closing_reminder_summary', defaultMessage: 'Receive an email containing a list of students who receive closing reminders for a survey.', }, videos_opening_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.videos_opening_reminder.', defaultMessage: 'Be notified when a new video is available.', }, videos_closing_reminder: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.videos_closing_reminder', defaultMessage: 'Be notified when a video is about to expire.', }, users_new_enrol_request: { id: 'course.UserEmailSubscriptions.subscriptionDescriptions.users_new_enrol_request', defaultMessage: 'Be notified when a new course enrolment request is made.', }, }); export default translations;
YJBeetle/QtAndroidAPI
android-28/android/icu/text/NumberFormat.cpp
<gh_stars>10-100 #include "../../../JArray.hpp" #include "../math/BigDecimal.hpp" #include "./DisplayContext.hpp" #include "./DisplayContext_Type.hpp" #include "../util/Currency.hpp" #include "../util/CurrencyAmount.hpp" #include "../util/ULocale.hpp" #include "../../../JString.hpp" #include "../../../java/lang/Number.hpp" #include "../../../JObject.hpp" #include "../../../JString.hpp" #include "../../../java/lang/StringBuffer.hpp" #include "../../../java/math/BigDecimal.hpp" #include "../../../java/math/BigInteger.hpp" #include "../../../java/text/FieldPosition.hpp" #include "../../../java/text/ParsePosition.hpp" #include "../../../java/util/Locale.hpp" #include "./NumberFormat.hpp" namespace android::icu::text { // Fields jint NumberFormat::ACCOUNTINGCURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "ACCOUNTINGCURRENCYSTYLE" ); } jint NumberFormat::CASHCURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "CASHCURRENCYSTYLE" ); } jint NumberFormat::CURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "CURRENCYSTYLE" ); } jint NumberFormat::FRACTION_FIELD() { return getStaticField<jint>( "android.icu.text.NumberFormat", "FRACTION_FIELD" ); } jint NumberFormat::INTEGERSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "INTEGERSTYLE" ); } jint NumberFormat::INTEGER_FIELD() { return getStaticField<jint>( "android.icu.text.NumberFormat", "INTEGER_FIELD" ); } jint NumberFormat::ISOCURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "ISOCURRENCYSTYLE" ); } jint NumberFormat::NUMBERSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "NUMBERSTYLE" ); } jint NumberFormat::PERCENTSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "PERCENTSTYLE" ); } jint NumberFormat::PLURALCURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "PLURALCURRENCYSTYLE" ); } jint NumberFormat::SCIENTIFICSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "SCIENTIFICSTYLE" ); } jint NumberFormat::STANDARDCURRENCYSTYLE() { return getStaticField<jint>( "android.icu.text.NumberFormat", "STANDARDCURRENCYSTYLE" ); } // QJniObject forward NumberFormat::NumberFormat(QJniObject obj) : android::icu::text::UFormat(obj) {} // Constructors NumberFormat::NumberFormat() : android::icu::text::UFormat( "android.icu.text.NumberFormat", "()V" ) {} // Methods JArray NumberFormat::getAvailableLocales() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getAvailableLocales", "()[Ljava/util/Locale;" ); } android::icu::text::NumberFormat NumberFormat::getCurrencyInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getCurrencyInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getCurrencyInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getCurrencyInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getCurrencyInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getCurrencyInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getInstance(jint arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "(I)Landroid/icu/text/NumberFormat;", arg0 ); } android::icu::text::NumberFormat NumberFormat::getInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getInstance(android::icu::util::ULocale arg0, jint arg1) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "(Landroid/icu/util/ULocale;I)Landroid/icu/text/NumberFormat;", arg0.object(), arg1 ); } android::icu::text::NumberFormat NumberFormat::getInstance(java::util::Locale arg0, jint arg1) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getInstance", "(Ljava/util/Locale;I)Landroid/icu/text/NumberFormat;", arg0.object(), arg1 ); } android::icu::text::NumberFormat NumberFormat::getIntegerInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getIntegerInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getIntegerInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getIntegerInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getIntegerInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getIntegerInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getNumberInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getNumberInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getNumberInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getNumberInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getNumberInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getNumberInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getPercentInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getPercentInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getPercentInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getPercentInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getPercentInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getPercentInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getScientificInstance() { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getScientificInstance", "()Landroid/icu/text/NumberFormat;" ); } android::icu::text::NumberFormat NumberFormat::getScientificInstance(android::icu::util::ULocale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getScientificInstance", "(Landroid/icu/util/ULocale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } android::icu::text::NumberFormat NumberFormat::getScientificInstance(java::util::Locale arg0) { return callStaticObjectMethod( "android.icu.text.NumberFormat", "getScientificInstance", "(Ljava/util/Locale;)Landroid/icu/text/NumberFormat;", arg0.object() ); } JObject NumberFormat::clone() const { return callObjectMethod( "clone", "()Ljava/lang/Object;" ); } jboolean NumberFormat::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } JString NumberFormat::format(android::icu::math::BigDecimal arg0) const { return callObjectMethod( "format", "(Landroid/icu/math/BigDecimal;)Ljava/lang/String;", arg0.object() ); } JString NumberFormat::format(android::icu::util::CurrencyAmount arg0) const { return callObjectMethod( "format", "(Landroid/icu/util/CurrencyAmount;)Ljava/lang/String;", arg0.object() ); } JString NumberFormat::format(jdouble arg0) const { return callObjectMethod( "format", "(D)Ljava/lang/String;", arg0 ); } JString NumberFormat::format(java::math::BigDecimal arg0) const { return callObjectMethod( "format", "(Ljava/math/BigDecimal;)Ljava/lang/String;", arg0.object() ); } JString NumberFormat::format(java::math::BigInteger arg0) const { return callObjectMethod( "format", "(Ljava/math/BigInteger;)Ljava/lang/String;", arg0.object() ); } JString NumberFormat::format(jlong arg0) const { return callObjectMethod( "format", "(J)Ljava/lang/String;", arg0 ); } java::lang::StringBuffer NumberFormat::format(android::icu::math::BigDecimal arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(Landroid/icu/math/BigDecimal;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0.object(), arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(android::icu::util::CurrencyAmount arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(Landroid/icu/util/CurrencyAmount;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0.object(), arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(jdouble arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(DLjava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0, arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(JObject arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(Ljava/lang/Object;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0.object<jobject>(), arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(java::math::BigDecimal arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(Ljava/math/BigDecimal;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0.object(), arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(java::math::BigInteger arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(Ljava/math/BigInteger;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0.object(), arg1.object(), arg2.object() ); } java::lang::StringBuffer NumberFormat::format(jlong arg0, java::lang::StringBuffer arg1, java::text::FieldPosition arg2) const { return callObjectMethod( "format", "(JLjava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;", arg0, arg1.object(), arg2.object() ); } android::icu::text::DisplayContext NumberFormat::getContext(android::icu::text::DisplayContext_Type arg0) const { return callObjectMethod( "getContext", "(Landroid/icu/text/DisplayContext$Type;)Landroid/icu/text/DisplayContext;", arg0.object() ); } android::icu::util::Currency NumberFormat::getCurrency() const { return callObjectMethod( "getCurrency", "()Landroid/icu/util/Currency;" ); } jint NumberFormat::getMaximumFractionDigits() const { return callMethod<jint>( "getMaximumFractionDigits", "()I" ); } jint NumberFormat::getMaximumIntegerDigits() const { return callMethod<jint>( "getMaximumIntegerDigits", "()I" ); } jint NumberFormat::getMinimumFractionDigits() const { return callMethod<jint>( "getMinimumFractionDigits", "()I" ); } jint NumberFormat::getMinimumIntegerDigits() const { return callMethod<jint>( "getMinimumIntegerDigits", "()I" ); } jint NumberFormat::getRoundingMode() const { return callMethod<jint>( "getRoundingMode", "()I" ); } jint NumberFormat::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } jboolean NumberFormat::isGroupingUsed() const { return callMethod<jboolean>( "isGroupingUsed", "()Z" ); } jboolean NumberFormat::isParseIntegerOnly() const { return callMethod<jboolean>( "isParseIntegerOnly", "()Z" ); } jboolean NumberFormat::isParseStrict() const { return callMethod<jboolean>( "isParseStrict", "()Z" ); } java::lang::Number NumberFormat::parse(JString arg0) const { return callObjectMethod( "parse", "(Ljava/lang/String;)Ljava/lang/Number;", arg0.object<jstring>() ); } java::lang::Number NumberFormat::parse(JString arg0, java::text::ParsePosition arg1) const { return callObjectMethod( "parse", "(Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Number;", arg0.object<jstring>(), arg1.object() ); } android::icu::util::CurrencyAmount NumberFormat::parseCurrency(JString arg0, java::text::ParsePosition arg1) const { return callObjectMethod( "parseCurrency", "(Ljava/lang/CharSequence;Ljava/text/ParsePosition;)Landroid/icu/util/CurrencyAmount;", arg0.object<jstring>(), arg1.object() ); } JObject NumberFormat::parseObject(JString arg0, java::text::ParsePosition arg1) const { return callObjectMethod( "parseObject", "(Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Object;", arg0.object<jstring>(), arg1.object() ); } void NumberFormat::setContext(android::icu::text::DisplayContext arg0) const { callMethod<void>( "setContext", "(Landroid/icu/text/DisplayContext;)V", arg0.object() ); } void NumberFormat::setCurrency(android::icu::util::Currency arg0) const { callMethod<void>( "setCurrency", "(Landroid/icu/util/Currency;)V", arg0.object() ); } void NumberFormat::setGroupingUsed(jboolean arg0) const { callMethod<void>( "setGroupingUsed", "(Z)V", arg0 ); } void NumberFormat::setMaximumFractionDigits(jint arg0) const { callMethod<void>( "setMaximumFractionDigits", "(I)V", arg0 ); } void NumberFormat::setMaximumIntegerDigits(jint arg0) const { callMethod<void>( "setMaximumIntegerDigits", "(I)V", arg0 ); } void NumberFormat::setMinimumFractionDigits(jint arg0) const { callMethod<void>( "setMinimumFractionDigits", "(I)V", arg0 ); } void NumberFormat::setMinimumIntegerDigits(jint arg0) const { callMethod<void>( "setMinimumIntegerDigits", "(I)V", arg0 ); } void NumberFormat::setParseIntegerOnly(jboolean arg0) const { callMethod<void>( "setParseIntegerOnly", "(Z)V", arg0 ); } void NumberFormat::setParseStrict(jboolean arg0) const { callMethod<void>( "setParseStrict", "(Z)V", arg0 ); } void NumberFormat::setRoundingMode(jint arg0) const { callMethod<void>( "setRoundingMode", "(I)V", arg0 ); } } // namespace android::icu::text
mikelandy/HIPS
user-contributed/lblOLD/xview/genial/lib/c_array.c
/* * c_array.c a collection of routines for handeling * dynamically allocated arrays in C. * * <NAME> LBL * * This routines allocate and access array by creating arrays of pointers. * The reason for these routines are speed and code readability. Allocating * arrays in this manner means that elements can be accessed by pointers * instead of by a multiplication and an addition. This method uses more * memory, but on a machine with plenty of memory the increase in speed * is worth it. * * for example, this: * * for (r = 0; r < nrow; r++) * for (c = 0; c < ncol; c++) { * pixel = image[r][c]; * * is faster and more readable (in my opinion), than this: * * for (r = 0; r < nrow; r++) * for (c = 0; c < ncol; c++) { * pixel = image[r * nrow + c]; */ /* routines in this file: alloc_3d_byte_array(nx,ny,nz) alloc_2d_byte_array(nx,ny) read_3d_byte_array(fp,array,nx,ny,nz) read_2d_byte_array(fp,array,nx ,ny) write_3d_byte_array(fp,array,nx,ny,nz) write_2d_byte_array(fp,array,nx,ny) free_3d_byte_array(array) free_2d_byte_array(array) ** and same routines for short, int, and float * * all read/write routines return a 0 if successful and 1 otherwise * * * sample use with hips images: r=rows, c=cols, f = frames * 2D case: * u_char **pic; * pic = alloc_2d_byte_array(r,c); * read_2d_byte_array(stdin, pic1, r,c); * * for (i = 0; i < r; i++) * for (j = 0; j < c; j++) { * want column to vary fastest * * val = pic[i][j]; * } * write_2d_byte_array(stdout, pic2, r,c); * **************************************************** * 3D case: * u_char **pic; * pic = alloc_3d_byte_array(f,r,c); * * read_3d_byte_array(stdin, pic, f,r,c); * * for (i = 0; i < f; i++) * for (j = 0; j < r; j++) * for(k=0; k< c; k++) { * vary col fastest, frame slowest * * val = pic[i][j][k]; */ /***********************************************************************/ /* COPYRIGHT NOTICE *******************************************/ /***********************************************************************/ /* This program is copyright (C) 1990, Regents of the University of California. Anyone may reproduce this software, in whole or in part, provided that: (1) Any copy or redistribution must show the Regents of the University of California, through its Lawrence Berkeley Laboratory, as the source, and must include this notice; (2) Any use of this software must reference this distribu- tion, state that the software copyright is held by the Regents of the University of California, and that the software is used by their permission. It is acknowledged that the U.S. Government has rights to this software under Contract DE-AC03-765F00098 between the U.S. Department of Energy and the University of California. This software is provided as a professional academic contribution for joint exchange. Thus it is experimental, is provided ``as is'', with no warranties of any kind whatsoever, no support, promise of updates, or printed documentation. Bug reports or fixes may be sent to the author, who may or may not act on them as he desires. */ /* Author: <NAME> * Lawrence Berkeley Laboratory * Imaging and Distributed Computing Group * email: <EMAIL> */ #include <stdio.h> #include <sys/types.h> #define Calloc(x,y) (y *)calloc((unsigned)(x), sizeof(y)) #define Fread(a,b,c,d) fread((char *)(a), b, (int)(c), d) #define Fwrite(a,b,c,d) fwrite((char *)(a), b, (int)(c), d) /*********************************/ u_char *** alloc_3d_byte_array(nx,ny,nz) /* in hips terminology: col,row,frame */ int nx,ny,nz; { u_char ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, u_char **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, u_char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, u_char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (nz * ny * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ u_char ** alloc_2d_byte_array(nx,ny) int nx,ny; { u_char **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, u_char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, u_char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < nx; i++) array[i] = array[0] + (ny * i); return(array); } /**********************************/ char ** alloc_2d_char_array(nx,ny) int nx,ny; { char **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < nx; i++) array[i] = array[0] + (ny * i); return(array); } /********************************/ int read_3d_byte_array(fp,array,nx,ny,nz) FILE *fp; u_char ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(u_char), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_byte_array(fp,array,nx ,ny) FILE *fp; u_char **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(u_char), rsize, fp) != rsize) { perror("\n error reading file\n"); return (-1); } return(0); } /*******************************/ int write_3d_byte_array(fp,array,nx,ny,nz) FILE *fp; u_char ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(u_char), size, fp) != size) { perror("\n error writing file\n"); return (-1); } return(0); } /********************************/ int write_2d_byte_array(fp,array,nx ,ny) FILE *fp; u_char **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(u_char), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int free_3d_byte_array(array) u_char ***array; { cfree((char *)array[0][0]); cfree((char *)array[0]); cfree((char *)array); } /*********************************/ int free_2d_byte_array(array) u_char **array; { cfree((char *)array[0]); cfree((char *)array); } /********************************************************/ /* same routines for data type short */ /********************************************************/ short *** alloc_3d_short_array(nx,ny,nz) int nx,ny,nz; { short ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, short **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, short *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, short)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ short ** alloc_2d_short_array(nx,ny) int nx,ny; { short **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, short *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, short)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_short_array(fp,array,nx,ny,nz) FILE *fp; short ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(short), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_short_array(fp,array,nx ,ny) FILE *fp; short **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(short), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_short_array(fp,array,nx,ny,nz) FILE *fp; short ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(short), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_short_array(fp,array,nx ,ny) FILE *fp; short **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(short), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int free_3d_short_array(array) short ***array; { cfree((char *)array[0][0]); cfree((char *)array[0]); cfree((char *)array); } /*********************************/ int free_2d_short_array(array) short **array; { cfree((char *)array[0]); cfree((char *)array); } /****************************************************/ /* int routines */ /**************************************************/ int *** alloc_3d_int_array(nx,ny,nz) int nx,ny,nz; { int ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, int **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, int *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, int)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ int ** alloc_2d_int_array(nx,ny) int nx,ny; { int **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, int *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, int)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_int_array(fp,array,nx,ny,nz) FILE *fp; int ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(int), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_int_array(fp,array,nx ,ny) FILE *fp; int **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(int), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_int_array(fp,array,nx,ny,nz) FILE *fp; int ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(int), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_int_array(fp,array,nx ,ny) FILE *fp; int **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(int), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int free_3d_int_array(array) int ***array; { cfree((char *)array[0][0]); cfree((char *)array[0]); cfree((char *)array); } /*********************************/ int free_2d_int_array(array) int **array; { cfree((char *)array[0]); cfree((char *)array); } /****************************************************/ /* float routines */ /**************************************************/ float *** alloc_3d_float_array(nx,ny,nz) int nx,ny,nz; { float ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, float **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, float *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, float)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ float ** alloc_2d_float_array(nx,ny) int nx,ny; { float **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, float *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, float)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_float_array(fp,array,nx,ny,nz) FILE *fp; float ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(float), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_float_array(fp,array,nx ,ny) FILE *fp; float **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(float), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_float_array(fp,array,nx,ny,nz) FILE *fp; float ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(float), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_float_array(fp,array,nx ,ny) FILE *fp; float **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(float), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int free_3d_float_array(array) float ***array; { cfree((char *)array[0][0]); cfree((char *)array[0]); cfree((char *)array); } /*********************************/ int free_2d_float_array(array) float **array; { cfree((char *)array[0]); cfree((char *)array); } /**************************************************************/ /* long routines */ /**************************************************************/ long *** alloc_3d_long_array(nx,ny,nz) /* in hips terminology: col,row,frame */ int nx,ny,nz; { long ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, long **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, long *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, long)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (nz * ny * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ long ** alloc_2d_long_array(nx,ny) int nx,ny; { long **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, long *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, long)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int free_3d_long_array(array) long ***array; { cfree((char *)array[0][0]); cfree((char *)array[0]); cfree((char *)array); } /*********************************/ int free_2d_long_array(array) long **array; { cfree((char *)array[0]); cfree((char *)array); } /***********************************************************************/ /* all types: all use these if array is cast when calling the routine */ /***********************************************************************/ int free_3d_array(array) char ***array; { cfree(array[0][0]); cfree(array[0]); cfree(array); } /*********************************/ int free_2d_array(array) char **array; { cfree(array[0]); cfree(array); }
matslindh/hiof
rammeverk/patterns/src/main/java/no/lindh/prototypeexample/MyExplicitPrototypeSubClass.java
<filename>rammeverk/patterns/src/main/java/no/lindh/prototypeexample/MyExplicitPrototypeSubClass.java<gh_stars>0 package no.lindh.prototypeexample; public class MyExplicitPrototypeSubClass extends MyExplicitPrototypeConcrete { int subclassValue; MyExplicitPrototypeSubClass() {}; MyExplicitPrototypeSubClass(MyExplicitPrototypeSubClass prototype) { super(prototype); this.subclassValue = prototype.subclassValue; } public MyExplicitPrototypeSubClass cloneMe() { return new MyExplicitPrototypeSubClass(this); } }
vsawchuk/CPDBv2_frontend
test/components/animation/fade-motion.js
import React from 'react'; import { shallow } from 'enzyme'; import { CSSTransition } from 'react-transition-group'; import { withAnimationDisabled } from 'utils/test'; import FadeMotion from 'components/animation/fade-motion'; describe('FadeMotion components', function () { const children = () => <div className='test--sample-div' />; context('animation disabled', function () { it('should render nothing if its show property is false', function () { withAnimationDisabled(() => { const wrapper = shallow( <FadeMotion show={ false } children={ children } /> ); wrapper.find('.test--sample-div').exists().should.be.false(); }); }); it('should render children if its show property is true', function () { withAnimationDisabled(() => { const wrapper = shallow( <FadeMotion show={ true } children={ children } /> ); wrapper.find('.test--sample-div').exists().should.be.true(); }); }); }); context('animation enabled', function () { it('should render Motion component', function () { const wrapper = shallow( <FadeMotion show={ true } children={ children } /> ); wrapper.find(CSSTransition).exists().should.be.true(); }); }); });
phillydorn/CAProject2
app/server/index.js
const Webpack_isomorphic_tools = require('webpack-isomorphic-tools'); const project_base_path = require('path').resolve(__dirname, '..'); global.webpack_isomorphic_tools = new Webpack_isomorphic_tools(require('../../webpack-isomorphic-tools-configuration')) .server(project_base_path, () => { require('./server.js'); });
xiaoxiaosaohuo/clappr
test/playbacks/html5_video_spec.js
import HTML5Video from 'playbacks/html5_video' import Events from 'base/events.js' describe('HTML5Video playback', () => { it('checks if it can play a resource', () => { expect(HTML5Video.canPlay('')).to.be.false expect(HTML5Video.canPlay('resource_without_dots')).to.be.false expect(HTML5Video.canPlay('http://domain.com/video.ogv')).to.be.true expect(HTML5Video.canPlay('http://domain.com/video.ogv?query_string=here')).to.be.true expect(HTML5Video.canPlay('/relative/video.ogv')).to.be.true }) it('checks if it can play a resource with mime-type', () => { expect(HTML5Video.canPlay('resource_without_dots', 'video/ogg; codecs="theora, vorbis"')).to.be.true }) it('does set a valid src to video element', () => { var options = {src: 'http://example.com/dash.ogg'} var playback = new HTML5Video(options) expect(playback._src).to.be.equals('http://example.com/dash.ogg') }) it('starts not ready', () => { var options = {src: 'http://example.com/dash.ogg'} var playback = new HTML5Video(options) expect(playback.isReady).to.be.undefined }) it('can be ready', () => { var options = {src: 'http://example.com/dash.ogg'} var playback = new HTML5Video(options) playback._ready() expect(playback.isReady).to.be.true }) it('triggers PLAYBACK_PLAY_INTENT on play request', () => { var thereWasPlayIntent = false var options = {src: 'http://example.com/dash.ogg'} var playback = new HTML5Video(options) playback.on(Events.PLAYBACK_PLAY_INTENT, function() { thereWasPlayIntent = true }) playback.play() expect(thereWasPlayIntent).to.be.true }) it('setup crossorigin attribute', () => { var options = { src: 'http://example.com/dash.ogg', playback: {crossOrigin: 'use-credentials'} } var playback = new HTML5Video(options) expect(playback.el.crossOrigin).to.be.equal('use-credentials') }) describe('audio resources', () => { it('should be able to play audio resources', () => { expect(HTML5Video.canPlay('http://domain.com/Audio.oga')).to.be.true expect(HTML5Video.canPlay('http://domain.com/Audio.oga?query_string=here')).to.be.true expect(HTML5Video.canPlay('/relative/Audio.oga')).to.be.true expect(HTML5Video.canPlay('/relative/Audio.wav')).to.be.true }) it('should play audio resources on an audio tag', () => { var options = { src: 'http://example.com/dash.oga' } var playback = new HTML5Video(options) expect(playback.tagName).to.be.equal('audio') }) it('should use an audio tag when the audioOnly option is set to true', () => { var options = { src: 'http://example.com/dash.m3u8', playback: { audioOnly: true } } var playback = new HTML5Video(options) expect(playback.tagName).to.be.equal('audio') }) }) })
luisdiasdev/simple-social-network
backend/src/test/java/br/com/agateownz/foodsocial/modules/post/controller/FeedControllerTest.java
package br.com.agateownz.foodsocial.modules.post.controller; import br.com.agateownz.foodsocial.config.ApplicationProfiles; import br.com.agateownz.foodsocial.modules.post.FeedMockBuilders.FeedResponseMock; import br.com.agateownz.foodsocial.modules.post.service.FeedService; import br.com.agateownz.foodsocial.modules.shared.annotations.MockMvcContextConfiguration; import br.com.agateownz.foodsocial.modules.shared.controller.AbstractControllerTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.domain.Pageable; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ActiveProfiles; import static br.com.agateownz.foodsocial.modules.post.FeedMockBuilders.EMPTY_PAGE; import static br.com.agateownz.foodsocial.modules.post.FeedMockBuilders.VALID_PAGE; import static br.com.agateownz.foodsocial.modules.post.FeedMockBuilders.VALID_PAGE_TOTAL_ELEMENTS; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @ActiveProfiles(ApplicationProfiles.TEST) @WebMvcTest(FeedController.class) @MockMvcContextConfiguration @WithMockUser class FeedControllerTest extends AbstractControllerTest { private static final String ENDPOINT = "/feed"; @MockBean private FeedService feedService; @BeforeEach public void setup() { when(feedService.getFeed(any())) .then(invocationOnMock -> { var pageable = invocationOnMock.<Pageable>getArgument(0); if (pageable.getPageNumber() == VALID_PAGE) { return FeedResponseMock.page(pageable); } return FeedResponseMock.empty(pageable); }); } @DisplayName("GET /feed?page= should return feed content if authenticated") @Test public void getFeedSuccess() throws Exception { mockMvc.perform(get(ENDPOINT).param("page", VALID_PAGE.toString())) .andExpect(status().isOk()) .andExpect(jsonPath("$.totalElements", is(VALID_PAGE_TOTAL_ELEMENTS))) .andExpect(jsonPath("$.number", is(VALID_PAGE))) .andExpect(jsonPath("$.content", hasSize(10))); } @DisplayName("GET /feed?page= should return empty feed if not more content available") @Test public void getFeedEmpty() throws Exception { mockMvc.perform(get(ENDPOINT).param("page", EMPTY_PAGE.toString())) .andExpect(status().isOk()) .andExpect(jsonPath("$.totalElements", is(VALID_PAGE_TOTAL_ELEMENTS))) .andExpect(jsonPath("$.number", is(EMPTY_PAGE))) .andExpect(jsonPath("$.content", empty())); } @DisplayName("GET /feed?page= should return 403 if not authenticated") @Test @WithAnonymousUser public void getFeedAuthentication() throws Exception { mockMvc.perform(get(ENDPOINT).param("page", VALID_PAGE.toString())) .andExpect(status().isForbidden()); } }
qinjidong/EasyMPlayer
mplayer/libmpdemux/demux_nsv.c
/* * Nullsoft Streaming Video demuxer * copyright (c) 2004 by <NAME> <<EMAIL>> * Based on A'rpis G2 work * * seeking and PCM audio not yet supported * PCM needs extra audio chunk "miniheader" parsing * * This file is part of MPlayer. * * MPlayer 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. * * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "config.h" #include "mp_msg.h" #include "help_mp.h" #include "stream/stream.h" #include "demuxer.h" #include "stheader.h" typedef struct { float v_pts; int video_pack_no; unsigned int a_format; unsigned int v_format; unsigned char fps; } nsv_priv_t; #define HEADER_SEARCH_SIZE 256000 /** * Seeking still to be implemented */ static void demux_seek_nsv ( demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags ) { // seeking is not yet implemented } static int demux_nsv_fill_buffer ( demuxer_t *demuxer, demux_stream_t *ds ) { unsigned char hdr[17]; // for the extra data unsigned char aux[6]; int i_aux = 0; // videolen = audio chunk length, audiolen = video chunk length int videolen,audiolen; sh_video_t *sh_video = demuxer->video->sh; sh_audio_t *sh_audio = demuxer->audio->sh; nsv_priv_t * priv = demuxer->priv; // if the audio/video chunk has no new header the first 2 bytes will be discarded 0xBEEF // or rather 0xEF 0xBE stream_read(demuxer->stream,hdr,7); if(stream_eof(demuxer->stream)) return 0; // sometimes instead of 0xBEEF as described for the next audio/video chunk we get // a whole new header mp_dbg(MSGT_DEMUX, MSGL_DBG2, "demux_nsv: %08X %08"PRIX64"\n", hdr[0] << 8 | hdr[1], stream_tell(demuxer->stream)); switch(hdr[0]<<8|hdr[1]) { case 0x4E53: if(hdr[2]==0x56 && hdr[3]==0x73){ // NSVs // get the header since there is no more metaheader after the first one // there is no more need to skip that stream_read(demuxer->stream,hdr+7,17-7); stream_read(demuxer->stream,hdr,7); } break; case 0xEFBE: break; default: mp_dbg(MSGT_DEMUX,MSGL_WARN,"demux_nsv: sync lost\n"); break; } if (sh_video) sh_video->pts = priv->v_pts =demuxer->video->pts= priv->video_pack_no * (float)sh_video->frametime; else priv->v_pts = priv->video_pack_no; demuxer->filepos=stream_tell(demuxer->stream); mp_dbg(MSGT_DEMUX,MSGL_DBG2,"demux_nsv: %08X: %02X %02X | %02X %02X %02X | %02X %02X \n", (int)demuxer->filepos, hdr[0],hdr[1],hdr[2],hdr[3],hdr[4],hdr[5],hdr[6]); // read video: videolen=(hdr[2]>>4)|(hdr[3]<<4)|(hdr[4]<<0xC); //check if we got extra data like subtitles here if( (hdr[2]&0x0f) != 0x0 ) { stream_read( demuxer->stream, aux, 6); i_aux = aux[0]|aux[1]<<8; // We skip this extra data stream_skip( demuxer->stream, i_aux ); i_aux+=6; videolen -= i_aux; } // we need to return an empty packet when the // video frame is empty otherwise the stream will fasten up if(sh_video) { if( (hdr[2]&0x0f) != 0x0 ) ds_read_packet(demuxer->video,demuxer->stream,videolen,priv->v_pts,demuxer->filepos-i_aux,0); else ds_read_packet(demuxer->video,demuxer->stream,videolen,priv->v_pts,demuxer->filepos,0); } else stream_skip(demuxer->stream,videolen); // read audio: audiolen=(hdr[5])|(hdr[6]<<8); // we need to return an empty packet when the // audio frame is empty otherwise the stream will fasten up if(sh_audio) { ds_read_packet(demuxer->audio,demuxer->stream,audiolen,priv->v_pts,demuxer->filepos+videolen,0); } else stream_skip(demuxer->stream,audiolen); ++priv->video_pack_no; return 1; } static demuxer_t* demux_open_nsv ( demuxer_t* demuxer ) { // last 2 bytes 17 and 18 are unknown but right after that comes the length unsigned char hdr[17]; int videolen,audiolen; unsigned char buf[10]; sh_video_t *sh_video = NULL; sh_audio_t *sh_audio = NULL; nsv_priv_t * priv = malloc(sizeof(nsv_priv_t)); demuxer->priv=priv; priv->video_pack_no=0; /* disable seeking yet to be fixed*/ demuxer->seekable = 0; stream_read(demuxer->stream,hdr,4); if(stream_eof(demuxer->stream)) return 0; if(hdr[0]==0x4E && hdr[1]==0x53 && hdr[2]==0x56){ // NSV header! if(hdr[3]==0x73){ // NSVs stream_read(demuxer->stream,hdr+4,17-4); } if(hdr[3]==0x66){ // NSVf int len=stream_read_dword_le(demuxer->stream); // TODO: parse out metadata!!!! stream_skip(demuxer->stream,len-8); // NSVs stream_read(demuxer->stream,hdr,17); if (stream_eof(demuxer->stream) || strncmp(hdr, "NSVs", 4)) return 0; } // dummy debug message mp_msg(MSGT_DEMUX,MSGL_V,"demux_nsv: Header: %.12s\n",hdr); // bytes 8-11 audio codec fourcc // PCM fourcc needs extra parsing for every audio chunk, yet to implement if((demuxer->audio->id != -2) && strncmp(hdr+8,"NONE", 4)){//&&strncmp(hdr+8,"VLB ", 4)){ sh_audio = new_sh_audio ( demuxer, 0, NULL ); demuxer->audio->id = 0; demuxer->audio->sh = sh_audio; sh_audio->format=mmioFOURCC(hdr[8],hdr[9],hdr[10],hdr[11]); priv->a_format=mmioFOURCC(hdr[8],hdr[9],hdr[10],hdr[11]); } // store hdr fps priv->fps=hdr[16]; if ((demuxer->video->id != -2) && strncmp(hdr+4,"NONE", 4)) { /* Create a new video stream header */ sh_video = new_sh_video ( demuxer, 0 ); /* Make sure the demuxer knows about the new video stream header * (even though new_sh_video() ought to take care of it) */ demuxer->video->id = 0; demuxer->video->sh = sh_video; // bytes 4-7 video codec fourcc priv->v_format = sh_video->format=mmioFOURCC(hdr[4],hdr[5],hdr[6],hdr[7]); // new video stream! parse header sh_video->disp_w=hdr[12]|(hdr[13]<<8); sh_video->disp_h=hdr[14]|(hdr[15]<<8); sh_video->bih=calloc(1,sizeof(*sh_video->bih)); sh_video->bih->biSize=sizeof(*sh_video->bih); sh_video->bih->biPlanes=1; sh_video->bih->biBitCount=24; sh_video->bih->biWidth=hdr[12]|(hdr[13]<<8); sh_video->bih->biHeight=hdr[14]|(hdr[15]<<8); memcpy(&sh_video->bih->biCompression,hdr+4,4); sh_video->bih->biSizeImage=sh_video->bih->biWidth*sh_video->bih->biHeight*3; // here we search for the correct keyframe // vp6 keyframe is when the 2nd byte of the vp6 header is // 0x36 for VP61 and 0x46 for VP62 if((priv->v_format==mmioFOURCC('V','P','6','1')) || (priv->v_format==mmioFOURCC('V','P','6','2')) || (priv->v_format==mmioFOURCC('V','P','3','1'))) { stream_read(demuxer->stream,buf,10); if (((((priv->v_format>>16) & 0xff) == '6') && ((buf[8]&0x0e)!=0x06)) || ((((priv->v_format>>16) & 0xff) == '3') && (buf[8]!=0x00 || buf[9]!=0x08))) { mp_msg(MSGT_DEMUX,MSGL_V,"demux_nsv: searching %.4s keyframe...\n", (char*)&priv->v_format); while(((((priv->v_format>>16) & 0xff) == '6') && ((buf[8]&0x0e)!=0x06)) || ((((priv->v_format>>16) & 0xff) == '3') && (buf[8]!=0x00 || buf[9]!=0x08))){ mp_msg(MSGT_DEMUX,MSGL_DBG2,"demux_nsv: %.4s block skip.\n", (char*)&priv->v_format); videolen=(buf[2]>>4)|(buf[3]<<4)|(buf[4]<<0xC); audiolen=(buf[5])|(buf[6]<<8); stream_skip(demuxer->stream, videolen+audiolen-3); stream_read(demuxer->stream,buf,10); if(stream_eof(demuxer->stream)) return 0; if(buf[0]==0x4E){ mp_msg(MSGT_DEMUX,MSGL_DBG2,"demux_nsv: Got NSVs block.\n"); stream_skip(demuxer->stream,7); stream_read(demuxer->stream,buf,10); } } } // data starts 10 bytes before current pos but later // we seek 17 backwards stream_skip(demuxer->stream,7); } switch(priv->fps){ case 0x80: sh_video->fps=30; break; case 0x81: sh_video->fps=(float)30000.0/1001.0; break; case 0x82: sh_video->fps=25; break; case 0x83: sh_video->fps=(float)24000.0/1001.0; break; case 0x85: sh_video->fps=(float)15000.0/1001.0; break; case 0x89: sh_video->fps=(float)10000.0/1001.0; break; default: sh_video->fps = (float)priv->fps; } sh_video->frametime = (float)1.0 / (float)sh_video->fps; } } // seek to start of NSV header stream_seek(demuxer->stream,stream_tell(demuxer->stream)-17); return demuxer; } static int nsv_check_file ( demuxer_t* demuxer ) { uint32_t hdr = 0; int i; mp_msg ( MSGT_DEMUX, MSGL_V, "Checking for Nullsoft Streaming Video\n" ); for (i = 0; i < HEADER_SEARCH_SIZE; i++) { uint8_t c = stream_read_char(demuxer->stream); if (stream_eof(demuxer->stream)) return 0; if (hdr == mmioFOURCC('s', 'V', 'S', 'N') || (hdr == mmioFOURCC('f', 'V', 'S', 'N') && !c)) { stream_seek(demuxer->stream,stream_tell(demuxer->stream)-5); return DEMUXER_TYPE_NSV; } hdr = (hdr << 8) | c; } return 0; } static void demux_close_nsv(demuxer_t* demuxer) { nsv_priv_t* priv = demuxer->priv; free(priv); } const demuxer_desc_t demuxer_desc_nsv = { "NullsoftVideo demuxer", "nsv", "Nullsoft Streaming Video", "<NAME>", "nsv and nsa streaming files", DEMUXER_TYPE_NSV, 0, // safe but expensive autodetect nsv_check_file, demux_nsv_fill_buffer, demux_open_nsv, demux_close_nsv, demux_seek_nsv, NULL };
YeWR/PianoRoomReservationSystem
back_end/app.js
<reponame>YeWR/PianoRoomReservationSystem const Koa = require("koa"); const app = module.exports = new Koa(); const xmlParser = require('koa-xml-body'); const bodyParser = require("koa-bodyparser"); const views = require("./views/views"); const views_manage = require("./views/views_manage"); const cors = require("koa2-cors"); let file = require("fs"); let dbconfigFile = "mysqlConfig.json"; let dbconfig = JSON.parse(file.readFileSync(dbconfigFile)); const configPath = "configs.json"; const configs = JSON.parse(file.readFileSync(configPath)); app.keys = configs.app_key; app.use(cors()); app.use(xmlParser({ limit: 2048, xmlOptions: { normalize: true, // Trim whitespace inside text nodes normalizeTags: true, // Transform tags to lowercase explicitArray: false // Only put nodes in array if >1 } })); app.use(bodyParser()); app.use(views.routes()).use(views.allowedMethods()); app.use(views_manage.routes()).use(views_manage.allowedMethods()); if(!module.parent) { app.listen(3000); console.log("listen on 3000"); }
bot-motion/gap_sdk
rtos/openmp/include/omp.h
<reponame>bot-motion/gap_sdk int omp_get_thread_num(void);
DeeStarks/infiniti
application/services/staff.go
<filename>application/services/staff.go<gh_stars>1-10 package services import ( "encoding/json" "fmt" "net/http" "github.com/deestarks/infiniti/adapters/framework/db" "github.com/deestarks/infiniti/application/core" "github.com/deestarks/infiniti/utils" ) type Staff struct { dbPort db.DBPort corePort core.CoreAppPort } type StaffResource struct { Id int `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` Email string `json:"email"` CreatedAt string `json:"created_at"` } type StaffFKResource struct { // Staff with foreign keys Id int `json:"id"` FirstName string `json:"first_name"` LastName string `json:"last_name"` Email string `json:"email"` Group GroupResource `json:"group"` CreatedAt string `json:"created_at"` } // Initialize the staff service func (service *Service) NewStaffService() *Staff { return &Staff{ dbPort: service.dbPort, corePort: service.corePort, } } func (u *Staff) CreateStaff(data map[string]interface{}) (StaffFKResource, error) { adapter := u.dbPort.NewUserAdapter() // First check that all required fields are present required := []string{"email", "password", "first_name", "last_name"} var missing string for _, field := range required { if _, ok := data[field]; !ok { missing = fmt.Sprintf("%s, %s", missing, field) } } if len(missing) > 0 { return StaffFKResource{}, &utils.RequestError{ Code: http.StatusBadRequest, Err: fmt.Errorf("missing required field(s): %s", missing[2:]), } } // Hash the password encyptPass, err := u.corePort.HashPassword(data["password"].(string)) if err != nil { return StaffFKResource{}, &utils.RequestError{ Code: http.StatusInternalServerError, Err: err, } } // Prepare staff data staffData := map[string]interface{}{ "email": data["email"], "password": <PASSWORD>, "first_name": data["first_name"], "last_name": data["last_name"], } // Create the staff staff, err := adapter.Create(staffData) if err != nil { return StaffFKResource{}, &utils.RequestError{ Code: http.StatusBadRequest, Err: err, } } // Add the staff to the group group, err := u.dbPort.NewGroupAdapter().Get("name", "staff") if err != nil { return StaffFKResource{}, &utils.RequestError{ Code: http.StatusInternalServerError, Err: err, } } _, err = u.dbPort.NewUserGroupAdapter().Create(map[string]interface{}{ "user_id": staff.Id, "group_id": group.Id, }) if err != nil { return StaffFKResource{}, &utils.RequestError{ Code: http.StatusInternalServerError, Err: err, } } // Combine and return var ( userRes StaffFKResource groupRes GroupResource ) // User userJson, _ := json.Marshal(staff) json.Unmarshal(userJson, &userRes) // Group groupJson, _ := json.Marshal(group) json.Unmarshal(groupJson, &groupRes) // Combine and return userRes.Group = groupRes return userRes, nil } func (u *Staff) GetStaff(key string, value interface{}) (StaffResource, error) { userAdapter := u.dbPort.NewUserAdapter() staff, err := userAdapter.Get(key, value) if err != nil { return StaffResource{}, &utils.RequestError{ Code: http.StatusBadRequest, Err: fmt.Errorf("staff not found"), } } var staffRes StaffResource staffJson, _ := json.Marshal(staff) json.Unmarshal(staffJson, &staffRes) return staffRes, nil } func (u *Staff) ListStaff() ([]StaffFKResource, error) { userAdapter := u.dbPort.NewUserAdapter() conditions := map[string]interface{}{ "groups.name": "staff", } selector := userAdapter.NewUserCustomSelector(conditions, "users.id", true). Join("user_groups", "user_id", "users", "id", []string{"user_id", "group_id"}). Join("groups", "id", "user_groups", "group_id", []string{"id", "name"}) data, err := selector.Query() if err != nil { return []StaffFKResource{}, &utils.RequestError{ Code: http.StatusInternalServerError, Err: err, } } var res []StaffFKResource for _, user := range data { // Prepare user data userData := map[string]interface{}{ "id": user["users__id"], "email": user["users__email"], "password": <PASSWORD>["<PASSWORD>"], "first_name": user["users__first_name"], "last_name": user["users__last_name"], "created_at": user["users__created_at"], } // Prepare group data groupData := map[string]interface{}{ "id": user["groups__id"], "name": user["groups__name"], } // Combine and return var staffRes StaffFKResource userJson, _ := json.Marshal(userData) json.Unmarshal(userJson, &staffRes) var groupRes GroupResource groupJson, _ := json.Marshal(groupData) json.Unmarshal(groupJson, &groupRes) staffRes.Group = groupRes res = append(res, staffRes) } return res, nil } func (u *Staff) UpdateStaff(key string, value interface{}, data map[string]interface{}) (StaffResource, error) { for _, v := range []string{"id", "created_at"} { // These fields cannot be updated delete(data, v) } userAdapter := u.dbPort.NewUserAdapter() // Confirm staff exists _, err := userAdapter.Get(key, value) if err != nil { return StaffResource{}, &utils.RequestError{ Code: http.StatusBadRequest, Err: fmt.Errorf("staff not found"), } } // Update staff staff, err := userAdapter.Update(key, value, data) if err != nil { return StaffResource{}, &utils.RequestError{ Code: http.StatusBadRequest, Err: err, } } var staffRes StaffResource staffJson, _ := json.Marshal(staff) json.Unmarshal(staffJson, &staffRes) return staffRes, nil } func (u *Staff) DeleteStaff(id int) error { // First check if user exists userAdapter := u.dbPort.NewUserAdapter() _, err := userAdapter.Get("id", id) if err != nil { return &utils.RequestError{ Code: http.StatusBadRequest, Err: fmt.Errorf("staff not found"), } } // Delete all references to the user // 1. "user_permissions" table userPermissionAdapter := u.dbPort.NewUserPermissionsAdapter() userPermissionAdapter.Delete("user_id", id) // 2. "user_groups" table userGroupAdapter := u.dbPort.NewUserGroupAdapter() userGroupAdapter.Delete("user_id", id) // 3. "user_accounts" table userAccountAdapter := u.dbPort.NewAccountAdapter() userAccountAdapter.Delete("user_id", id) // 4. "user_transactions" table userTransactionAdapter := u.dbPort.NewTransactionAdapter() userTransactionAdapter.Delete("user_id", id) // Delete the user userAdapter.Delete("id", id) return nil }
LukaszZachariasz/IUI
back-end/food-order-back/src/main/java/com/foodorderback/controller/ShoppingCartResourceController.java
<filename>back-end/food-order-back/src/main/java/com/foodorderback/controller/ShoppingCartResourceController.java<gh_stars>1-10 package com.foodorderback.controller; import com.foodorderback.model.CartItem; import com.foodorderback.model.Food; import com.foodorderback.model.ShoppingCart; import com.foodorderback.model.User; import com.foodorderback.service.implementations.CartItemService; import com.foodorderback.service.implementations.FoodService; import com.foodorderback.service.implementations.ShoppingCartService; import com.foodorderback.service.implementations.UserManagementService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; import java.util.HashMap; import java.util.List; @RestController @RequestMapping("/cart") public class ShoppingCartResourceController { @Autowired private UserManagementService userManagementService; @Autowired private FoodService foodService; @Autowired private CartItemService cartItemService; @Autowired private ShoppingCartService shoppingCartService; @RequestMapping("/add") public ResponseEntity<?> addItem(@RequestBody HashMap<String, String> mapper, Principal principal) { String foodId = mapper.get("id"); String qty = mapper.get("qty"); User user = userManagementService.findByUsername(principal.getName()); Food food = foodService.findOne(Long.parseLong(foodId)).get(); CartItem cartItem = cartItemService.addFoodToCartItem(food, user, Integer.parseInt(qty)); return new ResponseEntity<>("Food Added Succesfull!", HttpStatus.OK); } @RequestMapping("/getCartItemList") public List<CartItem> getCartItemList(Principal principal) { User user = userManagementService.findByUsername(principal.getName()); ShoppingCart shoppingCart = user.getShoppingCart(); List<CartItem> cartItemList = cartItemService.findByShoppingCart(shoppingCart); shoppingCartService.updateShoppingCart(shoppingCart); return cartItemList; } @RequestMapping("/getShoppingCart") public ShoppingCart getShoppingCart(Principal principal) { User user = userManagementService.findByUsername(principal.getName()); ShoppingCart shoppingCart = user.getShoppingCart(); shoppingCartService.updateShoppingCart(shoppingCart); return shoppingCart; } @RequestMapping("/removeItem") public ResponseEntity<?> removeItem(@RequestBody String id) { cartItemService.removeCartItem(cartItemService.findById(Long.parseLong(id))); return new ResponseEntity<>("Food Removed Succesfull!", HttpStatus.OK); } @RequestMapping("/updateCartItem") public ResponseEntity<?> updateCartItem(@RequestBody HashMap<String, String> mapper) { String cartItemId = mapper.get("cartItemId"); String qty = mapper.get("qty"); CartItem cartItem = cartItemService.findById(Long.parseLong(cartItemId)); cartItem.setQty(Integer.parseInt(qty)); cartItemService.updateCartItem(cartItem); return new ResponseEntity<>("Food updated Succesfull!", HttpStatus.OK); } }
kmewhort/git.legal-codeclimate
spec/services/php_composer_lock/parse_spec.rb
<reponame>kmewhort/git.legal-codeclimate require 'rails_helper' describe Service::PhpComposerLock::Parse do let(:package_json_path) { Rails.root.join('spec','fixtures','composer_lock','composer.lock') } let(:file_contents) { IO.read(package_json_path) } subject { Service::PhpComposerLock::Parse.call(file_contents: file_contents) } it "finds the libraries listed in the composer.lock" do expect(subject.count).to eq 7 end it "finds the line number where a gem is reported" do expect(subject[0][:name]).to eq 'bower-asset/jquery' expect(subject[0][:line]).to eq 10 end end
yufeiwang63/ROLL
scripts/test_multiworld.py
<filename>scripts/test_multiworld.py<gh_stars>10-100 import multiworld import gym import cv2 from multiworld.envs.mujoco.cameras import ( sawyer_init_camera_full, sawyer_init_camera_zoomed_in, sawyer_pick_and_place_camera, sawyer_door_env_camera_v0 ) from multiworld.core.image_env import ImageEnv import copy import numpy as np def show_obs(normalized_img_vec_, imsize=48, name='img'): print(name) normalized_img_vec = copy.deepcopy(normalized_img_vec_) img = (normalized_img_vec * 255).astype(np.uint8) img = img.reshape(3, imsize, imsize).transpose() img = img[::-1, :, ::-1] cv2.imshow(name, img) cv2.waitKey() if __name__ == '__main__': # env_name = 'SawyerDoorHookResetFreeEnv-v1' env_name = 'SawyerPushHurdle-v0' # env_name = 'SawyerPushNIPSFull-v0' # env_name = 'SawyerPushNIPSEasy-v0' # env_name = 'SawyerPushHurdleResetFreeEnv-v0' multiworld.register_all_envs() imsize = 48 # presampled_goals_path = 'data/local/goals/SawyerDoorHookResetFreeEnv-v1-goal.npy' # presampled_goals_path = 'data/local/goals/SawyerPickupEnvYZEasy-v0-goal-500.npy' # presampled_goals = np.load(presampled_goals_path, allow_pickle=True).item() env = ImageEnv( env, imsize, init_camera=sawyer_init_camera_zoomed_in, transpose=True, normalize=True, presampled_goals=None ) print(env.action_space.low) print(env.action_space.high) for i in range(50): o = env.reset() for t in range(50): print(t) action = env.action_space.sample() s, r, _, _ = env.step(action) img = s['image_observation'] show_obs(img, imsize=imsize, name=env_name)
radishengine/drowsy
mac/filetypes/open_VWPR.js
define(function() { 'use strict'; function open(item) { item.getSubitem(/VWSC/) .then(function(vwsc) { vwsc.populate() .then(function() { var testScreen = document.createElement('CANVAS'); testScreen.width = 640; testScreen.height = 400; var ctx = testScreen.getContext('2d'); var playHead = testScreen.playHead = vwsc.playHeadFactory.create(); var sprites = playHead.sprites; testScreen.playHead.eventTarget = testScreen; testScreen.addEventListener('enter-frame', function() { ctx.clearRect(0, 0, 640, 480); for (var i = 0; i < sprites.length; i++) { if (!sprites[i].cast) continue; ctx.fillStyle = 'rgb(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ')'; ctx.fillRect(sprites[i].top, sprites[i].left, sprites[i].width, sprites[i].height); } }); item.addItem(testScreen); testScreen.playHead.next(); }); }); } return open; });
sergey-v-sedov/jmix-docs
content/modules/ldap/examples/ex1/src/main/java/ldap/ex1/service/MyUserSynchronizationStrategy.java
<reponame>sergey-v-sedov/jmix-docs package ldap.ex1.service; import io.jmix.ldap.userdetails.AbstractLdapUserDetailsSynchronizationStrategy; import ldap.ex1.entity.User; import org.springframework.ldap.core.DirContextOperations; import org.springframework.stereotype.Component; // tag::strategy[] @Component("ldap_MyUserSynchronizationStrategy") public class MyUserSynchronizationStrategy extends AbstractLdapUserDetailsSynchronizationStrategy<User> { @Override protected Class<User> getUserClass() { return User.class; } @Override protected void mapUserDetailsAttributes(User userDetails, DirContextOperations ctx) { userDetails.setFirstName(ctx.getStringAttribute("givenName")); userDetails.setLastName(ctx.getStringAttribute("sn")); } } // end::strategy[]
Jignesh1996/bcmd-web
app/testing/test_bcmd_model.py
from bayescmd.bcmdModel.bcmd_model import ModelBCMD from bayescmd.util import * from nose.tools import assert_true, assert_equal import numpy.testing as np_test import filecmp import os BASEDIR = findBaseDir('bcmd-web', verbose=True) print("BASEDIR:\t%s" % os.path.abspath(BASEDIR)) TESTDIR = os.path.abspath(os.path.dirname(__file__)) class testDefault: def setUp(self): self.input_file = os.path.join(TESTDIR, 'test_files', 'test.input') self.actual = os.path.join(TESTDIR, 'test_files', 'rc_actual.out') self.times = list(range(0, 30, 5)) self.inputs = {"names": ['V'], "values": [ [1], [0], [-1], [0], [1] ] } self.params = None def tearDown(self): try: os.remove(self.model.input_file) except (FileNotFoundError, TypeError): pass try: os.remove(self.model.output_coarse) except (FileNotFoundError, TypeError): pass try: os.remove(self.model.output_detail) except (FileNotFoundError, TypeError): pass def test_create_input_and_run_from_file(self): """ Check that a full model run will create the correct input file and output data. Uses file creation as input. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, input_file=self.input_file, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=True, suppress=True, basedir=BASEDIR) self.model.write_default_input() self.model.run_from_file() assert_true(filecmp.cmp(self.model.output_coarse, self.actual), msg='Coarse output files do not match actual.') def test_output_dict_from_file(self): """ Check that an output file will be read and processed correctly. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, input_file=None, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=False, suppress=True, basedir=BASEDIR) self.model.write_default_input() self.model.run_from_file() vc_test = self.model.output_parse()['Vc'] np_test.assert_almost_equal(vc_test, [0.99326201853524232, 0.0066925479138209504, -0.99321690724584777, -0.0066922439555526904, 0.99321692632751313], err_msg='Vc Output not the same') def test_output_dict_from_buffer(self): """ Check that an output file will be read and processed correctly. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, input_file=None, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=False, suppress=True, basedir=BASEDIR) self.model.create_default_input() self.model.run_from_buffer() vc_test = self.model.output_parse()['Vc'] np_test.assert_almost_equal(vc_test, [0.99326201853524232, 0.0066925479138209504, -0.99321690724584777, -0.0066922439555526904, 0.99321692632751313], err_msg='Vc Output not the same') def test_create_input_and_run_from_buffer(self): """ Check that a full model run will create the correct input file and output data. Uses StringIO as model input and output. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, input_file=None, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=True, suppress=True, basedir=BASEDIR) self.model.create_default_input() result = self.model.run_from_buffer() with open(self.actual) as f_actual: actual_content = f_actual.read() assert_equal(result.stdout.decode(), actual_content) class testInitialised: def setUp(self): self.times = [0, 2, 4, 12, 15, 25] self.inputs = {"names": ['V'], "values": [ [5], [0], [15], [-8], [25], [0] ] } self.params = {"C": 0.0121805, "R": 1000, "Vc": 0} self.outputs = ['Vc'] def tearDown(self): #try: # os.remove(self.model.output_coarse) #except (FileNotFoundError, TypeError): # pass #try: # os.remove(self.model.input_file) # except (FileNotFoundError, TypeError): # pass try: os.remove(self.model.output_detail) except (FileNotFoundError, TypeError): pass def test_init_output_from_buffer(self): """ Check that an output file will be read and processed correctly. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, outputs=self.outputs, input_file=None, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=False, suppress=True, basedir=BASEDIR) self.model.create_initialised_input() result = self.model.run_from_buffer() vc_test = self.model.output_parse() out = self.outputs[0] np_test.assert_almost_equal(vc_test[out], [5, 4.2428747349702212, 5.8717730134973181, -0.80728597087174025, 4.8266677606599329, 2.1237257717723548], err_msg='Vc Output not the same') def test_init_output_from_file(self): """ Check that an output file will be read and processed correctly. """ self.model = ModelBCMD('rc', inputs=self.inputs, params=self.params, times=self.times, outputs=self.outputs, input_file=None, create_input=True, testing=True, workdir=os.path.join(TESTDIR, 'test_files'), debug=False, suppress=True, basedir=BASEDIR) self.model.write_initialised_input() result = self.model.run_from_file() vc_test = self.model.output_parse() out = self.outputs[0] np_test.assert_almost_equal(vc_test[out], [5, 4.2428747349702212, 5.8717730134973181, -0.80728597087174025, 4.8266677606599329, 2.1237257717723548], err_msg='Vc Output not the same')
mrbartrns/programmers-algorithm
lv1/whitespace.py
def solution(s): answer = '' index = 0 for i in range(len(s)): if index % 2 == 0: answer += s[i].upper() else: answer += s[i].lower() if s[i] == ' ': index = 0 else: index += 1 return answer print(solution('name hi'))
Li-YangZhong/professional-javascript-for-web-developers
Chapter11PromisesAndAsyncFunctions/Promises/PromiseChainingAndComposition/ParallelPromiseCompositionWithPromiseallAndPromiserace/Promiserace/PromiseraceExample02.js
// Resolve occurs first, reject in timeout ignored let p1 = Promise.race([ Promise.resolve(3), new Promise((resolve, reject) => setTimeout(reject, 1000)) ]); setTimeout(console.log, 0, p1); // Promise <resolved>: 3 // Reject occurs first, resolve in timeout ignored let p2 = Promise.race([ Promise.reject(4), new Promise((resolve, reject) => setTimeout(resolve, 1000)) ]); setTimeout(console.log, 0, p2); // Promise <rejected>: 4 // Iterator order is the tiebreaker for settling order let p3 = Promise.race([ Promise.resolve(5), Promise.resolve(6), Promise.resolve(7) ]); setTimeout(console.log, 0, p3); // Promise <resolved>: 5
chouer19/enjoyDriving
include/ibeosdk/database/DbInterfaceT.hpp
<filename>include/ibeosdk/database/DbInterfaceT.hpp //====================================================================== /*! \file DbInterfaceT.hpp * * \copydoc Copyright * \author <NAME> (kb) * \date Feb 9, 2016 *///------------------------------------------------------------------- //====================================================================== #ifndef DBINTERFACET_HPP_SEEN #define DBINTERFACET_HPP_SEEN //====================================================================== #include <ibeosdk/database/DbConnection.hpp> #include <ibeosdk/database/DbQueryOptions.hpp> #include <ibeosdk/database/DbQueryIterator.hpp> #include <ibeosdk/database/CollectionName.hpp> #include <ibeosdk/database/MongoDbConnection.hpp> #include <ibeosdk/database/DatabaseException.hpp> //====================================================================== namespace ibeosdk { namespace dbaccess { //====================================================================== /*!\class DbInterfaceT * \brief Templated virtual class to warp some query functionality from the mongo-cxx-driver * with different object types. * \tparam DataType Type of the data interfaced by this class. * \author <NAME> (kb) * \version 0.1 * \date Feb 9, 2016 *///------------------------------------------------------------------ template<class DataType> class DbInterfaceT { public: //======================================== /*!\brief Boost shared pointer for DbInterfaceT *///------------------------------------- typedef boost::shared_ptr<DbInterfaceT> DbIfPtr; public: DbInterfaceT(const DbConPtr dbConnection, const CollectionName& collectionName) : m_dbConnection(dbConnection), m_collectionName(collectionName) {} //======================================== /*!\brief Default destructor. *///------------------------------------- virtual ~DbInterfaceT() {} public: virtual DbQueryIterator<DataType> queryData() { DbQueryOptions options; return queryData(options); } //======================================== /*!\brief Perform a query on a database. * * Return first item matching query. * * \param[in] options Specified DbQueryOptions. * \param[out] data Resulting DataType with information received * from the database. * \return \c true if query was successful, \c false otherwise. *///------------------------------------- virtual bool queryOne(const DbQueryOptions& options, DataType& data) = 0; //======================================== /*!\brief Perform a query on a database. * * Return first item matching query. * * \param[in] query Query string. * \param[out] data Resulting DataType with information received * from the database. * \return \c true if query was successful, \c false otherwise. *///------------------------------------- virtual bool queryOne(const std::string& query, DataType& data) = 0; //======================================== /*!\brief Perform a query on a database. * * \param[in] options Specified DbQueryOptions. * \return Iterator to all items matching specified query. *///------------------------------------- virtual DbQueryIterator<DataType> queryData(const DbQueryOptions& options) = 0; //======================================== /*!\brief Perform a query on a database. * * \param[in] options Specified DbQueryOptions. * \return mongo::DBClientcursor (boost shared pointer) to all items * matching specified query. *///------------------------------------- virtual MongoCursorPtr fastQuery(const DbQueryOptions& options = DbQueryOptions()) = 0; //======================================== /*!\brief Perform a query on a database to count the number of result elements. * * \param[in] options Specified DbQueryOptions. * \return Number of items matching specified query. *///------------------------------------- virtual UINT64 countData(const DbQueryOptions& options) = 0; //public: // virtual bool createIndex(const std::string& fullDBName, const std::string& fieldname) { return false; }; public: //======================================== /*!\brief Returns status of the database connection. * * \return \c true if connection to database is established * \c false otherwise. *///------------------------------------- bool isConnected() const { return m_dbConnection->isConnected(); } //======================================== /*!\brief Returns connection properties. * * \return DbConnection::ConnectionProperties *///------------------------------------- DbConnection::ConnectionProperties& getConnectionProperties() { return m_dbConnection->getConnectionProperties(); } //======================================== /*!\brief Returns connection properties. * * \return DbConnection::ConnectionProperties *///------------------------------------- const DbConnection::ConnectionProperties& getConnectionProperties() const { return m_dbConnection->getConnectionProperties(); } //======================================== /*!\brief Returns the database connection. * * \return DbConPtr shared pointer to DbConnection. *///------------------------------------- const DbConPtr getDbConnection() const { return m_dbConnection; } //======================================== /*!\brief Returns the collection name this interface points to. * * \return Collection as a CollectionName. *///------------------------------------- const CollectionName& getCollectionName() const { return m_collectionName; } protected: //======================================== /*!\brief Holds the database connection. *///------------------------------------- const DbConPtr m_dbConnection; //======================================== /*!\brief Holds the collection this interface points to. *///------------------------------------- CollectionName m_collectionName; }; // class DbInterfaceT //====================================================================== } // namespace dbaccess } // namespace ibeosdk //====================================================================== #endif // DBINTERFACET_HPP_SEEN //======================================================================
liuhpleon/RubyLCPractice
leetcode/256_Paint_House.rb
# Leetcode 256 class PaintHouse def min_cost(costs) return 0 if costs.empty? res = costs.shift costs.each do |cost| next_res = [] next_res[0] = cost[0] + [res[1], res[2]].min next_res[1] = cost[1] + [res[0], res[2]].min next_res[2] = cost[2] + [res[0], res[1]].min res = next_res end res.min end end
timja/ecutest-plugin
src/test/java/de/tracetronic/jenkins/plugins/ecutest/util/EnvUtilTest.java
/* * Copyright (c) 2015-2019 TraceTronic GmbH * * SPDX-License-Identifier: BSD-3-Clause */ package de.tracetronic.jenkins.plugins.ecutest.util; import hudson.EnvVars; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Unit tests for {@link EnvUtil}. * * @author <NAME> <<EMAIL>> */ public class EnvUtilTest { @Test public void testDefaultIfEmptyEnvVar() { final String expanded = EnvUtil.expandEnvVar("", new EnvVars(), "default"); assertEquals("Should expand to default value if empty", "default", expanded); } @Test public void testDefaultIfNullEnvVar() { final String expanded = EnvUtil.expandEnvVar(null, new EnvVars(), "default"); assertEquals("Should expand to default value if null", "default", expanded); } @Test public void testExpandedEnvVar() { final String expanded = EnvUtil.expandEnvVar("${test}", new EnvVars("test", "expandedTest"), "default"); assertEquals("Should expand using env vars", "expandedTest", expanded); } @Test public void testMultipleExpandedEnvVar() { final String expanded = EnvUtil.expandEnvVar("${test}${var}", new EnvVars("test", "expandedTest", "var", "123"), "default"); assertEquals("Should expand using multiple env vars", "expandedTest123", expanded); } }
Alexander3006/TBQForms_2.0
TBQForms_client/src/Components/Footer.js
<filename>TBQForms_client/src/Components/Footer.js import React from 'react'; import '../styles/footer.css'; class Footer extends React.Component { constructor(props) { super(props); } render() { return ( <div className="footer"> <a className = "footer_link" href="">About Us</a> <a className = "footer_link" href="">License</a> <a className = "footer_link" href="">Authors</a> </div> ); } } export default Footer;
prafullkotecha/waltz
waltz-ng/client/user/routes.js
<filename>waltz-ng/client/user/routes.js /* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ import activeUsersView from "./active-users"; import userManagementView from "./user-management"; import userLogView from "./user-log"; const base = { url: 'user' }; const activeUsersState = { url: '/active-users', views: {'content@': activeUsersView } }; const userManagementState = { url: '/management', views: {'content@': userManagementView } }; const userLogState = { url: '/log', views: {'content@': userLogView } }; function configureStates(stateProvider) { stateProvider .state('main.user', base) .state('main.user.active', activeUsersState) .state('main.user.management', userManagementState) .state('main.user.log', userLogState); } configureStates.$inject = ['$stateProvider']; export default configureStates;
dev-senior-com-br/senior-hcm-java
src/main/java/br/com/senior/hcm/payroll/pojos/Actingtype.java
/* * Folha de Pagamento * HCM - Folha de pagamento * * * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package br.com.senior.hcm.payroll.pojos; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import br.com.senior.hcm.payroll.pojos.AdditionalPaymentType; import br.com.senior.hcm.payroll.pojos.JobActingType; import java.io.IOException; /** * Actingtype */ public class Actingtype { @SerializedName("code") private Integer code = null; @SerializedName("goal") private String goal = null; @SerializedName("additionalPaymentType") private AdditionalPaymentType additionalPaymentType = null; @SerializedName("additionalPaymentPercentage") private Double additionalPaymentPercentage = null; @SerializedName("name") private String name = null; @SerializedName("consistCharacteristic") private Boolean consistCharacteristic = null; @SerializedName("jobActingType") private JobActingType jobActingType = null; @SerializedName("id") private String id = null; @SerializedName("mainhistory") private Boolean mainhistory = null; @SerializedName("headCountControl") private Boolean headCountControl = null; public Actingtype code(Integer code) { this.code = code; return this; } /** * Código do tipo de atuação * @return code **/ @ApiModelProperty(required = true, value = "Código do tipo de atuação") public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Actingtype goal(String goal) { this.goal = goal; return this; } /** * Objetivo * @return goal **/ @ApiModelProperty(required = true, value = "Objetivo") public String getGoal() { return goal; } public void setGoal(String goal) { this.goal = goal; } public Actingtype additionalPaymentType(AdditionalPaymentType additionalPaymentType) { this.additionalPaymentType = additionalPaymentType; return this; } /** * Get additionalPaymentType * @return additionalPaymentType **/ @ApiModelProperty(required = true, value = "") public AdditionalPaymentType getAdditionalPaymentType() { return additionalPaymentType; } public void setAdditionalPaymentType(AdditionalPaymentType additionalPaymentType) { this.additionalPaymentType = additionalPaymentType; } public Actingtype additionalPaymentPercentage(Double additionalPaymentPercentage) { this.additionalPaymentPercentage = additionalPaymentPercentage; return this; } /** * Porcentagem do pagamento do posto adicional * @return additionalPaymentPercentage **/ @ApiModelProperty(required = true, value = "Porcentagem do pagamento do posto adicional") public Double getAdditionalPaymentPercentage() { return additionalPaymentPercentage; } public void setAdditionalPaymentPercentage(Double additionalPaymentPercentage) { this.additionalPaymentPercentage = additionalPaymentPercentage; } public Actingtype name(String name) { this.name = name; return this; } /** * Descrição do tipo de atuação * @return name **/ @ApiModelProperty(required = true, value = "Descrição do tipo de atuação") public String getName() { return name; } public void setName(String name) { this.name = name; } public Actingtype consistCharacteristic(Boolean consistCharacteristic) { this.consistCharacteristic = consistCharacteristic; return this; } /** * Consistir característica? * @return consistCharacteristic **/ @ApiModelProperty(required = true, value = "Consistir característica?") public Boolean isConsistCharacteristic() { return consistCharacteristic; } public void setConsistCharacteristic(Boolean consistCharacteristic) { this.consistCharacteristic = consistCharacteristic; } public Actingtype jobActingType(JobActingType jobActingType) { this.jobActingType = jobActingType; return this; } /** * Get jobActingType * @return jobActingType **/ @ApiModelProperty(required = true, value = "") public JobActingType getJobActingType() { return jobActingType; } public void setJobActingType(JobActingType jobActingType) { this.jobActingType = jobActingType; } public Actingtype id(String id) { this.id = id; return this; } /** * Id do tipo de atuação * @return id **/ @ApiModelProperty(value = "Id do tipo de atuação") public String getId() { return id; } public void setId(String id) { this.id = id; } public Actingtype mainhistory(Boolean mainhistory) { this.mainhistory = mainhistory; return this; } /** * Histórico principal? * @return mainhistory **/ @ApiModelProperty(required = true, value = "Histórico principal?") public Boolean isMainhistory() { return mainhistory; } public void setMainhistory(Boolean mainhistory) { this.mainhistory = mainhistory; } public Actingtype headCountControl(Boolean headCountControl) { this.headCountControl = headCountControl; return this; } /** * Indica se atuações deste tipo contrabilizam uma vaga no quadro de lotação * @return headCountControl **/ @ApiModelProperty(required = true, value = "Indica se atuações deste tipo contrabilizam uma vaga no quadro de lotação") public Boolean isHeadCountControl() { return headCountControl; } public void setHeadCountControl(Boolean headCountControl) { this.headCountControl = headCountControl; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Actingtype actingtype = (Actingtype) o; return Objects.equals(this.code, actingtype.code) && Objects.equals(this.goal, actingtype.goal) && Objects.equals(this.additionalPaymentType, actingtype.additionalPaymentType) && Objects.equals(this.additionalPaymentPercentage, actingtype.additionalPaymentPercentage) && Objects.equals(this.name, actingtype.name) && Objects.equals(this.consistCharacteristic, actingtype.consistCharacteristic) && Objects.equals(this.jobActingType, actingtype.jobActingType) && Objects.equals(this.id, actingtype.id) && Objects.equals(this.mainhistory, actingtype.mainhistory) && Objects.equals(this.headCountControl, actingtype.headCountControl); } @Override public int hashCode() { return Objects.hash(code, goal, additionalPaymentType, additionalPaymentPercentage, name, consistCharacteristic, jobActingType, id, mainhistory, headCountControl); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Actingtype {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" goal: ").append(toIndentedString(goal)).append("\n"); sb.append(" additionalPaymentType: ").append(toIndentedString(additionalPaymentType)).append("\n"); sb.append(" additionalPaymentPercentage: ").append(toIndentedString(additionalPaymentPercentage)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" consistCharacteristic: ").append(toIndentedString(consistCharacteristic)).append("\n"); sb.append(" jobActingType: ").append(toIndentedString(jobActingType)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" mainhistory: ").append(toIndentedString(mainhistory)).append("\n"); sb.append(" headCountControl: ").append(toIndentedString(headCountControl)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
platform/main/server-4u/com/cyc/cycjava/cycl/inference/harness/forward_rule_propagation.java
<reponame>TeamSPoon/CYC_JRTL_with_CommonLisp_OLD package com.cyc.cycjava.cycl.inference.harness; import static com.cyc.cycjava.cycl.constant_handles.reader_make_constant_shell; import static com.cyc.cycjava.cycl.el_utilities.literal_arg0; import static com.cyc.cycjava.cycl.el_utilities.literal_predicate; import static com.cyc.cycjava.cycl.el_utilities.replace_formula_arg; import static com.cyc.cycjava.cycl.el_utilities.sefify; import static com.cyc.cycjava.cycl.subl_macro_promotions.$catch_error_message_target$; import static com.cyc.cycjava.cycl.utilities_macros.$current_forward_problem_store$; import static com.cyc.cycjava.cycl.utilities_macros.$is_noting_progressP$; import static com.cyc.cycjava.cycl.utilities_macros.$last_percent_progress_index$; import static com.cyc.cycjava.cycl.utilities_macros.$last_percent_progress_prediction$; import static com.cyc.cycjava.cycl.utilities_macros.$noting_progress_delayed_mode_seconds$; import static com.cyc.cycjava.cycl.utilities_macros.$noting_progress_delayed_mode_string$; import static com.cyc.cycjava.cycl.utilities_macros.$percent_progress_start_time$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_count$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_elapsed_seconds_for_notification$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_last_pacification_time$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_notification_count$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_pacifications_since_last_nl$; import static com.cyc.cycjava.cycl.utilities_macros.$progress_start_time$; import static com.cyc.cycjava.cycl.utilities_macros.$silent_progressP$; import static com.cyc.cycjava.cycl.utilities_macros.$suppress_all_progress_faster_than_seconds$; import static com.cyc.cycjava.cycl.utilities_macros.$within_noting_percent_progress$; import static com.cyc.cycjava.cycl.utilities_macros.note_percent_progress; import static com.cyc.cycjava.cycl.utilities_macros.noting_percent_progress_postamble; import static com.cyc.cycjava.cycl.utilities_macros.noting_percent_progress_preamble; import static com.cyc.cycjava.cycl.utilities_macros.noting_progress_postamble; import static com.cyc.cycjava.cycl.utilities_macros.noting_progress_preamble; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.ConsesLow.cons; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.ConsesLow.list; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Eval.eval; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Numbers.add; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Numbers.subtract; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.PrintLow.format; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.cconcatenate; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.find; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.find_if; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.length; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.nreverse; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Sequences.remove_if; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Symbols.symbol_function; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Threads.$is_thread_performing_cleanupP$; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Time.get_universal_time; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Values.getValuesAsVector; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Values.nth_value_step_1; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Values.nth_value_step_2; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Values.restoreValuesFromVector; import static com.cyc.tool.subl.jrtl.nativeCode.subLisp.Values.values; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeBoolean; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeKeyword; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeString; import static com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObjectFactory.makeSymbol; import static com.cyc.tool.subl.util.SubLFiles.declareFunction; import static com.cyc.tool.subl.util.SubLFiles.deflexical; import com.cyc.cycjava.cycl.V10; import com.cyc.cycjava.cycl.arguments; import com.cyc.cycjava.cycl.assertion_handles; import com.cyc.cycjava.cycl.assertion_utilities; import com.cyc.cycjava.cycl.assertions_high; import com.cyc.cycjava.cycl.assertions_interface; import com.cyc.cycjava.cycl.clauses; import com.cyc.cycjava.cycl.format_cycl_expression; import com.cyc.cycjava.cycl.format_nil; import com.cyc.cycjava.cycl.hl_supports; import com.cyc.cycjava.cycl.iteration; import com.cyc.cycjava.cycl.kb_accessors; import com.cyc.cycjava.cycl.kb_control_vars; import com.cyc.cycjava.cycl.kb_hl_support_handles; import com.cyc.cycjava.cycl.kb_hl_supports_high; import com.cyc.cycjava.cycl.kb_utilities; import com.cyc.cycjava.cycl.list_utilities; import com.cyc.cycjava.cycl.queues; import com.cyc.cycjava.cycl.subl_promotions; import com.cyc.cycjava.cycl.variables; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Errors; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.Mapping; import com.cyc.tool.subl.jrtl.nativeCode.subLisp.SubLThread; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLList; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLObject; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLProcess; import com.cyc.tool.subl.jrtl.nativeCode.type.core.SubLString; import com.cyc.tool.subl.jrtl.nativeCode.type.symbol.SubLSymbol; import com.cyc.tool.subl.util.SubLFile; import com.cyc.tool.subl.util.SubLTranslatedFile; public final class forward_rule_propagation extends SubLTranslatedFile implements V10 { public static final SubLFile me = new forward_rule_propagation(); public static final String myName = "com.cyc.cycjava_2.cycl.inference.harness.forward_rule_propagation"; // deflexical public static final SubLSymbol $forward_trigger_lazy_iteration_threshold$ = makeSymbol("*FORWARD-TRIGGER-LAZY-ITERATION-THRESHOLD*"); private static final SubLObject $$InferencePSC = reader_make_constant_shell(makeString("InferencePSC")); private static final SubLSymbol $sym1$RULE_ASSERTION_ = makeSymbol("RULE-ASSERTION?"); private static final SubLString $str3$Triggering_rule_against__A__S_sup = makeString("Triggering rule against ~A ~S support~:p: ~A"); private static final SubLSymbol $sym4$_APPEND_STACK_TRACES_TO_ERROR_MESSAGES__ = makeSymbol("*APPEND-STACK-TRACES-TO-ERROR-MESSAGES?*"); private static final SubLList $list5 = list(makeSymbol("CSETQ"), makeSymbol("*APPEND-STACK-TRACES-TO-ERROR-MESSAGES?*"), NIL); private static final SubLString $str8$_A = makeString("~A"); private static final SubLString $str12$time_to_use_a_real_query_iterator = makeString("time to use a real query iterator here"); private static final SubLString $$$Determining_trigger_GAFs_for_ = makeString("Determining trigger GAFs for "); private static final SubLList $list14 = list(makeKeyword("PRODUCTIVITY-LIMIT"), makeKeyword("POSITIVE-INFINITY"), makeKeyword("RETURN"), makeKeyword("SUPPORTS")); private static final SubLSymbol FIRST_GAF_IN_SUPPORTS = makeSymbol("FIRST-GAF-IN-SUPPORTS"); private static final SubLSymbol KBEQ = makeSymbol("KBEQ"); private static final SubLList $list20 = list(makeKeyword("BROWSABLE?"), T, makeKeyword("MAX-STEP"), FIVE_INTEGER, makeKeyword("PRODUCTIVITY-LIMIT"), makeKeyword("POSITIVE-INFINITY"), makeKeyword("ALLOWED-MODULES"), list(makeKeyword("NOT"), list(makeKeyword("OR"), list(makeKeyword("MODULE-TYPE"), makeKeyword("REMOVAL-CONJUNCTIVE")), $JOIN, makeKeyword("REMOVAL-PRED-UNBOUND")))); private static final SubLSymbol TACTIC_HL_MODULE_NAME = makeSymbol("TACTIC-HL-MODULE-NAME"); private static final SubLString $str24$Can_t_determine_trigger_asent_for = makeString("Can't determine trigger asent for rule with split antecedent: ~S"); private static final SubLString $str25$Can_t_determine_trigger_asent_for = makeString("Can't determine trigger asent for rule: ~S"); private static final SubLString $str26$Can_t_create_inference_to_determi = makeString("Can't create inference to determine trigger asent for rule: ~S"); private static final SubLObject $$evaluate = reader_make_constant_shell(makeString("evaluate")); private static final SubLObject $$BaseKB = reader_make_constant_shell(makeString("BaseKB")); private static final SubLSymbol $sym30$EQUALS_EL_ = makeSymbol("EQUALS-EL?"); private static final SubLSymbol $sym31$GAF_ASSERTION_ = makeSymbol("GAF-ASSERTION?"); private static final SubLList $list34 = list(reader_make_constant_shell(makeString("isa")), reader_make_constant_shell(makeString("quotedIsa"))); public static SubLObject forward_propagate_rule_via_trigger_gafs(final SubLObject rule, SubLObject propagation_mt) { if (propagation_mt == UNPROVIDED) { propagation_mt = $$InferencePSC; } final SubLThread thread = SubLProcess.currentSubLThread(); assert NIL != assertions_high.rule_assertionP(rule) : "assertions_high.rule_assertionP(rule) " + "CommonSymbols.NIL != assertions_high.rule_assertionP(rule) " + rule; possibly_change_assertion_direction_to_forward_without_repropagation(rule); final SubLObject rule_string = format_cycl_expression.format_cycl_expression_to_string(assertions_high.assertion_ist_formula(rule), UNPROVIDED); final SubLObject before_dependents = assertions_high.assertion_dependent_count(rule); SubLObject sofar = ZERO_INTEGER; thread.resetMultipleValues(); final SubLObject iterator = new_forward_rule_trigger_gaf_iterator(rule, propagation_mt); final SubLObject total = thread.secondMultipleValue(); final SubLObject focal_asent = thread.thirdMultipleValue(); thread.resetMultipleValues(); assert NIL != subl_promotions.non_negative_integer_p(total) : "subl_promotions.non_negative_integer_p(total) " + "CommonSymbols.NIL != subl_promotions.non_negative_integer_p(total) " + total; final SubLObject _prev_bind_0 = $last_percent_progress_index$.currentBinding(thread); final SubLObject _prev_bind_2 = $last_percent_progress_prediction$.currentBinding(thread); final SubLObject _prev_bind_3 = $within_noting_percent_progress$.currentBinding(thread); final SubLObject _prev_bind_4 = $percent_progress_start_time$.currentBinding(thread); try { $last_percent_progress_index$.bind(ZERO_INTEGER, thread); $last_percent_progress_prediction$.bind(NIL, thread); $within_noting_percent_progress$.bind(T, thread); $percent_progress_start_time$.bind(get_universal_time(), thread); try { noting_percent_progress_preamble(format(NIL, $str3$Triggering_rule_against__A__S_sup, new SubLObject[]{ total, focal_asent, rule_string })); SubLObject valid; for (SubLObject done_var = NIL; NIL == done_var; done_var = makeBoolean(NIL == valid)) { thread.resetMultipleValues(); final SubLObject trigger_gaf = iteration.iteration_next(iterator); valid = thread.secondMultipleValue(); thread.resetMultipleValues(); if (NIL != valid) { SubLObject message_var = NIL; final SubLObject was_appendingP = eval($sym4$_APPEND_STACK_TRACES_TO_ERROR_MESSAGES__); eval($list5); try { try { thread.throwStack.push($catch_error_message_target$.getGlobalValue()); final SubLObject _prev_bind_0_$1 = Errors.$error_handler$.currentBinding(thread); try { Errors.$error_handler$.bind(CATCH_ERROR_MESSAGE_HANDLER, thread); try { forward.repropagate_forward_gaf_wrt_rule(trigger_gaf, rule); } catch (final Throwable catch_var) { Errors.handleThrowable(catch_var, NIL); } } finally { Errors.$error_handler$.rebind(_prev_bind_0_$1, thread); } } catch (final Throwable ccatch_env_var) { message_var = Errors.handleThrowable(ccatch_env_var, $catch_error_message_target$.getGlobalValue()); } finally { thread.throwStack.pop(); } } finally { final SubLObject _prev_bind_0_$2 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values = getValuesAsVector(); eval(list(CSETQ, $sym4$_APPEND_STACK_TRACES_TO_ERROR_MESSAGES__, was_appendingP)); restoreValuesFromVector(_values); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$2, thread); } } if (message_var.isString()) { Errors.warn($str8$_A, message_var); } sofar = add(sofar, ONE_INTEGER); note_percent_progress(sofar, total); } } } finally { final SubLObject _prev_bind_0_$3 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values2 = getValuesAsVector(); noting_percent_progress_postamble(); restoreValuesFromVector(_values2); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$3, thread); } } } finally { $percent_progress_start_time$.rebind(_prev_bind_4, thread); $within_noting_percent_progress$.rebind(_prev_bind_3, thread); $last_percent_progress_prediction$.rebind(_prev_bind_2, thread); $last_percent_progress_index$.rebind(_prev_bind_0, thread); } final SubLObject after_dependents = assertions_high.assertion_dependent_count(rule); final SubLObject new_dependents = subtract(after_dependents, before_dependents); return values(new_dependents, sofar); } public static SubLObject possibly_change_assertion_direction_to_forward_without_repropagation(final SubLObject assertion) { assert NIL != assertion_handles.assertion_p(assertion) : "assertion_handles.assertion_p(assertion) " + "CommonSymbols.NIL != assertion_handles.assertion_p(assertion) " + assertion; if (NIL == assertions_high.forward_assertionP(assertion)) { assertions_interface.kb_set_assertion_direction(assertion, $FORWARD); return assertions_high.forward_assertionP(assertion); } return NIL; } public static SubLObject repropagate_trigger_gaf_against_rule(final SubLObject trigger_gaf, final SubLObject rule) { final SubLThread thread = SubLProcess.currentSubLThread(); SubLObject result = NIL; final SubLObject _prev_bind_0 = forward.$forward_inference_shares_same_problem_storeP$.currentBinding(thread); try { forward.$forward_inference_shares_same_problem_storeP$.bind(NIL, thread); final SubLObject environment = forward.get_forward_inference_environment(); assert NIL != queues.queue_p(environment) : "queues.queue_p(environment) " + "CommonSymbols.NIL != queues.queue_p(environment) " + environment; final SubLObject _prev_bind_0_$4 = kb_control_vars.$forward_inference_environment$.currentBinding(thread); final SubLObject _prev_bind_2 = $current_forward_problem_store$.currentBinding(thread); try { kb_control_vars.$forward_inference_environment$.bind(environment, thread); $current_forward_problem_store$.bind(NIL, thread); try { result = forward.repropagate_forward_gaf_wrt_rule(trigger_gaf, rule); } finally { final SubLObject _prev_bind_0_$5 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values = getValuesAsVector(); forward.clear_current_forward_problem_store(); restoreValuesFromVector(_values); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$5, thread); } } } finally { $current_forward_problem_store$.rebind(_prev_bind_2, thread); kb_control_vars.$forward_inference_environment$.rebind(_prev_bind_0_$4, thread); } } finally { forward.$forward_inference_shares_same_problem_storeP$.rebind(_prev_bind_0, thread); } return result; } public static SubLObject forward_rule_trigger_gafs(final SubLObject rule, SubLObject propagation_mt) { if (propagation_mt == UNPROVIDED) { propagation_mt = $$InferencePSC; } final SubLThread thread = SubLProcess.currentSubLThread(); assert NIL != assertions_high.rule_assertionP(rule) : "assertions_high.rule_assertionP(rule) " + "CommonSymbols.NIL != assertions_high.rule_assertionP(rule) " + rule; thread.resetMultipleValues(); final SubLObject focal_asent = forward_rule_trigger_asent(rule, propagation_mt); final SubLObject estimated_children = thread.secondMultipleValue(); thread.resetMultipleValues(); if (NIL != focal_asent) { return forward_rule_trigger_gafs_int(focal_asent, propagation_mt); } return NIL; } public static SubLObject new_forward_rule_trigger_gaf_iterator(final SubLObject rule, SubLObject propagation_mt) { if (propagation_mt == UNPROVIDED) { propagation_mt = $$InferencePSC; } final SubLThread thread = SubLProcess.currentSubLThread(); assert NIL != assertions_high.rule_assertionP(rule) : "assertions_high.rule_assertionP(rule) " + "CommonSymbols.NIL != assertions_high.rule_assertionP(rule) " + rule; thread.resetMultipleValues(); final SubLObject focal_asent = forward_rule_trigger_asent(rule, propagation_mt); final SubLObject estimated_children = thread.secondMultipleValue(); thread.resetMultipleValues(); if (NIL == focal_asent) { return iteration.new_list_iterator(NIL); } if ((!$forward_trigger_lazy_iteration_threshold$.getGlobalValue().isNumber()) || estimated_children.numLE($forward_trigger_lazy_iteration_threshold$.getGlobalValue())) { final SubLObject trigger_gafs = forward_rule_trigger_gafs_int(focal_asent, propagation_mt); return values(iteration.new_list_iterator(trigger_gafs), length(trigger_gafs), focal_asent); } return Errors.error($str12$time_to_use_a_real_query_iterator); } public static SubLObject forward_rule_trigger_gafs_int(final SubLObject focal_asent, final SubLObject propagation_mt) { final SubLThread thread = SubLProcess.currentSubLThread(); SubLObject query_result = NIL; SubLObject trigger_gafs = NIL; final SubLObject _prev_bind_0 = $noting_progress_delayed_mode_seconds$.currentBinding(thread); final SubLObject _prev_bind_2 = $noting_progress_delayed_mode_string$.currentBinding(thread); try { $noting_progress_delayed_mode_seconds$.bind(TWO_INTEGER, thread); $noting_progress_delayed_mode_string$.bind(cconcatenate($$$Determining_trigger_GAFs_for_, format_nil.format_nil_s_no_copy(focal_asent)), thread); final SubLObject str = cconcatenate($$$Determining_trigger_GAFs_for_, format_nil.format_nil_s_no_copy(focal_asent)); final SubLObject _prev_bind_0_$6 = $progress_start_time$.currentBinding(thread); final SubLObject _prev_bind_1_$7 = $progress_last_pacification_time$.currentBinding(thread); final SubLObject _prev_bind_3 = $progress_elapsed_seconds_for_notification$.currentBinding(thread); final SubLObject _prev_bind_4 = $progress_notification_count$.currentBinding(thread); final SubLObject _prev_bind_5 = $progress_pacifications_since_last_nl$.currentBinding(thread); final SubLObject _prev_bind_6 = $progress_count$.currentBinding(thread); final SubLObject _prev_bind_7 = $is_noting_progressP$.currentBinding(thread); final SubLObject _prev_bind_8 = $silent_progressP$.currentBinding(thread); try { $progress_start_time$.bind(get_universal_time(), thread); $progress_last_pacification_time$.bind($progress_start_time$.getDynamicValue(thread), thread); $progress_elapsed_seconds_for_notification$.bind($suppress_all_progress_faster_than_seconds$.getDynamicValue(thread), thread); $progress_notification_count$.bind(ZERO_INTEGER, thread); $progress_pacifications_since_last_nl$.bind(ZERO_INTEGER, thread); $progress_count$.bind(ZERO_INTEGER, thread); $is_noting_progressP$.bind(T, thread); $silent_progressP$.bind(NIL != str ? $silent_progressP$.getDynamicValue(thread) : T, thread); noting_progress_preamble(str); final SubLObject environment = forward.get_forward_inference_environment(); assert NIL != queues.queue_p(environment) : "queues.queue_p(environment) " + "CommonSymbols.NIL != queues.queue_p(environment) " + environment; final SubLObject _prev_bind_0_$7 = kb_control_vars.$forward_inference_environment$.currentBinding(thread); final SubLObject _prev_bind_1_$8 = $current_forward_problem_store$.currentBinding(thread); try { kb_control_vars.$forward_inference_environment$.bind(environment, thread); $current_forward_problem_store$.bind(NIL, thread); try { final SubLObject overriding_query_properties = $list14; final SubLObject query_properties = forward.forward_inference_query_properties(clauses.empty_clause(), overriding_query_properties); query_result = inference_kernel.new_cyc_query(focal_asent, propagation_mt, query_properties); } finally { final SubLObject _prev_bind_0_$8 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values = getValuesAsVector(); forward.clear_current_forward_problem_store(); restoreValuesFromVector(_values); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$8, thread); } } } finally { $current_forward_problem_store$.rebind(_prev_bind_1_$8, thread); kb_control_vars.$forward_inference_environment$.rebind(_prev_bind_0_$7, thread); } final SubLObject raw_trigger_gafs = remove_if(NULL, Mapping.mapcar(symbol_function(FIRST_GAF_IN_SUPPORTS), query_result), UNPROVIDED, UNPROVIDED, UNPROVIDED, UNPROVIDED); trigger_gafs = assertion_utilities.sort_assertions(list_utilities.fast_delete_duplicates(raw_trigger_gafs, symbol_function(KBEQ), UNPROVIDED, UNPROVIDED, UNPROVIDED, UNPROVIDED)); noting_progress_postamble(); } finally { $silent_progressP$.rebind(_prev_bind_8, thread); $is_noting_progressP$.rebind(_prev_bind_7, thread); $progress_count$.rebind(_prev_bind_6, thread); $progress_pacifications_since_last_nl$.rebind(_prev_bind_5, thread); $progress_notification_count$.rebind(_prev_bind_4, thread); $progress_elapsed_seconds_for_notification$.rebind(_prev_bind_3, thread); $progress_last_pacification_time$.rebind(_prev_bind_1_$7, thread); $progress_start_time$.rebind(_prev_bind_0_$6, thread); } } finally { $noting_progress_delayed_mode_string$.rebind(_prev_bind_2, thread); $noting_progress_delayed_mode_seconds$.rebind(_prev_bind_0, thread); } return trigger_gafs; } public static SubLObject forward_rule_trigger_asent(final SubLObject rule, SubLObject propagation_mt) { if (propagation_mt == UNPROVIDED) { propagation_mt = $$InferencePSC; } final SubLThread thread = SubLProcess.currentSubLThread(); assert NIL != assertions_high.rule_assertionP(rule) : "assertions_high.rule_assertionP(rule) " + "CommonSymbols.NIL != assertions_high.rule_assertionP(rule) " + rule; final SubLObject cnf = assertions_high.assertion_cnf(rule); final SubLObject neg_lits = clauses.neg_lits(cnf); SubLObject trigger_asent = NIL; SubLObject estimated_children = NIL; if (NIL != neg_lits) { if (NIL != list_utilities.singletonP(neg_lits)) { trigger_asent = neg_lits.first(); estimated_children = inference_utilities.literal_removal_cost(trigger_asent, $POS, propagation_mt, $ALL); } else { final SubLObject environment = forward.get_forward_inference_environment(); assert NIL != queues.queue_p(environment) : "queues.queue_p(environment) " + "CommonSymbols.NIL != queues.queue_p(environment) " + environment; final SubLObject _prev_bind_0 = kb_control_vars.$forward_inference_environment$.currentBinding(thread); final SubLObject _prev_bind_2 = $current_forward_problem_store$.currentBinding(thread); try { kb_control_vars.$forward_inference_environment$.bind(environment, thread); $current_forward_problem_store$.bind(NIL, thread); try { final SubLObject query_dnf = clauses.make_dnf(NIL, obfuscate_non_trigger_literal_lits(neg_lits, rule, propagation_mt)); final SubLObject overriding_query_properties = $list20; final SubLObject query_properties = forward.forward_inference_query_properties(clauses.empty_clause(), overriding_query_properties); SubLObject inference = NIL; try { inference = nth_value_step_2(nth_value_step_1(TWO_INTEGER), inference_kernel.new_cyc_query_from_dnf(query_dnf, propagation_mt, NIL, query_properties)); if (NIL != inference) { final SubLObject strategy = inference_datastructures_inference.simplest_inference_strategy(inference); final SubLObject root_problem = inference_datastructures_inference.inference_root_problem(inference); final SubLObject executed_tactics = inference_datastructures_problem.problem_executed_tactics(root_problem); final SubLObject join_ordered_tactic = find($JOIN_ORDERED, executed_tactics, symbol_function(EQ), symbol_function(TACTIC_HL_MODULE_NAME), UNPROVIDED, UNPROVIDED); if (NIL != join_ordered_tactic) { final SubLObject focal_problem = inference_worker_join_ordered.join_ordered_tactic_focal_problem(join_ordered_tactic); final SubLObject productivity = inference_worker.simple_problem_estimated_total_global_productivity(focal_problem, strategy); trigger_asent = inference_datastructures_problem.single_literal_problem_atomic_sentence(focal_problem); estimated_children = inference_datastructures_enumerated_types.number_of_children_for_productivity(productivity); } else if (NIL != find($SPLIT, executed_tactics, symbol_function(EQ), symbol_function(TACTIC_HL_MODULE_NAME), UNPROVIDED, UNPROVIDED)) { Errors.warn($str24$Can_t_determine_trigger_asent_for, sefify(rule)); } else { Errors.warn($str25$Can_t_determine_trigger_asent_for, sefify(rule)); } } else { Errors.warn($str26$Can_t_create_inference_to_determi, sefify(rule)); } } finally { final SubLObject _prev_bind_0_$11 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values = getValuesAsVector(); if (NIL != inference) { } restoreValuesFromVector(_values); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$11, thread); } } } finally { final SubLObject _prev_bind_0_$12 = $is_thread_performing_cleanupP$.currentBinding(thread); try { $is_thread_performing_cleanupP$.bind(T, thread); final SubLObject _values2 = getValuesAsVector(); forward.clear_current_forward_problem_store(); restoreValuesFromVector(_values2); } finally { $is_thread_performing_cleanupP$.rebind(_prev_bind_0_$12, thread); } } } finally { $current_forward_problem_store$.rebind(_prev_bind_2, thread); kb_control_vars.$forward_inference_environment$.rebind(_prev_bind_0, thread); } } } return values(trigger_asent, estimated_children); } public static SubLObject obfuscate_non_trigger_literal_lits(final SubLObject lits, final SubLObject rule, final SubLObject propagation_mt) { final SubLObject non_trigger_literals = inference_worker_transformation.forward_rule_non_trigger_literals(rule, propagation_mt); SubLObject n = $int$100; SubLObject result = NIL; SubLObject cdolist_list_var = lits; SubLObject lit = NIL; lit = cdolist_list_var.first(); while (NIL != cdolist_list_var) { if ((NIL == kb_utilities.kbeq($$evaluate, literal_predicate(lit, UNPROVIDED))) && ((NIL != kb_accessors.not_assertible_predicateP(literal_predicate(lit, UNPROVIDED), $$BaseKB)) || ((NIL != subl_promotions.memberP(lit, non_trigger_literals, symbol_function($sym30$EQUALS_EL_), UNPROVIDED)) && (NIL == variables.variable_p(literal_arg0(lit, UNPROVIDED)))))) { result = cons(replace_formula_arg(ZERO_INTEGER, variables.get_variable(n), lit), result); n = add(n, ONE_INTEGER); } else { result = cons(lit, result); } cdolist_list_var = cdolist_list_var.rest(); lit = cdolist_list_var.first(); } return nreverse(result); } public static SubLObject forward_rule_initial_fanout(final SubLObject rule, SubLObject propagation_mt) { if (propagation_mt == UNPROVIDED) { propagation_mt = $$InferencePSC; } return nth_value_step_2(nth_value_step_1(ONE_INTEGER), forward_rule_trigger_asent(rule, propagation_mt)); } public static SubLObject first_gaf_in_supports(final SubLObject supports) { SubLObject result = find_if(symbol_function($sym31$GAF_ASSERTION_), supports, UNPROVIDED, UNPROVIDED, UNPROVIDED); if ((NIL == result) && (NIL != list_utilities.singletonP(supports))) { final SubLObject justification = hl_supports.hl_justify(supports.first()); if ((NIL != list_utilities.singletonP(justification)) && (NIL != assertions_high.gaf_assertionP(justification.first()))) { result = justification.first(); } } if (NIL == result) { final SubLObject v_hl_supports = list_utilities.find_all_if(symbol_function(HL_SUPPORT_P), supports, UNPROVIDED); SubLObject isa_hl_supports = NIL; SubLObject cdolist_list_var = v_hl_supports; SubLObject hl_support = NIL; hl_support = cdolist_list_var.first(); while (NIL != cdolist_list_var) { if ($ISA == arguments.hl_support_module(hl_support)) { isa_hl_supports = cons(hl_support, isa_hl_supports); } cdolist_list_var = cdolist_list_var.rest(); hl_support = cdolist_list_var.first(); } if (NIL != list_utilities.singletonP(isa_hl_supports)) { final SubLObject isa_hl_support = isa_hl_supports.first(); SubLObject isa_assertions = NIL; SubLObject cdolist_list_var2 = (NIL != kb_hl_support_handles.kb_hl_support_p(isa_hl_support)) ? kb_hl_supports_high.kb_hl_support_justification(isa_hl_support) : hl_supports.hl_justify(isa_hl_support); SubLObject support = NIL; support = cdolist_list_var2.first(); while (NIL != cdolist_list_var2) { if (NIL != assertion_utilities.gaf_assertion_with_any_of_preds_p(support, $list34)) { isa_assertions = cons(support, isa_assertions); } cdolist_list_var2 = cdolist_list_var2.rest(); support = cdolist_list_var2.first(); } if (NIL != list_utilities.singletonP(isa_assertions)) { result = isa_assertions.first(); } } } return result; } public static SubLObject declare_forward_rule_propagation_file() { declareFunction("forward_propagate_rule_via_trigger_gafs", "FORWARD-PROPAGATE-RULE-VIA-TRIGGER-GAFS", 1, 1, false); declareFunction("possibly_change_assertion_direction_to_forward_without_repropagation", "POSSIBLY-CHANGE-ASSERTION-DIRECTION-TO-FORWARD-WITHOUT-REPROPAGATION", 1, 0, false); declareFunction("repropagate_trigger_gaf_against_rule", "REPROPAGATE-TRIGGER-GAF-AGAINST-RULE", 2, 0, false); declareFunction("forward_rule_trigger_gafs", "FORWARD-RULE-TRIGGER-GAFS", 1, 1, false); declareFunction("new_forward_rule_trigger_gaf_iterator", "NEW-FORWARD-RULE-TRIGGER-GAF-ITERATOR", 1, 1, false); declareFunction("forward_rule_trigger_gafs_int", "FORWARD-RULE-TRIGGER-GAFS-INT", 2, 0, false); declareFunction("forward_rule_trigger_asent", "FORWARD-RULE-TRIGGER-ASENT", 1, 1, false); declareFunction("obfuscate_non_trigger_literal_lits", "OBFUSCATE-NON-TRIGGER-LITERAL-LITS", 3, 0, false); declareFunction("forward_rule_initial_fanout", "FORWARD-RULE-INITIAL-FANOUT", 1, 1, false); declareFunction("first_gaf_in_supports", "FIRST-GAF-IN-SUPPORTS", 1, 0, false); return NIL; } public static SubLObject init_forward_rule_propagation_file() { deflexical("*FORWARD-TRIGGER-LAZY-ITERATION-THRESHOLD*", NIL); return NIL; } public static SubLObject setup_forward_rule_propagation_file() { return NIL; } @Override public void declareFunctions() { declare_forward_rule_propagation_file(); } @Override public void initializeVariables() { init_forward_rule_propagation_file(); } @Override public void runTopLevelForms() { setup_forward_rule_propagation_file(); } static { } } /** * Total time: 265 ms */
zhangjunfang/eclipse-dir
nspExt/src/main/java/cache/cn/newcapec/framework/plugins/aspect/FlushCacheAspect.java
<filename>nspExt/src/main/java/cache/cn/newcapec/framework/plugins/aspect/FlushCacheAspect.java package cn.newcapec.framework.plugins.aspect; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import cn.newcapec.framework.plugins.cache.Cache; import cn.newcapec.framework.plugins.cache.CacheEngine; import cn.newcapec.framework.plugins.cache.annotation.FlushCache; import cn.newcapec.framework.plugins.cache.memoryCache.CacheController; import cn.newcapec.framework.plugins.cache.utils.StringUtils; @Component @Aspect public class FlushCacheAspect implements Cache { private static final long serialVersionUID = -1069745020898186109L; protected final static Log log = LogFactory.getLog(FlushCacheAspect.class); @SuppressWarnings("unused") @Pointcut("@annotation(cn.newcapec.framework.plugins.cache.annotation.FlushCache)") private void doMethod() { } private CacheEngine getCache() { return CacheController.getCache(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Around("doMethod()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { log.info("开始刷新缓存数据……"); long starttime = System.currentTimeMillis(); MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); Class[] methodParameterTypes = method.getParameterTypes(); Class target = pjp.getTarget().getClass(); Method meth = target.getMethod(method.getName(), methodParameterTypes); FlushCache uc = meth.getAnnotation(FlushCache.class); StringBuffer key = new StringBuffer(); if (uc.defaulttype()) { key.append(uc.head()); key.append(target.getName()); key.append(uc.foot()); } else { key.append(uc.head()).append(uc.foot()).toString(); } if (uc.orderfirst()) { this.clearFromCache(key.toString(), uc.joins()); } Object val = pjp.proceed(); if (!uc.orderfirst()) { this.clearFromCache(key.toString(), uc.joins()); } log.info("缓存刷新结束,总用时:" + (System.currentTimeMillis() - starttime) + "毫秒."); return val; } private void clearFromCache(String key, String joins) { if (getCache().get(key) != null) { getCache().remove(key); if (StringUtils.hasText(joins)) { if (joins.indexOf(StringUtils.Symbol.COMMA) != -1) { String[] joinsgroup = joins.split(StringUtils.Symbol.COMMA); for (String join : joinsgroup) { if (StringUtils.hasText(join)) { getCache().remove(join); } } } else { getCache().remove(joins); } } } } }
huylg/apollo-react-js
final/server/node_modules/apollo/lib/git.js
"use strict"; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; }; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const fs = require("fs"); const ci = require("env-ci"); const git_parse_1 = require("git-parse"); const git = require("git-rev-sync"); const lodash_1 = require("lodash"); const findGitRoot = (start) => { start = start || process.cwd(); if (typeof start === "string") { if (start[start.length - 1] !== path.sep) start += path.sep; start = start.split(path.sep); } if (!start.length) return; start.pop(); const dir = start.join(path.sep); if (fs.existsSync(path.join(dir, ".git"))) { return path.normalize(dir); } else { return findGitRoot(start); } }; exports.gitInfo = async () => { const { isCi, commit, branch, slug, root } = ci(); const gitLoc = root ? root : findGitRoot(); if (!commit) return; let committer; let remoteUrl = slug; let message; if (gitLoc) { const _a = await git_parse_1.gitToJs(gitLoc) .then((commits) => commits && commits.length > 0 ? commits[0] : { authorName: null, authorEmail: null, message: null }) .catch(() => ({ authorEmail: null, authorName: null, message: null })), { authorName, authorEmail } = _a, commit = __rest(_a, ["authorName", "authorEmail"]); committer = `${authorName || ""} ${authorEmail ? `<${authorEmail}>` : ""}`.trim(); message = commit.message; if (!isCi) { try { remoteUrl = git.remoteUrl(); } catch (e) { } } } return lodash_1.pickBy({ committer, commit, remoteUrl, message, branch }, lodash_1.identity); }; //# sourceMappingURL=git.js.map
jcarreira/cirrus-kv
src/object_store/LRUEvictionPolicy.cpp
#include "object_store/LRUEvictionPolicy.h" #include "object_store/FullCacheStore.h" namespace cirrus { LRUEvictionPolicy::LRUEvictionPolicy(size_t num_objs) : EvictionPolicy(num_objs) { } LRUEvictionPolicy::~LRUEvictionPolicy() { } bool LRUEvictionPolicy::evictIfNeeded(FullCacheStore& fc) { if (fc->getNumObjs() > max_num_objs_) { fc->dropLRUObj(); return true; } return false; } } // namespace cirrus
VidolVidolov/SoftuniFundamentals
LadyBugs.js
<gh_stars>0 function ladyBugs(input) { let field = input.shift(); let ladyBugsField = []; for (let i = 0; i < field; i++) { ladyBugsField[i] = i + ''; } let startPositions = input.shift(); let innerCounter = 0; let separatePositions = []; for (let i = 0; i < startPositions.length; i++) { if (startPositions[i] === ' ') { } else { separatePositions[innerCounter] = Number(startPositions[i]); innerCounter++; } } innerCounter = 0; separatePositions.sort(); for (let i = 0; i < ladyBugsField.length; i++) { if (i === Number(separatePositions[innerCounter])) { ladyBugsField[i] = 'ladybug'; innerCounter++; } else { ladyBugsField[i] = i; } } let currentBug = ''; let step; let way = ''; innerCounter = 0; let newMove = []; let flag = false; for (let i = 0; i < input.length; i++) { let element = input[i]; if (element.includes('right')) { way = 'right'; } else if (element.includes('left')) { way = 'left'; } currentBug = element[0]; step = element[element.length - 1]; if (element.includes('-')) { step = '-' + step; } for (let j = Number(currentBug); j < ladyBugsField.length; j++) { if(ladyBugsField[j] !== "ladybug"){ break; } if (way === 'right') { if (Number(step) < 0) { if (ladyBugsField[j - Number(step)] === 'ladybug') { ladyBugsField[j - (Number(step))] = 'ladybug'; ladyBugsField[j - (Number(step))] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } else if (ladyBugsField[j - Number(step)] >= ladyBugsField.length) { ladyBugsField[j] = j; innerCounter++; break; } else { ladyBugsField[j - step] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } } else { if (ladyBugsField[j + Number(step)] === 'ladybug') { ladyBugsField[j + (Number(step))] = 'ladybug'; ladyBugsField[j + (Number(step))] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } else if (j + Number(step) >= ladyBugsField.length) { ladyBugsField[j] = j; innerCounter++; break; } else { ladyBugsField[j + Number(step)] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } } } else if (way === 'left') { if (Number(step < 0)) { step = Math.abs(step); if (ladyBugsField[j + Number(step)] === 'ladybug') { ladyBugsField[j + (Number(step))] = 'ladybug'; ladyBugsField[j + (Number(step))] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } else if (j + Number(step) >= ladyBugsField.length) { ladyBugsField[j] = j; innerCounter++; break; } else { ladyBugsField[j + Number(step)] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } } else { if (ladyBugsField[j - Number(step)] === 'ladybug') { ladyBugsField[j - (Number(step))] = 'ladybug'; ladyBugsField[j - (Number(step))] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } else if (ladyBugsField[j - Number(step)] >= ladyBugsField.length) { ladyBugsField[j] = j; innerCounter++; break; } else { ladyBugsField[j - step] = 'ladybug'; ladyBugsField[j] = j; innerCounter++; break; } } } } } for (let i = 0; i < ladyBugsField.length; i++) { if (ladyBugsField[i] === 'ladybug') { ladyBugsField[i] = 1; } else { ladyBugsField[i] = 0; } } console.log(ladyBugsField.join(' ')); } ladyBugs([ 5, '3 2', '250 left 2', '1 left -250'] );
claytonjwong/leetcode-js
136_single_number.js
<reponame>claytonjwong/leetcode-js /* * 136. Single Number * * Q: https://leetcode.com/problems/single-number/ * A: https://leetcode.com/problems/single-number/discuss/559253/Javascript-and-C%2B%2B-solutions */ /** * @param {number[]} nums * @return {number} */ let singleNumber = (A, ans = 0) => { A.forEach(x => ans ^= x); return ans; }; let singleNumber = A => A.reduce((a, b) => a ^ b, 0);
forgotter/Snippets
c++/discrete_root.cpp
/// Name: DiscreteRoot /// Description: Computes solution to equation of form x^k = b%m where m is prime. /// Detail: Maths, Number Theory /// Guarantee: } // DiscreteRoot /// Dependencies: baby_step_giant_leap, primitive_root // reference : https://cp-algorithms.com/algebra/discrete-root.html vector<int> discrete_root(int k, int m, int b) { int g = primitiveRoot(m); int p = shanks(g, b, m); vector<int> roots; int delta = (m - 1) / __gcd(m - 1, k); for (int i = p % delta; i < m - 1; i += delta) roots.push_back(modexp(g, i, m)); return roots; } // DiscreteRoot
jm90m/pigzbe-app
src/app/components/modal/index.js
<filename>src/app/components/modal/index.js import React from 'react'; import {View, Image} from 'react-native'; import styles from './styles'; export default ({children, noBird=false}) => ( <View style={styles.overlay}> <View> {!noBird && <Image source={require('./images/bird.png')} style={styles.bird}/> } <View style={styles.container}> {children} </View> </View> </View> );
cypherdotXd/o3de
Code/Editor/Controls/BitmapToolTip.cpp
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ // Description : Tooltip that displays bitmap. #include "EditorDefs.h" #include "BitmapToolTip.h" // Qt #include <QVBoxLayout> // Editor #include "Util/Image.h" #include "Util/ImageUtil.h" static const int STATIC_TEXT_C_HEIGHT = 42; static const int HISTOGRAM_C_HEIGHT = 130; ///////////////////////////////////////////////////////////////////////////// // CBitmapToolTip CBitmapToolTip::CBitmapToolTip(QWidget* parent) : QWidget(parent, Qt::ToolTip) , m_staticBitmap(new QLabel(this)) , m_staticText(new QLabel(this)) , m_rgbaHistogram(new CImageHistogramCtrl(this)) , m_alphaChannelHistogram(new CImageHistogramCtrl(this)) { m_nTimer = 0; m_hToolWnd = nullptr; m_bShowHistogram = true; m_bShowFullsize = false; m_eShowMode = ESHOW_RGB; connect(&m_timer, &QTimer::timeout, this, &CBitmapToolTip::OnTimer); auto* layout = new QVBoxLayout(this); layout->setSizeConstraint(QLayout::SetFixedSize); layout->addWidget(m_staticBitmap); layout->addWidget(m_staticText); auto* histogramLayout = new QHBoxLayout(); histogramLayout->addWidget(m_rgbaHistogram); histogramLayout->addWidget(m_alphaChannelHistogram); m_alphaChannelHistogram->setVisible(false); layout->addLayout(histogramLayout); setLayout(layout); } CBitmapToolTip::~CBitmapToolTip() { } ////////////////////////////////////////////////////////////////////////// void CBitmapToolTip::GetShowMode(EShowMode& eShowMode, bool& bShowInOriginalSize) const { bShowInOriginalSize = CheckVirtualKey(Qt::Key_Space); eShowMode = ESHOW_RGB; if (m_bHasAlpha) { if (CheckVirtualKey(Qt::Key_Control)) { eShowMode = ESHOW_RGB_ALPHA; } else if (CheckVirtualKey(Qt::Key_Alt)) { eShowMode = ESHOW_ALPHA; } else if (CheckVirtualKey(Qt::Key_Shift)) { eShowMode = ESHOW_RGBA; } } else if (m_bIsLimitedHDR) { if (CheckVirtualKey(Qt::Key_Shift)) { eShowMode = ESHOW_RGBE; } } } const char* CBitmapToolTip::GetShowModeDescription(EShowMode eShowMode, [[maybe_unused]] bool bShowInOriginalSize) const { switch (eShowMode) { case ESHOW_RGB: return "RGB"; case ESHOW_RGB_ALPHA: return "RGB+A"; case ESHOW_ALPHA: return "Alpha"; case ESHOW_RGBA: return "RGBA"; case ESHOW_RGBE: return "RGBExp"; } return ""; } void CBitmapToolTip::RefreshViewmode() { LoadImage(m_filename); if (m_eShowMode == ESHOW_RGB_ALPHA || m_eShowMode == ESHOW_RGBA) { m_rgbaHistogram->setVisible(true); m_alphaChannelHistogram->setVisible(true); } else if (m_eShowMode == ESHOW_ALPHA) { m_rgbaHistogram->setVisible(false); m_alphaChannelHistogram->setVisible(true); } else { m_rgbaHistogram->setVisible(true); m_alphaChannelHistogram->setVisible(false); } } bool CBitmapToolTip::LoadImage(const QString& imageFilename) { EShowMode eShowMode = ESHOW_RGB; const char* pShowModeDescription = "RGB"; bool bShowInOriginalSize = false; GetShowMode(eShowMode, bShowInOriginalSize); pShowModeDescription = GetShowModeDescription(eShowMode, bShowInOriginalSize); QString convertedFileName = Path::GamePathToFullPath(Path::ReplaceExtension(imageFilename, ".dds")); // We need to check against both the image filename and the converted filename as it is possible that the // converted file existed but failed to load previously and we reverted to loading the source asset. bool alreadyLoadedImage = ((m_filename == convertedFileName) || (m_filename == imageFilename)); if (alreadyLoadedImage && (m_eShowMode == eShowMode) && (m_bShowFullsize == bShowInOriginalSize)) { return true; } CCryFile fileCheck; if (!fileCheck.Open(convertedFileName.toUtf8().data(), "rb")) { // if we didn't find it, then default back to just using what we can find (if any) convertedFileName = imageFilename; } else { fileCheck.Close(); } m_eShowMode = eShowMode; m_bShowFullsize = bShowInOriginalSize; CImageEx image; image.SetHistogramEqualization(CheckVirtualKey(Qt::Key_Shift)); bool loadedRequestedAsset = true; if (!CImageUtil::LoadImage(convertedFileName, image)) { //Failed to load the requested asset, let's try loading the source asset if available. loadedRequestedAsset = false; if (!CImageUtil::LoadImage(imageFilename, image)) { m_staticBitmap->clear(); return false; } } QString imginfo; m_filename = loadedRequestedAsset ? convertedFileName : imageFilename; m_bHasAlpha = image.HasAlphaChannel(); m_bIsLimitedHDR = image.IsLimitedHDR(); GetShowMode(eShowMode, bShowInOriginalSize); pShowModeDescription = GetShowModeDescription(eShowMode, bShowInOriginalSize); if (m_bHasAlpha) { imginfo = tr("%1x%2 %3\nShowing %4 (ALT=Alpha, SHIFT=RGBA, CTRL=RGB+A, SPACE=see in original size)"); } else if (m_bIsLimitedHDR) { imginfo = tr("%1x%2 %3\nShowing %4 (SHIFT=see hist.-equalized, SPACE=see in original size)"); } else { imginfo = tr("%1x%2 %3\nShowing %4 (SPACE=see in original size)"); } imginfo = imginfo.arg(image.GetWidth()).arg(image.GetHeight()).arg(image.GetFormatDescription()).arg(pShowModeDescription); m_staticText->setText(imginfo); int w = image.GetWidth(); int h = image.GetHeight(); int multiplier = (m_eShowMode == ESHOW_RGB_ALPHA ? 2 : 1); int originalW = w * multiplier; int originalH = h; if (!bShowInOriginalSize || (w == 0)) { w = 256; } if (!bShowInOriginalSize || (h == 0)) { h = 256; } w *= multiplier; resize(w + 4, h + 4 + STATIC_TEXT_C_HEIGHT + HISTOGRAM_C_HEIGHT); setVisible(true); CImageEx scaledImage; if (bShowInOriginalSize && (originalW < w)) { w = originalW; } if (bShowInOriginalSize && (originalH < h)) { h = originalH; } scaledImage.Allocate(w, h); if (m_eShowMode == ESHOW_RGB_ALPHA) { CImageUtil::ScaleToDoubleFit(image, scaledImage); } else { CImageUtil::ScaleToFit(image, scaledImage); } if (m_eShowMode == ESHOW_RGB || m_eShowMode == ESHOW_RGBE) { scaledImage.SwapRedAndBlue(); scaledImage.FillAlpha(); } else if (m_eShowMode == ESHOW_ALPHA) { for (int hh = 0; hh < scaledImage.GetHeight(); hh++) { for (int ww = 0; ww < scaledImage.GetWidth(); ww++) { int a = scaledImage.ValueAt(ww, hh) >> 24; scaledImage.ValueAt(ww, hh) = RGB(a, a, a); } } } else if (m_eShowMode == ESHOW_RGB_ALPHA) { int halfWidth = scaledImage.GetWidth() / 2; for (int hh = 0; hh < scaledImage.GetHeight(); hh++) { for (int ww = 0; ww < halfWidth; ww++) { int r = GetRValue(scaledImage.ValueAt(ww, hh)); int g = GetGValue(scaledImage.ValueAt(ww, hh)); int b = GetBValue(scaledImage.ValueAt(ww, hh)); int a = scaledImage.ValueAt(ww, hh) >> 24; scaledImage.ValueAt(ww, hh) = RGB(b, g, r); scaledImage.ValueAt(ww + halfWidth, hh) = RGB(a, a, a); } } } else //if (m_showMode == ESHOW_RGBA) { scaledImage.SwapRedAndBlue(); } QImage qImage(scaledImage.GetWidth(), scaledImage.GetHeight(), QImage::Format_RGB32); memcpy(qImage.bits(), scaledImage.GetData(), qImage.sizeInBytes()); m_staticBitmap->setPixmap(QPixmap::fromImage(qImage)); if (m_bShowHistogram && scaledImage.GetData()) { m_rgbaHistogram->ComputeHistogram(image, CImageHistogram::eImageFormat_32BPP_BGRA); m_rgbaHistogram->setDrawMode(EHistogramDrawMode::OverlappedRGB); m_alphaChannelHistogram->histogramDisplay()->CopyComputedDataFrom(m_rgbaHistogram->histogramDisplay()); m_alphaChannelHistogram->setDrawMode(EHistogramDrawMode::AlphaChannel); } return true; } void CBitmapToolTip::OnTimer() { /* if (IsWindowVisible()) { if (m_bHaveAnythingToRender) Invalidate(); } */ if (m_hToolWnd) { QRect toolRc(m_toolRect); QRect rc = geometry(); QPoint cursorPos = QCursor::pos(); toolRc.moveTopLeft(m_hToolWnd->mapToGlobal(toolRc.topLeft())); if (!toolRc.contains(cursorPos) && !rc.contains(cursorPos)) { setVisible(false); } else { RefreshViewmode(); } } } ////////////////////////////////////////////////////////////////////////// void CBitmapToolTip::showEvent([[maybe_unused]] QShowEvent* event) { QPoint cursorPos = QCursor::pos(); move(cursorPos); m_timer.start(500); } ////////////////////////////////////////////////////////////////////////// void CBitmapToolTip::hideEvent([[maybe_unused]] QHideEvent* event) { m_timer.stop(); } ////////////////////////////////////////////////////////////////////////// void CBitmapToolTip::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Alt || event->key() == Qt::Key_Shift) { RefreshViewmode(); } } void CBitmapToolTip::keyReleaseEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Alt || event->key() == Qt::Key_Shift) { RefreshViewmode(); } } ////////////////////////////////////////////////////////////////////////// void CBitmapToolTip::SetTool(QWidget* pWnd, const QRect& rect) { assert(pWnd); m_hToolWnd = pWnd; m_toolRect = rect; } #include <Controls/moc_BitmapToolTip.cpp>
HeRaNO/OI-ICPC-Codes
Codeforces/Gym102346H.cpp
#include <bits/stdc++.h> #define ll long long #define ls id<<1 #define rs id<<1|1 #define mem(a,b) memset(a,b,sizeof(a)) #define pii pair<int,int> #define pb(x) push_back(x) using namespace std; const int N=300050; const int inf=0x3f3f3f3f; const ll mod=1e9+7; double n,v; int a[N]; int main() { cin>>n>>v; n=n*v; for(int i=1;i<=9;++i) { cout<<fixed<<setprecision(0)<<ceil(n*(i/10.0))<<" "; } return 0; }
cotra/Java-test
ssm-stage2/src/main/java/com/lubuwei2/ssm/modules/security/dto/Register.java
<filename>ssm-stage2/src/main/java/com/lubuwei2/ssm/modules/security/dto/Register.java package com.lubuwei2.ssm.modules.security.dto; public class Register { private Integer flag; private Long uid; public Integer getFlag() { return flag; } public void setFlag(Integer flag) { this.flag = flag; } public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } }
lechium/iPhoneOS_12.1.1_Headers
Applications/MobileSlideShow/PHImportDelegate-Protocol.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // @class PHImportSource; @protocol PHImportDelegate - (void)removedImportSource:(PHImportSource *)arg1; - (void)addedImportSource:(PHImportSource *)arg1; @end
TomographyLab/NiftyRec
teem/src/nrrd/cc.c
/* Teem: Tools to process and visualize scientific data and images Copyright (C) 2011, 2010, 2009 University of Chicago Copyright (C) 2008, 2007, 2006, 2005 <NAME> Copyright (C) 2004, 2003, 2002, 2001, 2000, 1999, 1998 University of Utah This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The terms of redistributing and/or modifying this software also include exceptions to the LGPL that facilitate static linking. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "nrrd.h" #include "privateNrrd.h" /* ** learned: if you have globals, such as _nrrdCC_verb, which are ** defined and declared here, but which are NOT initialized, then ** C++ apps which are linking against Teem will have problems!!! ** This was first seen on the mac. */ int _nrrdCC_EqvIncr = 128; int _nrrdCC_verb = 0; int _nrrdCCFind_1(Nrrd *nout, unsigned int *numid, const Nrrd *nin) { /* static const char me[]="_nrrdCCFind_1"; */ unsigned int sx, I, id, lval, val, *out, (*lup)(const void *, size_t); lup = nrrdUILookup[nin->type]; out = AIR_CAST(unsigned int*, nout->data); out[0] = id = 0; *numid = 1; sx = AIR_CAST(unsigned int, nin->axis[0].size); lval = lup(nin->data, 0); for (I=1; I<sx; I++) { val = lup(nin->data, I); if (lval != val) { id++; (*numid)++; } out[I] = id; lval = val; } return 0; } /* ** layout of value (pvl) and index (pid) cache: ** ** 2 3 4 --> X ** 1 . . oddly, index 0 is never used ** . . . ** | ** v Y */ int _nrrdCCFind_2(Nrrd *nout, unsigned int *numid, airArray *eqvArr, const Nrrd *nin, unsigned int conny) { static const char me[]="_nrrdCCFind_2"; double vl=0, pvl[5]={0,0,0,0,0}; unsigned int id, pid[5]={0,0,0,0,0}, (*lup)(const void *, size_t), *out; unsigned int p, x, y, sx, sy; id = 0; /* sssh! compiler warnings */ lup = nrrdUILookup[nin->type]; out = AIR_CAST(unsigned int*, nout->data); sx = AIR_CAST(unsigned int, nin->axis[0].size); sy = AIR_CAST(unsigned int, nin->axis[1].size); #define GETV_2(x,y) ((AIR_IN_CL(0, AIR_CAST(int, x), AIR_CAST(int, sx-1)) \ && AIR_IN_CL(0, AIR_CAST(int, y), AIR_CAST(int, sy-1))) \ ? lup(nin->data, (x) + sx*(y)) \ : 0.5) /* value that can't come from an array of uints */ #define GETI_2(x,y) ((AIR_IN_CL(0, AIR_CAST(int, x), AIR_CAST(int, sx-1)) \ && AIR_IN_CL(0, AIR_CAST(int, y), AIR_CAST(int, sy-1))) \ ? out[(x) + sx*(y)] \ : AIR_CAST(unsigned int, -1)) /* CC index (probably!) never assigned */ *numid = 0; for (y=0; y<sy; y++) { for (x=0; x<sx; x++) { if (_nrrdCC_verb) { fprintf(stderr, "%s(%d,%d) -----------\n", me, x, y); } if (!x) { pvl[1] = GETV_2(-1, y); pid[1] = GETI_2(-1, y); pvl[2] = GETV_2(-1, y-1); pid[2] = GETI_2(-1, y-1); pvl[3] = GETV_2(0, y-1); pid[3] = GETI_2(0, y-1); } else { pvl[1] = vl; pid[1] = id; pvl[2] = pvl[3]; pid[2] = pid[3]; pvl[3] = pvl[4]; pid[3] = pid[4]; } pvl[4] = GETV_2(x+1, y-1); pid[4] = GETI_2(x+1, y-1); vl = GETV_2(x, y); p = 0; if (vl == pvl[1]) { id = pid[p=1]; } #define TEST(P) \ if (vl == pvl[(P)]) { \ if (p) { /* we already had a value match */ \ if (id != pid[(P)]) { \ airEqvAdd(eqvArr, pid[(P)], id); \ } \ } else { \ id = pid[p=(P)]; \ } \ } TEST(3); if (2 == conny) { TEST(2); TEST(4); } if (!p) { /* didn't match anything previous */ id = *numid; (*numid)++; } if (_nrrdCC_verb) { fprintf(stderr, "%s: pvl: %g %g %g %g (vl = %g)\n", me, pvl[1], pvl[2], pvl[3], pvl[4], vl); fprintf(stderr, " pid: %d %d %d %d\n", pid[1], pid[2], pid[3], pid[4]); fprintf(stderr, " --> p = %d, id = %d, *numid = %d\n", p, id, *numid); } out[x + sx*y] = id; } } return 0; } /* ** ** 5 6 7 --> X ** 8 9 10 ** 11 12 13 ** | ** v Y ** 2 3 4 ** / 1 . . again, 0 index never used, for reasons forgotten ** Z . . . */ int _nrrdCCFind_3(Nrrd *nout, unsigned int *numid, airArray *eqvArr, const Nrrd *nin, unsigned int conny) { /* static const char me[]="_nrrdCCFind_3" ; */ double pvl[14]={0,0,0,0,0,0,0,0,0,0,0,0,0,0}, vl=0; unsigned int id, *out, (*lup)(const void *, size_t), pid[14]={0,0,0,0,0,0,0,0,0,0,0,0,0,0}; unsigned int p, x, y, z, sx, sy, sz; id = 0; /* sssh! compiler warnings */ lup = nrrdUILookup[nin->type]; out = AIR_CAST(unsigned int*, nout->data); sx = AIR_CAST(unsigned int, nin->axis[0].size); sy = AIR_CAST(unsigned int, nin->axis[1].size); sz = AIR_CAST(unsigned int, nin->axis[2].size); #define GETV_3(x,y,z) ((AIR_IN_CL(0, AIR_CAST(int, x), AIR_CAST(int, sx-1)) \ && AIR_IN_CL(0, AIR_CAST(int, y), AIR_CAST(int, sy-1)) \ && AIR_IN_CL(0, AIR_CAST(int, z), AIR_CAST(int, sz-1)))\ ? lup(nin->data, (x) + sx*((y) + sy*(z))) \ : 0.5) #define GETI_3(x,y,z) ((AIR_IN_CL(0, AIR_CAST(int, x), AIR_CAST(int, sx-1)) \ && AIR_IN_CL(0, AIR_CAST(int, y), AIR_CAST(int, sy-1)) \ && AIR_IN_CL(0, AIR_CAST(int, z), AIR_CAST(int, sz-1)))\ ? out[(x) + sx*((y) + sy*(z))] \ : AIR_CAST(unsigned int, -1)) *numid = 0; for (z=0; z<sz; z++) { for (y=0; y<sy; y++) { for (x=0; x<sx; x++) { if (!x) { pvl[ 1] = GETV_3( -1, y, z); pid[ 1] = GETI_3( -1, y, z); pvl[ 2] = GETV_3( -1, y-1, z); pid[ 2] = GETI_3( -1, y-1, z); pvl[ 3] = GETV_3( 0, y-1, z); pid[ 3] = GETI_3( 0, y-1, z); pvl[ 5] = GETV_3( -1, y-1, z-1); pid[ 5] = GETI_3( -1, y-1, z-1); pvl[ 8] = GETV_3( -1, y, z-1); pid[ 8] = GETI_3( -1, y, z-1); pvl[11] = GETV_3( -1, y+1, z-1); pid[11] = GETI_3( -1, y+1, z-1); pvl[ 6] = GETV_3( 0, y-1, z-1); pid[ 6] = GETI_3( 0, y-1, z-1); pvl[ 9] = GETV_3( 0, y, z-1); pid[ 9] = GETI_3( 0, y, z-1); pvl[12] = GETV_3( 0, y+1, z-1); pid[12] = GETI_3( 0, y+1, z-1); } else { pvl[ 1] = vl; pid[ 1] = id; pvl[ 2] = pvl[ 3]; pid[ 2] = pid[ 3]; pvl[ 3] = pvl[ 4]; pid[ 3] = pid[ 4]; pvl[ 5] = pvl[ 6]; pid[ 5] = pid[ 6]; pvl[ 8] = pvl[ 9]; pid[ 8] = pid[ 9]; pvl[11] = pvl[12]; pid[11] = pid[12]; pvl[ 6] = pvl[ 7]; pid[ 6] = pid[ 7]; pvl[ 9] = pvl[10]; pid[ 9] = pid[10]; pvl[12] = pvl[13]; pid[12] = pid[13]; } pvl[ 4] = GETV_3(x+1, y-1, z); pid[ 4] = GETI_3(x+1, y-1, z); pvl[ 7] = GETV_3(x+1, y-1, z-1); pid[ 7] = GETI_3(x+1, y-1, z-1); pvl[10] = GETV_3(x+1, y, z-1); pid[10] = GETI_3(x+1, y, z-1); pvl[13] = GETV_3(x+1, y+1, z-1); pid[13] = GETI_3(x+1, y+1, z-1); vl = GETV_3(x, y, z); p = 0; if (vl == pvl[1]) { id = pid[p=1]; } TEST(3); TEST(9); if (2 <= conny) { TEST(2); TEST(4); TEST(6); TEST(8); TEST(10); TEST(12); if (3 == conny) { TEST(5); TEST(7); TEST(11); TEST(13); } } if (!p) { /* didn't match anything previous */ id = *numid; (*numid)++; } out[x + sx*(y + sy*z)] = id; } } } return 0; } int _nrrdCCFind_N(Nrrd *nout, unsigned int *numid, airArray *eqvArr, const Nrrd *nin, unsigned int conny) { static const char me[]="_nrrdCCFind_N"; AIR_UNUSED(nout); AIR_UNUSED(numid); AIR_UNUSED(eqvArr); AIR_UNUSED(nin); AIR_UNUSED(conny); biffAddf(NRRD, "%s: sorry, not implemented yet", me); return 1; } /* ******** nrrdCCFind ** ** finds connected components (CCs) in given integral type nrrd "nin", ** according to connectivity "conny", putting the results in "nout". ** The "type" argument controls what type the output will be. If ** type == nrrdTypeDefault, the type used will be the smallest that ** can contain the CC id values. Otherwise, the specified type "type" ** will be used, assuming that it is large enough to hold the CC ids. ** ** "conny": the number of coordinates that need to varied together in ** order to reach all the samples that are to consitute the neighborhood ** around a sample. For 2-D, conny==1 specifies the 4 edge-connected ** pixels, and 2 specifies the 8 edge- and corner-connected. ** ** The caller can get a record of the values in each CC by passing a ** non-NULL nval, which will be allocated to an array of the same type ** as nin, so that nval->data[I] is the value in nin inside CC #I. */ int nrrdCCFind(Nrrd *nout, Nrrd **nvalP, const Nrrd *nin, int type, unsigned int conny) { static const char me[]="nrrdCCFind", func[]="ccfind"; Nrrd *nfpid; /* first-pass IDs */ airArray *mop, *eqvArr; unsigned int *fpid, numid, numsettleid, *map, (*lup)(const void *, size_t), (*ins)(void *, size_t, unsigned int); int ret; size_t I, NN; void *val; if (!(nout && nin)) { /* NULL nvalP okay */ biffAddf(NRRD, "%s: got NULL pointer", me); return 1; } if (nout == nin) { biffAddf(NRRD, "%s: nout == nin disallowed", me); return 1; } if (!( nrrdTypeIsIntegral[nin->type] && nrrdTypeIsUnsigned[nin->type] && nrrdTypeSize[nin->type] <= 4 )) { biffAddf(NRRD, "%s: can only find connected components in " "1, 2, or 4 byte unsigned integral values (not %s)", me, airEnumStr(nrrdType, nin->type)); return 1; } if (nrrdTypeDefault != type) { if (!( AIR_IN_OP(nrrdTypeUnknown, type, nrrdTypeLast) )) { biffAddf(NRRD, "%s: got invalid target type %d", me, type); return 1; } if (!( nrrdTypeIsIntegral[type] && nrrdTypeIsUnsigned[nin->type] && nrrdTypeSize[type] <= 4 )) { biffAddf(NRRD, "%s: can only save connected components to 1, 2, or 4 byte " "unsigned integral values (not %s)", me, airEnumStr(nrrdType, type)); return 1; } } if (!( conny <= nin->dim )) { biffAddf(NRRD, "%s: connectivity value must be in [1..%d] for %d-D " "data (not %d)", me, nin->dim, nin->dim, conny); return 1; } if (nrrdConvert(nfpid=nrrdNew(), nin, nrrdTypeUInt)) { biffAddf(NRRD, "%s: couldn't allocate fpid %s array to match input size", me, airEnumStr(nrrdType, nrrdTypeUInt)); return 1; } mop = airMopNew(); airMopAdd(mop, nfpid, (airMopper)nrrdNuke, airMopAlways); eqvArr = airArrayNew(NULL, NULL, 2*sizeof(unsigned int), _nrrdCC_EqvIncr); airMopAdd(mop, eqvArr, (airMopper)airArrayNuke, airMopAlways); ret = 0; switch(nin->dim) { case 1: ret = _nrrdCCFind_1(nfpid, &numid, nin); break; case 2: ret = _nrrdCCFind_2(nfpid, &numid, eqvArr, nin, conny); break; case 3: ret = _nrrdCCFind_3(nfpid, &numid, eqvArr, nin, conny); break; default: ret = _nrrdCCFind_N(nfpid, &numid, eqvArr, nin, conny); break; } if (ret) { biffAddf(NRRD, "%s: initial pass failed", me); airMopError(mop); return 1; } map = AIR_MALLOC(numid, unsigned int); airMopAdd(mop, map, airFree, airMopAlways); numsettleid = airEqvMap(eqvArr, map, numid); /* convert fpid values to final id values */ fpid = (unsigned int*)(nfpid->data); NN = nrrdElementNumber(nfpid); for (I=0; I<NN; I++) { fpid[I] = map[fpid[I]]; } if (nvalP) { if (!(*nvalP)) { *nvalP = nrrdNew(); } if (nrrdMaybeAlloc_va(*nvalP, nin->type, 1, AIR_CAST(size_t, numsettleid))) { biffAddf(NRRD, "%s: couldn't allocate output value list", me); airMopError(mop); return 1; } airMopAdd(mop, nvalP, (airMopper)airSetNull, airMopOnError); airMopAdd(mop, *nvalP, (airMopper)nrrdNuke, airMopOnError); val = (*nvalP)->data; lup = nrrdUILookup[nin->type]; ins = nrrdUIInsert[nin->type]; /* I'm not sure if its more work to do all the redundant assignments or to check whether or not to do them */ for (I=0; I<NN; I++) { ins(val, fpid[I], lup(nin->data, I)); } } if (nrrdTypeDefault != type) { if (numsettleid-1 > nrrdTypeMax[type]) { biffAddf(NRRD, "%s: max cc id %u is too large to fit in output type %s", me, numsettleid-1, airEnumStr(nrrdType, type)); airMopError(mop); return 1; } } else { type = (numsettleid-1 <= nrrdTypeMax[nrrdTypeUChar] ? nrrdTypeUChar : (numsettleid-1 <= nrrdTypeMax[nrrdTypeUShort] ? nrrdTypeUShort : nrrdTypeUInt)); } if (nrrdConvert(nout, nfpid, type)) { biffAddf(NRRD, "%s: trouble converting to final output", me); airMopError(mop); return 1; } if (nrrdContentSet_va(nout, func, nin, "%s,%d", airEnumStr(nrrdType, type), conny)) { biffAddf(NRRD, "%s:", me); return 1; } if (nout != nin) { nrrdAxisInfoCopy(nout, nin, NULL, NRRD_AXIS_INFO_NONE); } /* basic info handled by nrrdConvert */ airMopOkay(mop); return 0; } int _nrrdCCAdj_1(unsigned char *out, int numid, const Nrrd *nin) { AIR_UNUSED(out); AIR_UNUSED(numid); AIR_UNUSED(nin); return 0; } int _nrrdCCAdj_2(unsigned char *out, unsigned int numid, const Nrrd *nin, unsigned int conny) { unsigned int (*lup)(const void *, size_t), x, y, sx, sy, id=0; double pid[5]={0,0,0,0,0}; lup = nrrdUILookup[nin->type]; sx = AIR_CAST(unsigned int, nin->axis[0].size); sy = AIR_CAST(unsigned int, nin->axis[1].size); for (y=0; y<sy; y++) { for (x=0; x<sx; x++) { if (!x) { pid[1] = GETV_2(-1, y); pid[2] = GETV_2(-1, y-1); pid[3] = GETV_2(0, y-1); } else { pid[1] = id; pid[2] = pid[3]; pid[3] = pid[4]; } pid[4] = GETV_2(x+1, y-1); id = AIR_CAST(unsigned int, GETV_2(x, y)); #define TADJ(P) \ if (pid[(P)] != 0.5 && id != pid[(P)]) { \ out[id + numid*AIR_CAST(unsigned int, pid[(P)])] = \ out[AIR_CAST(unsigned int, pid[(P)]) + numid*id] = 1; \ } TADJ(1); TADJ(3); if (2 == conny) { TADJ(2); TADJ(4); } } } return 0; } int _nrrdCCAdj_3(unsigned char *out, int numid, const Nrrd *nin, unsigned int conny) { unsigned int (*lup)(const void *, size_t), x, y, z, sx, sy, sz, id=0; double pid[14]={0,0,0,0,0,0,0,0,0,0,0,0,0,0}; lup = nrrdUILookup[nin->type]; sx = AIR_CAST(unsigned int, nin->axis[0].size); sy = AIR_CAST(unsigned int, nin->axis[1].size); sz = AIR_CAST(unsigned int, nin->axis[2].size); for (z=0; z<sz; z++) { for (y=0; y<sy; y++) { for (x=0; x<sx; x++) { if (!x) { pid[ 1] = GETV_3(-1, y, z); pid[ 2] = GETV_3(-1, y-1, z); pid[ 3] = GETV_3( 0, y-1, z); pid[ 5] = GETV_3(-1, y-1, z-1); pid[ 8] = GETV_3(-1, y, z-1); pid[11] = GETV_3(-1, y+1, z-1); pid[ 6] = GETV_3( 0, y-1, z-1); pid[ 9] = GETV_3( 0, y, z-1); pid[12] = GETV_3( 0, y+1, z-1); } else { pid[ 1] = id; pid[ 2] = pid[ 3]; pid[ 3] = pid[ 4]; pid[ 5] = pid[ 6]; pid[ 8] = pid[ 9]; pid[11] = pid[12]; pid[ 6] = pid[ 7]; pid[ 9] = pid[10]; pid[12] = pid[13]; } pid[ 4] = GETV_3(x+1, y-1, z); pid[ 7] = GETV_3(x+1, y-1, z-1); pid[10] = GETV_3(x+1, y, z-1); pid[13] = GETV_3(x+1, y+1, z-1); id = AIR_CAST(unsigned int, GETV_3(x, y, z)); TADJ(1); TADJ(3); TADJ(9); if (2 <= conny) { TADJ(2); TADJ(4); TADJ(6); TADJ(8); TADJ(10); TADJ(12); if (3 == conny) { TADJ(5); TADJ(7); TADJ(11); TADJ(13); } } } } } return 0; } int _nrrdCCAdj_N(unsigned char *out, int numid, const Nrrd *nin, unsigned int conny) { static const char me[]="_nrrdCCAdj_N"; AIR_UNUSED(out); AIR_UNUSED(numid); AIR_UNUSED(nin); AIR_UNUSED(conny); biffAddf(NRRD, "%s: sorry, not implemented", me); return 1; } int nrrdCCAdjacency(Nrrd *nout, const Nrrd *nin, unsigned int conny) { static const char me[]="nrrdCCAdjacency", func[]="ccadj"; int ret; unsigned int maxid; unsigned char *out; if (!( nout && nrrdCCValid(nin) )) { biffAddf(NRRD, "%s: invalid args", me); return 1; } if (nout == nin) { biffAddf(NRRD, "%s: nout == nin disallowed", me); return 1; } if (!( AIR_IN_CL(1, conny, nin->dim) )) { biffAddf(NRRD, "%s: connectivity value must be in [1..%d] for %d-D " "data (not %d)", me, nin->dim, nin->dim, conny); return 1; } maxid = nrrdCCMax(nin); if (nrrdMaybeAlloc_va(nout, nrrdTypeUChar, 2, AIR_CAST(size_t, maxid+1), AIR_CAST(size_t, maxid+1))) { biffAddf(NRRD, "%s: trouble allocating output", me); return 1; } out = (unsigned char *)(nout->data); switch(nin->dim) { case 1: ret = _nrrdCCAdj_1(out, maxid+1, nin); break; case 2: ret = _nrrdCCAdj_2(out, maxid+1, nin, conny); break; case 3: ret = _nrrdCCAdj_3(out, maxid+1, nin, conny); break; default: ret = _nrrdCCAdj_N(out, maxid+1, nin, conny); break; } if (ret) { biffAddf(NRRD, "%s: trouble", me); return 1; } /* this goofiness is just so that histo-based projections return the sorts of values that we expect */ nout->axis[0].center = nout->axis[1].center = nrrdCenterCell; nout->axis[0].min = nout->axis[1].min = -0.5; nout->axis[0].max = nout->axis[1].max = maxid + 0.5; if (nrrdContentSet_va(nout, func, nin, "%d", conny)) { biffAddf(NRRD, "%s:", me); return 1; } return 0; } /* ******** nrrdCCMerge ** ** Slightly-too-multi-purpose tool for merging small connected components ** (CCs) into larger ones, according to a number of possible different ** constraints, as explained below. ** ** valDir: (value direction) uses information about the original values ** in the CC to constrain whether darker gets merged into brighter, or vice ** versa, or neither. For non-zero valDir values, a non-NULL _nval (from ** nrrdCCFind) must be passed. ** valDir > 0 : merge dark CCs into bright, but not vice versa ** valDir = 0 : merge either way, values are irrelevant ** valDir < 0 : merge bright CCs into dark, but not vice versa ** When merging with multiple neighbors (maxNeighbor > 1), the value ** of the largest neighbor is considered. ** ** maxSize: a cap on how large "small" is- CCs any larger than maxSize are ** not merged, as they are deemed too significant. Or, a maxSize of 0 says ** size is no object for merging CCs. ** ** maxNeighbor: a maximum number of neighbors that a CC can have (either ** bigger than the CC or not) if it is to be merged. Use 1 to merge ** isolated islands into their surrounds, 2 to merge CC with the larger ** of their two neighbors, etc., or 0 to allow any number of neighbors. ** ** conny: passed to nrrdCCAdjacency() when determining neighbors ** ** In order to prevent weirdness, the merging done in one call to this ** function is not transitive: if A is merged to B, then B will not be ** merged to anything else, even if meets all the requirements defined ** by the given parameters. This is accomplished by working from the ** smallest CCs to the largest. Iterated calls may be needed to acheive ** the desired effect. ** ** Note: the output of this is not "settled"- the CC id values are not ** shiftward downwards to their lowest possible values, since this would ** needlessly invalidate the nval value store. */ int nrrdCCMerge(Nrrd *nout, const Nrrd *nin, Nrrd *_nval, int valDir, unsigned int maxSize, unsigned int maxNeighbor, unsigned int conny) { static const char me[]="nrrdCCMerge", func[]="ccmerge"; char *valcnt; unsigned int _i, i, j, bigi=0, numid, *size, *sizeId, *nn, /* number of neighbors */ *val=NULL, *hit, (*lup)(const void *, size_t), (*ins)(void *, size_t, unsigned int); Nrrd *nadj, *nsize, *nval=NULL, *nnn; unsigned char *adj; unsigned int *map, *id; airArray *mop; size_t I, NN; mop = airMopNew(); if (!( nout && nrrdCCValid(nin) )) { /* _nval can be NULL */ biffAddf(NRRD, "%s: invalid args", me); airMopError(mop); return 1; } if (valDir) { airMopAdd(mop, nval = nrrdNew(), (airMopper)nrrdNuke, airMopAlways); if (nrrdConvert(nval, _nval, nrrdTypeUInt)) { biffAddf(NRRD, "%s: value-directed merging needs usable nval", me); airMopError(mop); return 1; } val = (unsigned int*)(nval->data); } if (nout != nin) { if (nrrdCopy(nout, nin)) { biffAddf(NRRD, "%s:", me); airMopError(mop); return 1; } } airMopAdd(mop, nadj = nrrdNew(), (airMopper)nrrdNuke, airMopAlways); airMopAdd(mop, nsize = nrrdNew(), (airMopper)nrrdNuke, airMopAlways); airMopAdd(mop, nnn = nrrdNew(), (airMopper)nrrdNuke, airMopAlways); if (nrrdCCSize(nsize, nin) || nrrdCopy(nnn, nsize) /* just to allocate to right size and type */ || nrrdCCAdjacency(nadj, nin, conny)) { biffAddf(NRRD, "%s:", me); airMopError(mop); return 1; } size = (unsigned int*)(nsize->data); adj = (unsigned char*)(nadj->data); nn = (unsigned int*)(nnn->data); numid = AIR_CAST(unsigned int, nsize->axis[0].size); for (i=0; i<numid; i++) { nn[i] = 0; for (j=0; j<numid; j++) { nn[i] += adj[j + numid*i]; } } map = AIR_MALLOC(numid, unsigned int); id = AIR_MALLOC(numid, unsigned int); hit = AIR_MALLOC(numid, unsigned int); sizeId = AIR_MALLOC(2*numid, unsigned int); /* we add to the mops BEFORE error checking so that anything non-NULL will get airFree'd, and happily airFree is a no-op on NULL */ airMopAdd(mop, map, airFree, airMopAlways); airMopAdd(mop, id, airFree, airMopAlways); airMopAdd(mop, hit, airFree, airMopAlways); airMopAdd(mop, sizeId, airFree, airMopAlways); if (!(map && id && hit && sizeId)) { biffAddf(NRRD, "%s: couldn't allocate buffers", me); airMopError(mop); return 1; } /* store and sort size/id pairs */ for (i=0; i<numid; i++) { sizeId[0 + 2*i] = size[i]; sizeId[1 + 2*i] = i; } qsort(sizeId, numid, 2*sizeof(unsigned int), nrrdValCompare[nrrdTypeUInt]); for (i=0; i<numid; i++) { id[i] = sizeId[1 + 2*i]; } /* initialize arrays */ for (i=0; i<numid; i++) { map[i] = i; hit[i] = AIR_FALSE; } /* _i goes through 0 to numid-1, i goes through the CC ids in ascending order of size */ for (_i=0; _i<numid; _i++) { i = id[_i]; if (hit[i]) { continue; } if (maxSize && (size[i] > maxSize)) { continue; } if (maxNeighbor && (nn[i] > maxNeighbor)) { continue; } /* find biggest neighbor, exploiting the fact that we already sorted CC ids on size. j descends through indices of id[], bigi goes through CC ids which are larger than CC i */ for (j=numid-1; j>_i; j--) { bigi = id[j]; if (adj[bigi + numid*i]) break; } if (j == _i) { continue; /* we had no neighbors ?!?! */ } if (valDir && (AIR_CAST(int, val[bigi]) - AIR_CAST(int, val[i]))*valDir < 0 ) { continue; } /* else all criteria for merging have been met */ map[i] = bigi; hit[bigi] = AIR_TRUE; } lup = nrrdUILookup[nin->type]; ins = nrrdUIInsert[nout->type]; NN = nrrdElementNumber(nin); for (I=0; I<NN; I++) { ins(nout->data, I, map[lup(nin->data, I)]); } valcnt = ((_nval && _nval->content) ? _nval->content : nrrdStateUnknownContent); if ( (valDir && nrrdContentSet_va(nout, func, nin, "%c(%s),%d,%d,%d", (valDir > 0 ? '+' : '-'), valcnt, maxSize, maxNeighbor, conny)) || (!valDir && nrrdContentSet_va(nout, func, nin, ".,%d,%d,%d", maxSize, maxNeighbor, conny)) ) { biffAddf(NRRD, "%s:", me); airMopError(mop); return 1; } /* basic info handled by nrrdCopy */ airMopOkay(mop); return 0; } /* ******** nrrdCCRevalue() ** ** assigns the original values back to the connected components ** obviously, this could be subsumed by nrrdApply1DLut(), but this ** is so special purpose that it seemed simpler to code from scratch */ int nrrdCCRevalue (Nrrd *nout, const Nrrd *nin, const Nrrd *nval) { static const char me[]="nrrdCCRevalue"; size_t I, NN; unsigned int (*vlup)(const void *, size_t), (*ilup)(const void *, size_t), (*ins)(void *, size_t, unsigned int); if (!( nout && nrrdCCValid(nin) && nval )) { biffAddf(NRRD, "%s: invalid args", me); return 1; } if (nrrdConvert(nout, nin, nval->type)) { biffAddf(NRRD, "%s: couldn't initialize output", me); return 1; } NN = nrrdElementNumber(nin); vlup = nrrdUILookup[nval->type]; ilup = nrrdUILookup[nin->type]; ins = nrrdUIInsert[nout->type]; for (I=0; I<NN; I++) { ins(nout->data, I, vlup(nval->data, ilup(nin->data, I))); } /* basic info handled by nrrdConvert */ return 0; } int nrrdCCSettle(Nrrd *nout, Nrrd **nvalP, const Nrrd *nin) { static const char me[]="nrrdCCSettle", func[]="ccsettle"; unsigned int numid, maxid, jd, id, *map, (*lup)(const void *, size_t), (*ins)(void *, size_t, unsigned int); size_t I, NN; airArray *mop; mop = airMopNew(); if (!( nout && nrrdCCValid(nin) )) { /* nvalP can be NULL */ biffAddf(NRRD, "%s: invalid args", me); airMopError(mop); return 1; } if (nrrdCopy(nout, nin)) { biffAddf(NRRD, "%s: initial copy failed", me); airMopError(mop); return 1; } maxid = nrrdCCMax(nin); lup = nrrdUILookup[nin->type]; ins = nrrdUIInsert[nin->type]; NN = nrrdElementNumber(nin); map = AIR_CALLOC(maxid+1, unsigned int); /* we do need it zeroed out */ if (!map) { biffAddf(NRRD, "%s: couldn't allocate internal LUT", me); airMopError(mop); return 1; } airMopAdd(mop, map, airFree, airMopAlways); for (I=0; I<NN; I++) { map[lup(nin->data, I)] = 1; } numid = 0; for (jd=0; jd<=maxid; jd++) { numid += map[jd]; } if (nvalP) { if (!(*nvalP)) { *nvalP = nrrdNew(); } if (nrrdMaybeAlloc_va(*nvalP, nin->type, 1, AIR_CAST(size_t, numid))) { biffAddf(NRRD, "%s: couldn't allocate output value list", me); airMopError(mop); return 1; } airMopAdd(mop, nvalP, (airMopper)airSetNull, airMopOnError); airMopAdd(mop, *nvalP, (airMopper)nrrdNuke, airMopOnError); } id = 0; for (jd=0; jd<=maxid; jd++) { if (map[jd]) { map[jd] = id; if (nvalP) { ins((*nvalP)->data, id, jd); } id++; } } for (I=0; I<NN; I++) { ins(nout->data, I, map[lup(nin->data, I)]); } if (nrrdContentSet_va(nout, func, nin, "")) { biffAddf(NRRD, "%s:", me); airMopError(mop); return 1; } /* basic info handled by nrrdCopy */ airMopOkay(mop); return 0; }
bbstilson/scalafx
scalafx/src/main/scala/scalafx/scene/chart/Axis.scala
/* * Copyright (c) 2011-2019, ScalaFX Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the ScalaFX Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE SCALAFX PROJECT 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. */ package scalafx.scene.chart import javafx.scene.{chart => jfxsc, paint => jfxsp, text => jfxst} import javafx.{geometry => jfxg} import scalafx.Includes._ import scalafx.beans.binding._ import scalafx.beans.property.{BooleanProperty, DoubleProperty, ObjectProperty} import scalafx.collections.ObservableBuffer import scalafx.delegate.SFXDelegate import scalafx.geometry.Side import scalafx.scene.layout.Region import scalafx.scene.paint.Paint import scalafx.scene.text.Font import scala.collection.JavaConverters._ import scala.collection.mutable import scala.language.implicitConversions object Axis { implicit def sfxAxis2jfx[T](v: Axis[T]): jfxsc.Axis[T] = if (v != null) v.delegate else null object TickMark { implicit def sfxTickMark2jfx[T](v: Axis.TickMark[T]): jfxsc.Axis.TickMark[T] = if (v != null) v.delegate else null } class TickMark[T](override val delegate: jfxsc.Axis.TickMark[T] = new jfxsc.Axis.TickMark[T]()) extends SFXDelegate[jfxsc.Axis.TickMark[T]] { def label: StringExpression = delegate.labelProperty def label_=(value: String): Unit = { delegate.setLabel(value) } def position: NumberExpression = delegate.positionProperty def position_=(value: Double): Unit = { delegate.setPosition(value) } def value: ObjectExpression[T] = delegate.valueProperty def value_=(value: T): Unit = { delegate.setValue(value) } def textVisible: Boolean = delegate.isTextVisible def textVisible_=(v: Boolean): Unit = { delegate.setTextVisible(v) } } } abstract class Axis[T](override val delegate: jfxsc.Axis[T]) extends Region(delegate) with SFXDelegate[jfxsc.Axis[T]] { def animated: BooleanProperty = delegate.animatedProperty def animated_=(v: Boolean): Unit = { animated() = v } def autoRanging: BooleanProperty = delegate.autoRangingProperty def autoRanging_=(v: Boolean): Unit = { autoRanging() = v } def label: ObjectProperty[java.lang.String] = delegate.labelProperty def label_=(v: String): Unit = { label() = v } def side: ObjectProperty[jfxg.Side] = delegate.sideProperty def side_=(v: Side): Unit = { side() = v } def tickLabelFill: ObjectProperty[jfxsp.Paint] = delegate.tickLabelFillProperty def tickLabelFill_=(v: Paint): Unit = { tickLabelFill() = v } def tickLabelFont: ObjectProperty[jfxst.Font] = delegate.tickLabelFontProperty def tickLabelFont_=(v: Font): Unit = { tickLabelFont() = v } def tickLabelGap: DoubleProperty = delegate.tickLabelGapProperty def tickLabelGap_=(v: Double): Unit = { tickLabelGap() = v } def tickLabelRotation: DoubleProperty = delegate.tickLabelRotationProperty def tickLabelRotation_=(v: Double): Unit = { tickLabelRotation() = v } def tickLabelsVisible: BooleanProperty = delegate.tickLabelsVisibleProperty def tickLabelsVisible_=(v: Boolean): Unit = { tickLabelsVisible() = v } def tickLength: DoubleProperty = delegate.tickLengthProperty def tickLength_=(v: Double): Unit = { tickLength() = v } def tickMarkVisible: BooleanProperty = delegate.tickMarkVisibleProperty def tickMarkVisible_=(v: Boolean): Unit = { tickMarkVisible() = v } def displayPosition(value: T): Double = delegate.getDisplayPosition(value) def tickMarks: ObservableBuffer[jfxsc.Axis.TickMark[T]] = delegate.getTickMarks def valueForDisplay(displayPosition: Double): T = delegate.getValueForDisplay(displayPosition) def zeroPosition: Double = delegate.getZeroPosition def invalidateRange(data: mutable.Buffer[T]): Unit = { delegate.invalidateRange(data.asJava) } def isValueOnAxis(value: T): Boolean = delegate.isValueOnAxis(value) def requestAxisLayout(): Unit = { delegate.requestAxisLayout() } def requestLayout(): Unit = { delegate.requestLayout() } def toNumericValue(value: T): Double = delegate.toNumericValue(value) def toRealValue(value: Double): T = delegate.toRealValue(value) }
anchoranalysis/anchor-plugins
anchor-plugin-mpp-feature/src/main/java/org/anchoranalysis/plugin/mpp/feature/bean/memo/ind/SurfaceSizeMaskNonZero.java
/*- * #%L * anchor-plugin-mpp-feature * %% * Copyright (C) 2010 - 2020 <NAME>, ETH Zurich, University of Zurich, Hoffmann-<NAME> * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package org.anchoranalysis.plugin.mpp.feature.bean.memo.ind; import lombok.Getter; import lombok.Setter; import org.anchoranalysis.bean.annotation.BeanField; import org.anchoranalysis.core.exception.OperationFailedException; import org.anchoranalysis.feature.calculate.FeatureCalculationException; import org.anchoranalysis.feature.calculate.cache.SessionInput; import org.anchoranalysis.image.core.object.properties.ObjectWithProperties; import org.anchoranalysis.image.voxel.binary.BinaryVoxels; import org.anchoranalysis.image.voxel.binary.values.BinaryValuesByte; import org.anchoranalysis.image.voxel.buffer.primitive.UnsignedByteBuffer; import org.anchoranalysis.image.voxel.kernel.ApplyKernel; import org.anchoranalysis.image.voxel.kernel.KernelApplicationParameters; import org.anchoranalysis.image.voxel.kernel.OutsideKernelPolicy; import org.anchoranalysis.image.voxel.kernel.outline.OutlineKernel; import org.anchoranalysis.image.voxel.object.ObjectMask; import org.anchoranalysis.image.voxel.statistics.VoxelStatistics; import org.anchoranalysis.mpp.bean.regionmap.RegionMap; import org.anchoranalysis.mpp.bean.regionmap.RegionMapSingleton; import org.anchoranalysis.mpp.feature.input.FeatureInputSingleMemo; import org.anchoranalysis.mpp.mark.voxelized.memo.VoxelizedMarkMemo; import org.anchoranalysis.spatial.box.Extent; public class SurfaceSizeMaskNonZero extends FeatureSingleMemoRegion { // START BEAN PROPERTIES @BeanField @Getter @Setter private int maskIndex = 0; @BeanField @Getter @Setter private RegionMap regionMap = RegionMapSingleton.instance(); @BeanField @Getter @Setter private boolean suppressZ = false; // END BEAN PROPERTIES @Override public double calculate(SessionInput<FeatureInputSingleMemo> input) throws FeatureCalculationException { ObjectMask objectMask = createMask(input.get()); int surfaceSize = estimateSurfaceSize(input.get().getPxlPartMemo(), objectMask); return resolveArea(surfaceSize, input.get().getResolutionOptional()); } private ObjectMask createMask(FeatureInputSingleMemo input) throws FeatureCalculationException { ObjectWithProperties omWithProps = input.getPxlPartMemo() .getMark() .deriveObject( input.dimensionsRequired(), regionMap.membershipWithFlagsForIndex(getRegionID()), BinaryValuesByte.getDefault()); return omWithProps.withoutProperties(); } private int estimateSurfaceSize(VoxelizedMarkMemo pxlMarkMemo, ObjectMask object) throws FeatureCalculationException { BinaryVoxels<UnsignedByteBuffer> voxelsOutline = outline(object, !suppressZ); Extent extent = object.boundingBox().extent(); try { int size = 0; for (int z = 0; z < extent.z(); z++) { VoxelStatistics stats = pxlMarkMemo.voxelized().statisticsFor(maskIndex, 0, z); if (stats.histogram().hasNonZeroCount(1)) { size += voxelsOutline .extract() .slice(z) .extract() .voxelsEqualTo(object.binaryValues().getOnInt()) .count(); } } return size; } catch (OperationFailedException e) { throw new FeatureCalculationException(e); } } private static BinaryVoxels<UnsignedByteBuffer> outline(ObjectMask object, boolean useZ) { OutlineKernel kernel = new OutlineKernel(); KernelApplicationParameters params = new KernelApplicationParameters(OutsideKernelPolicy.AS_OFF, useZ); return ApplyKernel.apply(kernel, object.binaryVoxels(), params); } }
gizatupu/hedera-services
hedera-node/src/test/java/com/hedera/services/grpc/marshalling/ImpliedTransfersMarshalTest.java
package com.hedera.services.grpc.marshalling; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 <NAME>, LLC * ​ * 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. * ‍ */ import com.hedera.services.context.properties.GlobalDynamicProperties; import com.hedera.services.ledger.BalanceChange; import com.hedera.services.ledger.PureTransferSemanticChecks; import com.hedera.services.state.submerkle.AssessedCustomFee; import com.hedera.services.state.submerkle.CustomFee; import com.hedera.services.state.submerkle.EntityId; import com.hedera.services.store.models.Id; import com.hedera.services.txns.customfees.CustomFeeSchedules; import com.hederahashgraph.api.proto.java.AccountID; import com.hederahashgraph.api.proto.java.CryptoTransferTransactionBody; import com.hederahashgraph.api.proto.java.TokenID; import com.hederahashgraph.api.proto.java.TokenTransferList; import com.hederahashgraph.api.proto.java.TransferList; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.hedera.test.utils.IdUtils.adjustFrom; import static com.hedera.test.utils.IdUtils.asAccount; import static com.hedera.test.utils.IdUtils.asToken; import static com.hedera.test.utils.IdUtils.hbarChange; import static com.hedera.test.utils.IdUtils.tokenChange; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.CUSTOM_FEE_OUTSIDE_NUMERIC_RANGE; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INSUFFICIENT_PAYER_BALANCE_FOR_CUSTOM_FEE; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.OK; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.TOKEN_WAS_DELETED; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.TRANSFER_LIST_SIZE_LIMIT_EXCEEDED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) class ImpliedTransfersMarshalTest { private CryptoTransferTransactionBody op; @Mock private GlobalDynamicProperties dynamicProperties; @Mock private PureTransferSemanticChecks transferSemanticChecks; @Mock private CustomFeeSchedules customFeeSchedules; @Mock private CustomFeeSchedules newCustomFeeSchedules; private ImpliedTransfersMarshal subject; private final AccountID aModel = asAccount("1.2.3"); private final AccountID bModel = asAccount("2.3.4"); private final AccountID cModel = asAccount("3.4.5"); private final AccountID payer = asAccount("5.6.7"); private final Id token = new Id(0, 0, 75231); private final Id anotherToken = new Id(0, 0, 75232); private final Id yetAnotherToken = new Id(0, 0, 75233); private final TokenID anId = asToken("<PASSWORD>"); private final TokenID anotherId = asToken("<PASSWORD>"); private final TokenID yetAnotherId = asToken("<PASSWORD>"); private final AccountID a = asAccount("1.2.3"); private final AccountID b = asAccount("2.3.4"); private final AccountID c = asAccount("3.4.5"); private final long aHbarChange = -100L; private final long bHbarChange = +50L; private final long cHbarChange = +50L; private final long aAnotherTokenChange = -50L; private final long bAnotherTokenChange = +25L; private final long cAnotherTokenChange = +25L; private final long bTokenChange = -100L; private final long cTokenChange = +100L; private final long aYetAnotherTokenChange = -15L; private final long bYetAnotherTokenChange = +15L; private final long customFeeChangeToFeeCollector = +20L; private final long customFeeChangeFromPayer = -20L; private final int maxExplicitHbarAdjusts = 5; private final int maxExplicitTokenAdjusts = 50; private final EntityId customFeeToken = new EntityId(0, 0, 123); private final EntityId customFeeCollector = new EntityId(0, 0, 124); final List<Pair<Id, List<CustomFee>>> entityCustomFees = List.of( Pair.of(customFeeToken.asId(), new ArrayList<>())); final List<Pair<EntityId, List<CustomFee>>> newCustomFeeChanges = List.of( Pair.of(customFeeToken, List.of(CustomFee.fixedFee(10L, customFeeToken, customFeeCollector)))); private final List<AssessedCustomFee> assessedCustomFees = List.of( new AssessedCustomFee(customFeeCollector, customFeeToken, 123L)); private final long numerator = 2L; private final long denominator = 100L; private final long minimumUnitsToCollect = 20L; private final long maximumUnitsToCollect = 100L; EntityId feeCollector = EntityId.fromGrpcAccountId(aModel); @BeforeEach void setUp() { subject = new ImpliedTransfersMarshal(dynamicProperties, transferSemanticChecks, customFeeSchedules); } @Test void validatesXfers() { setupFixtureOp(); final var expectedMeta = new ImpliedTransfersMeta( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, TRANSFER_LIST_SIZE_LIMIT_EXCEEDED, Collections.emptyList()); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); // and: given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(TRANSFER_LIST_SIZE_LIMIT_EXCEEDED); // when: final var result = subject.unmarshalFromGrpc(op, bModel); // then: assertEquals(result.getMeta(), expectedMeta); } @Test void getsExpectedList() { setupFixtureOp(); // and: final List<BalanceChange> expectedChanges = List.of(new BalanceChange[] { hbarChange(aModel, aHbarChange + (3 * customFeeChangeToFeeCollector)), hbarChange(bModel, bHbarChange), hbarChange(cModel, cHbarChange), tokenChange(anotherToken, aModel, aAnotherTokenChange), tokenChange(anotherToken, bModel, bAnotherTokenChange), tokenChange(anotherToken, cModel, cAnotherTokenChange), updateCodeForInsufficientBalance(hbarChange(payer, 3 * customFeeChangeFromPayer)), tokenChange(token, bModel, bTokenChange), tokenChange(token, cModel, cTokenChange), tokenChange(yetAnotherToken, aModel, aYetAnotherTokenChange), tokenChange(yetAnotherToken, bModel, bYetAnotherTokenChange), } ); final List<CustomFee> customFee = getFixedCustomFee(); final List<Pair<Id, List<CustomFee>>> expectedCustomFeeChanges = List.of(Pair.of(anotherToken, customFee), Pair.of(token, customFee), Pair.of(yetAnotherToken, customFee)); final List<AssessedCustomFee> expectedAssessedCustomFees = List.of( new AssessedCustomFee(EntityId.fromGrpcAccountId(aModel), customFeeChangeToFeeCollector), new AssessedCustomFee(EntityId.fromGrpcAccountId(aModel), customFeeChangeToFeeCollector), new AssessedCustomFee(EntityId.fromGrpcAccountId(aModel), customFeeChangeToFeeCollector)); // and: final var expectedMeta = new ImpliedTransfersMeta(maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, OK, expectedCustomFeeChanges); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(OK); given(customFeeSchedules.lookupScheduleFor(any())).willReturn(customFee); // when: final var result = subject.unmarshalFromGrpc(op, payer); // then: assertEquals(expectedMeta, result.getMeta()); assertEquals(expectedChanges, result.getAllBalanceChanges()); assertEquals(expectedCustomFeeChanges, result.getTokenFeeSchedules()); assertEquals(expectedAssessedCustomFees, result.getAssessedCustomFees()); } @Test void metaObjectContractSanityChecks() { // given: final var oneMeta = new ImpliedTransfersMeta(3, 4, OK, entityCustomFees); final var twoMeta = new ImpliedTransfersMeta(1, 2, TOKEN_WAS_DELETED, Collections.emptyList()); // and: final var oneRepr = "ImpliedTransfersMeta{code=OK, maxExplicitHbarAdjusts=3, " + "maxExplicitTokenAdjusts=4, customFeeSchedulesUsedInMarshal=[(Id{shard=0, realm=0, num=123},[])" + "]}"; final var twoRepr = "ImpliedTransfersMeta{code=TOKEN_WAS_DELETED, " + "maxExplicitHbarAdjusts=1, maxExplicitTokenAdjusts=2, customFeeSchedulesUsedInMarshal=[]}"; // expect: assertNotEquals(oneMeta, twoMeta); assertNotEquals(oneMeta.hashCode(), twoMeta.hashCode()); // and: assertEquals(oneRepr, oneMeta.toString()); assertEquals(twoRepr, twoMeta.toString()); } @Test void impliedXfersObjectContractSanityChecks() { // given: final var twoChanges = List.of(tokenChange( new Id(1, 2, 3), asAccount("4.5.6"), 7)); final var oneImpliedXfers = ImpliedTransfers.invalid(3, 4, TOKEN_WAS_DELETED); final var twoImpliedXfers = ImpliedTransfers.valid(1, 100, twoChanges, entityCustomFees, assessedCustomFees); // and: final var oneRepr = "ImpliedTransfers{meta=ImpliedTransfersMeta{code=TOKEN_WAS_DELETED, " + "maxExplicitHbarAdjusts=3, maxExplicitTokenAdjusts=4, customFeeSchedulesUsedInMarshal=[]}, " + "changes=[]," + " " + "tokenFeeSchedules=[], assessedCustomFees=[]}"; final var twoRepr = "ImpliedTransfers{meta=ImpliedTransfersMeta{code=OK, maxExplicitHbarAdjusts=1, " + "maxExplicitTokenAdjusts=100, customFeeSchedulesUsedInMarshal=[(Id{shard=0, realm=0, num=123},[])]}," + " changes=[BalanceChange{token=Id{shard=1, realm=2, num=3}, account=Id{shard=4, realm=5, num=6}," + " units=7, codeForInsufficientBalance=INSUFFICIENT_TOKEN_BALANCE}], " + "tokenFeeSchedules=[(Id{shard=0, realm=0, num=123},[])], " + "assessedCustomFees=[AssessedCustomFee{token=EntityId{shard=0, realm=0, num=123}, " + "account=EntityId{shard=0, realm=0, num=124}, units=123}]}"; // expect: assertNotEquals(oneImpliedXfers, twoImpliedXfers); assertNotEquals(oneImpliedXfers.hashCode(), twoImpliedXfers.hashCode()); // and: assertEquals(oneRepr, oneImpliedXfers.toString()); assertEquals(twoRepr, twoImpliedXfers.toString()); } @Test void handlesEasyCase() { // given: long reasonable = 1_234_567L; long n = 10; long d = 9; // and: final var expected = reasonable * n / d; // expect: assertEquals(expected, subject.safeFractionMultiply(n, d, reasonable)); } @Test void fallsBackToArbitraryPrecisionIfNeeded() { // given: long huge = Long.MAX_VALUE / 2; long n = 10; long d = 9; // and: final var expected = BigInteger.valueOf(huge) .multiply(BigInteger.valueOf(n)) .divide(BigInteger.valueOf(d)) .longValueExact(); // expect: assertEquals(expected, subject.safeFractionMultiply(n, d, huge)); } @Test void propagatesArithmeticExceptionOnOverflow() { // given: long huge = Long.MAX_VALUE - 1; long n = 10; long d = 9; // expect: assertThrows(ArithmeticException.class, () -> subject.safeFractionMultiply(n, d, huge)); } @Test void metaRecognizesIdenticalConditions() { // given: final var meta = new ImpliedTransfersMeta(3, 4, OK, entityCustomFees); given(dynamicProperties.maxTransferListSize()).willReturn(3); given(dynamicProperties.maxTokenTransferListSize()).willReturn(4); // expect: assertTrue(meta.wasDerivedFrom(dynamicProperties, customFeeSchedules)); //modify customFeeChanges to see test fails given(newCustomFeeSchedules.lookupScheduleFor(any())).willReturn(newCustomFeeChanges.get(0).getValue()); assertFalse(meta.wasDerivedFrom(dynamicProperties, newCustomFeeSchedules)); // and: given(dynamicProperties.maxTransferListSize()).willReturn(2); given(dynamicProperties.maxTokenTransferListSize()).willReturn(4); // expect: assertFalse(meta.wasDerivedFrom(dynamicProperties, customFeeSchedules)); // and: given(dynamicProperties.maxTransferListSize()).willReturn(3); given(dynamicProperties.maxTokenTransferListSize()).willReturn(3); // expect: assertFalse(meta.wasDerivedFrom(dynamicProperties, customFeeSchedules)); } @Test void translatesOverflowFromExcessiveSumming() { op = CryptoTransferTransactionBody.newBuilder() .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, Long.MAX_VALUE), adjustFrom(b, Long.MAX_VALUE / 2) ))).build(); // and: final var expected = ImpliedTransfers.invalid( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, CUSTOM_FEE_OUTSIDE_NUMERIC_RANGE); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(OK); // when: final var actual = subject.unmarshalFromGrpc(op, payer); // then: assertEquals(expected, actual); } @Test void translatesOverflowFromFractionalCalc() { op = CryptoTransferTransactionBody.newBuilder() .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, cHbarChange) ))).build(); // and: final var customFee = getOverflowingFractionalCustomFee(); // and: final var expected = ImpliedTransfers.invalid( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, CUSTOM_FEE_OUTSIDE_NUMERIC_RANGE); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(OK); given(customFeeSchedules.lookupScheduleFor(any())).willReturn(customFee); // when: final var actual = subject.unmarshalFromGrpc(op, payer); // then: assertEquals(expected, actual); } @Test void getsExpectedListWithFractionalCustomFee() { op = CryptoTransferTransactionBody.newBuilder() .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, cHbarChange) ))).build(); // and: final var expectedFractionalFee = Math.min( Math.max(numerator * cHbarChange / denominator, minimumUnitsToCollect), maximumUnitsToCollect); final var expectedChanges = List.of(new BalanceChange[] { tokenChange(anotherToken, aModel, cHbarChange + expectedFractionalFee), updateCodeForInsufficientBalance(tokenChange(anotherToken, payer, -expectedFractionalFee)) }); final var customFee = getFractionalCustomFee(); final var expectedCustomFeeChanges = List.of(Pair.of(anotherToken, customFee)); final var expectedAssessedCustomFees = List.of( new AssessedCustomFee(EntityId.fromGrpcAccountId(aModel), anotherToken.asEntityId(), expectedFractionalFee)); // and: final var expectedMeta = new ImpliedTransfersMeta(maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, OK, expectedCustomFeeChanges); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(OK); given(customFeeSchedules.lookupScheduleFor(any())).willReturn(customFee); // when: final var result = subject.unmarshalFromGrpc(op, payer); // then: assertEquals(expectedMeta, result.getMeta()); assertEquals(expectedChanges, result.getAllBalanceChanges()); assertEquals(expectedCustomFeeChanges, result.getTokenFeeSchedules()); assertEquals(expectedAssessedCustomFees, result.getAssessedCustomFees()); } @Test void throwsForFractionalZeroDenominator() { op = CryptoTransferTransactionBody.newBuilder() .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, cHbarChange) ))).build(); // and: var exception = assertThrows(IllegalArgumentException.class, () -> CustomFee.fractionalFee(numerator, 0, minimumUnitsToCollect, maximumUnitsToCollect, feeCollector)); assertEquals("Division by zero is not allowed", exception.getMessage()); } @Test void getsExpectedListWithFixedCustomFeeNonNullDenomination() { op = CryptoTransferTransactionBody.newBuilder() .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, cHbarChange) ))).build(); // and: final var expectedChanges = List.of(new BalanceChange[] { tokenChange(anotherToken, aModel, cHbarChange), tokenChange(token, aModel, 20L), updateCodeForInsufficientBalance(tokenChange(token, payer, -20L)) }); final var customFee = getFixedCustomFeeNonNullDenom(); final var expectedCustomFeeChanges = List.of(Pair.of(anotherToken, customFee)); final var expectedAssessedCustomFees = List.of( new AssessedCustomFee(EntityId.fromGrpcAccountId(aModel), token.asEntityId(), 20L)); // and: final var expectedMeta = new ImpliedTransfersMeta(maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, OK, expectedCustomFeeChanges); given(dynamicProperties.maxTransferListSize()).willReturn(maxExplicitHbarAdjusts); given(dynamicProperties.maxTokenTransferListSize()).willReturn(maxExplicitTokenAdjusts); given(transferSemanticChecks.fullPureValidation( maxExplicitHbarAdjusts, maxExplicitTokenAdjusts, op.getTransfers(), op.getTokenTransfersList())).willReturn(OK); given(customFeeSchedules.lookupScheduleFor(anotherToken.asEntityId())).willReturn(customFee); // when: final var result = subject.unmarshalFromGrpc(op, payer); // then: assertEquals(expectedMeta, result.getMeta()); assertEquals(expectedChanges, result.getAllBalanceChanges()); assertEquals(expectedCustomFeeChanges, result.getTokenFeeSchedules()); assertEquals(expectedAssessedCustomFees, result.getAssessedCustomFees()); } private void setupFixtureOp() { var hbarAdjusts = TransferList.newBuilder() .addAccountAmounts(adjustFrom(a, -100)) .addAccountAmounts(adjustFrom(b, 50)) .addAccountAmounts(adjustFrom(c, 50)) .build(); op = CryptoTransferTransactionBody.newBuilder() .setTransfers(hbarAdjusts) .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anotherId) .addAllTransfers(List.of( adjustFrom(a, -50), adjustFrom(b, 25), adjustFrom(c, 25) ))) .addTokenTransfers(TokenTransferList.newBuilder() .setToken(anId) .addAllTransfers(List.of( adjustFrom(b, -100), adjustFrom(c, 100) ))) .addTokenTransfers(TokenTransferList.newBuilder() .setToken(yetAnotherId) .addAllTransfers(List.of( adjustFrom(a, -15), adjustFrom(b, 15) ))) .build(); } private List<CustomFee> getFixedCustomFee() { return List.of( CustomFee.fixedFee(20L, null, feeCollector) ); } private List<CustomFee> getFixedCustomFeeNonNullDenom() { return List.of( CustomFee.fixedFee(20L, token.asEntityId(), feeCollector) ); } private List<CustomFee> getFractionalCustomFee() { return List.of( CustomFee.fractionalFee( numerator, denominator, minimumUnitsToCollect, maximumUnitsToCollect, feeCollector) ); } private List<CustomFee> getOverflowingFractionalCustomFee() { return List.of( CustomFee.fractionalFee( Long.MAX_VALUE, 2, minimumUnitsToCollect, maximumUnitsToCollect, feeCollector) ); } private BalanceChange updateCodeForInsufficientBalance(BalanceChange change) { change.setCodeForInsufficientBalance(INSUFFICIENT_PAYER_BALANCE_FOR_CUSTOM_FEE); return change; } }
Ks89/BYAManager
src/main/java/it/stefanocappa/gui/splashscreen/SplashScreen.java
/* Copyright 2011-2015 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package it.stefanocappa.gui.splashscreen; import it.stefanocappa.gui.kcomponent.KColors; import it.stefanocappa.gui.kcomponent.KPanel; import java.awt.*; import java.awt.image.ImageObserver; import java.net.URL; import javax.swing.JPanel; public class SplashScreen implements ImageObserver { private static SplashScreen instance = new SplashScreen(); /** * @uml.property name="image" */ private Image image ; /** * @uml.property name="label" */ private Label label = new Label ("Loading..." , Label.CENTER ); /** * @uml.property name="panel" * @uml.associationEnd */ private JPanel panel = new KPanel(); /** * @uml.property name="frame" */ private Frame frame ; /** * @uml.property name="splashTime" */ private long splashTime = 0; public static SplashScreen getInstance() { return instance; } public SplashScreen (String filename) { setImage(filename) ; } public SplashScreen (URL url) { setImage(url) ; } public SplashScreen() { //costruttore vuoto } public final void setImage (String filename) { image=Toolkit.getDefaultToolkit( ).getImage(filename) ; } public final void setImage (URL url) { image = Toolkit.getDefaultToolkit( ).getImage(url) ; } public void splash (String filename){ splash(Toolkit.getDefaultToolkit( ).getImage(filename)) ; } public void splash (URL url){ splash(Toolkit.getDefaultToolkit( ).getImage(url)) ; } public void splash(){ if (image!=null) { splash(image); } else { splash (Toolkit.getDefaultToolkit( ).getImage("splashbeta1.png")); } } public void splash (Image img) { image = img ; frame = new Frame(); frame.setUndecorated(true) ; if (!Toolkit.getDefaultToolkit().prepareImage(image,-1,-1,this)) { return; } splashScreen(); } @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { boolean allbits = infoflags == ImageObserver . ALLBITS ; if( allbits ) { splashScreen() ; } return !allbits; } private void splashScreen() { if (frame == null) { return; } final int width = image.getWidth(null) ; final int height = image.getHeight(null); Canvas canvas = new Canvas() { private static final long serialVersionUID = 2501900998022630894L; public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.drawImage(image,0,0,this); } public Dimension getPreferredSize() { return new Dimension(width, height); } }; frame.add(canvas,BorderLayout.CENTER); //ancora da migliorare //TODO MIGLIORARE BARRA SPLASHSCREEN label.setBackground(KColors.getNero()); label.setForeground(KColors.getVerde()); panel.setDoubleBuffered(true); panel.setLayout(new BorderLayout()); panel.add(label, BorderLayout.CENTER); frame.add(panel,BorderLayout.SOUTH); frame.pack(); Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize(); Dimension frameSize = frame.getSize(); frame.setLocation((screenSize.width - frameSize.width ) >> 1, (screenSize.height - frameSize.height) >> 1); frame.setVisible(true); splashTime = System . currentTimeMillis(); } public void showStatus(String s) { label.setText(s); } public void waitForSplash ( ) { MediaTracker mt = new MediaTracker(frame) ; mt.addImage(image,0) ; try{ mt.waitForID(0) ; } catch (InterruptedException ie) { } } public void waitForSplash ( long ms ) { MediaTracker mt = new MediaTracker ( frame ) ; mt.addImage(image,0); try{ mt.waitForID(0,ms); } catch (InterruptedException ie) { } } public void delayForSplash ( ) { int cpus = Runtime.getRuntime().availableProcessors(); switch (cpus) { case 0 : case 1 : waitForSplash(); break; case 2 : case 3 : default : waitForSplash(1000/cpus); } } public void splashFor (int ms ) { if ( splashTime == 0 ) { return ; } long splashDuration = System.currentTimeMillis( ) - splashTime ; if(splashDuration<ms) { try{ Thread.sleep(ms - splashDuration) ; } catch (InterruptedException ie ) { //TODO } } } public void dispose () { frame.remove(label); frame.dispose(); frame = null ; splashTime = 0 ; } }
grasscy/gemini
httpclient/request_test.go
package httpclient import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" ) type Response struct { ErrCode int `json:"errCode"` ErrMsg string `json:"errMsg"` Data *struct { Name string `json:"name"` Age int `json:"age"` } `json:"data"` } var s = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { if request.URL.Path == "/test" { resp := Response{ ErrCode: 200, ErrMsg: "success", Data: &struct { Name string `json:"name"` Age int `json:"age"` }{Name: "lijianfeng", Age: 29}, } data, _ := json.Marshal(&resp) writer.Header().Set("Content-Type", "application/json") writer.WriteHeader(200) writer.Write(data) } })) func TestNew(t *testing.T) { client := New() if client == nil { t.FailNow() } } func TestReqClient_RGet(t *testing.T) { t.Log(s.Listener.Addr()) var resp Response client := New() c, _ := context.WithCancel(context.TODO()) _ = client.RGet("http://"+s.Listener.Addr().String()+"/test", nil, c, &resp) t.Log(resp) } func TestReqClient_RPost(t *testing.T) { t.Log(s.Listener.Addr()) var resp Response client := New() c, _ := context.WithCancel(context.TODO()) _ = client.RPost("http://"+s.Listener.Addr().String()+"/test", nil, c, &resp) t.Log(resp) } func TestReqClient_RPut(t *testing.T) { t.Log(s.Listener.Addr()) var resp Response client := New() c, _ := context.WithCancel(context.TODO()) _ = client.RPut("http://"+s.Listener.Addr().String()+"/test", nil, c, &resp) t.Log(resp) } func TestReqClient_RDelete(t *testing.T) { t.Log(s.Listener.Addr()) var resp Response client := New() c, _ := context.WithCancel(context.TODO()) _ = client.RDelete("http://"+s.Listener.Addr().String()+"/test", nil, c, &resp) t.Log(resp) }
mayurhole/optaplanner
optaplanner-core/src/test/java/org/optaplanner/core/impl/solver/termination/BestScoreTerminationTest.java
<gh_stars>10-100 /* * Copyright 2014 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. */ package org.optaplanner.core.impl.solver.termination; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.math.BigDecimal; import org.junit.jupiter.api.Test; import org.optaplanner.core.api.score.buildin.bendable.BendableScore; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.optaplanner.core.api.score.buildin.hardsoftbigdecimal.HardSoftBigDecimalScore; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.api.score.buildin.simplebigdecimal.SimpleBigDecimalScore; import org.optaplanner.core.impl.phase.scope.AbstractPhaseScope; import org.optaplanner.core.impl.score.buildin.simple.SimpleScoreDefinition; import org.optaplanner.core.impl.score.definition.ScoreDefinition; import org.optaplanner.core.impl.solver.scope.DefaultSolverScope; public class BestScoreTerminationTest { @Test public void solveTermination() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(1); Termination termination = new BestScoreTermination(scoreDefinition, SimpleScore.of(-1000), new double[] {}); DefaultSolverScope solverScope = mock(DefaultSolverScope.class); when(solverScope.getScoreDefinition()).thenReturn(new SimpleScoreDefinition()); when(solverScope.isBestSolutionInitialized()).thenReturn(true); when(solverScope.getStartingInitializedScore()).thenReturn(SimpleScore.of(-1100)); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-1100)); assertEquals(false, termination.isSolverTerminated(solverScope)); assertEquals(0.0, termination.calculateSolverTimeGradient(solverScope), 0.0); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-1100)); assertEquals(false, termination.isSolverTerminated(solverScope)); assertEquals(0.0, termination.calculateSolverTimeGradient(solverScope), 0.0); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-1040)); assertEquals(false, termination.isSolverTerminated(solverScope)); assertEquals(0.6, termination.calculateSolverTimeGradient(solverScope), 0.0); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-1040)); assertEquals(false, termination.isSolverTerminated(solverScope)); assertEquals(0.6, termination.calculateSolverTimeGradient(solverScope), 0.0); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-1000)); assertEquals(true, termination.isSolverTerminated(solverScope)); assertEquals(1.0, termination.calculateSolverTimeGradient(solverScope), 0.0); when(solverScope.getBestScore()).thenReturn(SimpleScore.of(-900)); assertEquals(true, termination.isSolverTerminated(solverScope)); assertEquals(1.0, termination.calculateSolverTimeGradient(solverScope), 0.0); } @Test public void phaseTermination() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(1); Termination termination = new BestScoreTermination(scoreDefinition, SimpleScore.of(-1000), new double[] {}); AbstractPhaseScope phaseScope = mock(AbstractPhaseScope.class); when(phaseScope.getScoreDefinition()).thenReturn(new SimpleScoreDefinition()); when(phaseScope.isBestSolutionInitialized()).thenReturn(true); when(phaseScope.getStartingScore()).thenReturn(SimpleScore.of(-1100)); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-1100)); assertEquals(false, termination.isPhaseTerminated(phaseScope)); assertEquals(0.0, termination.calculatePhaseTimeGradient(phaseScope), 0.0); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-1100)); assertEquals(false, termination.isPhaseTerminated(phaseScope)); assertEquals(0.0, termination.calculatePhaseTimeGradient(phaseScope), 0.0); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-1040)); assertEquals(false, termination.isPhaseTerminated(phaseScope)); assertEquals(0.6, termination.calculatePhaseTimeGradient(phaseScope), 0.0); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-1040)); assertEquals(false, termination.isPhaseTerminated(phaseScope)); assertEquals(0.6, termination.calculatePhaseTimeGradient(phaseScope), 0.0); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-1000)); assertEquals(true, termination.isPhaseTerminated(phaseScope)); assertEquals(1.0, termination.calculatePhaseTimeGradient(phaseScope), 0.0); when(phaseScope.getBestScore()).thenReturn(SimpleScore.of(-900)); assertEquals(true, termination.isPhaseTerminated(phaseScope)); assertEquals(1.0, termination.calculatePhaseTimeGradient(phaseScope), 0.0); } @Test public void calculateTimeGradientSimpleScore() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(1); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, SimpleScore.of(10), new double[] {}); assertEquals(0.0, termination.calculateTimeGradient( SimpleScore.of(0), SimpleScore.of(10), SimpleScore.of(0)), 0.0); assertEquals(0.6, termination.calculateTimeGradient( SimpleScore.of(0), SimpleScore.of(10), SimpleScore.of(6)), 0.0); assertEquals(1.0, termination.calculateTimeGradient( SimpleScore.of(0), SimpleScore.of(10), SimpleScore.of(10)), 0.0); assertEquals(1.0, termination.calculateTimeGradient( SimpleScore.of(0), SimpleScore.of(10), SimpleScore.of(11)), 0.0); assertEquals(0.25, termination.calculateTimeGradient( SimpleScore.of(-10), SimpleScore.of(30), SimpleScore.of(0)), 0.0); assertEquals(0.33333, termination.calculateTimeGradient( SimpleScore.of(10), SimpleScore.of(40), SimpleScore.of(20)), 0.00001); } @Test public void calculateTimeGradientSimpleBigDecimalScore() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(1); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, SimpleBigDecimalScore.of(new BigDecimal("10.00")), new double[] {}); assertEquals(0.0, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("0.00")), SimpleBigDecimalScore.of(new BigDecimal("10.00")), SimpleBigDecimalScore.of(new BigDecimal("0.00"))), 0.0); assertEquals(0.6, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("0.00")), SimpleBigDecimalScore.of(new BigDecimal("10.00")), SimpleBigDecimalScore.of(new BigDecimal("6.00"))), 0.0); assertEquals(1.0, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("0.00")), SimpleBigDecimalScore.of(new BigDecimal("10.00")), SimpleBigDecimalScore.of(new BigDecimal("10.00"))), 0.0); assertEquals(1.0, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("0.00")), SimpleBigDecimalScore.of(new BigDecimal("10.00")), SimpleBigDecimalScore.of(new BigDecimal("11.00"))), 0.0); assertEquals(0.25, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("-10.00")), SimpleBigDecimalScore.of(new BigDecimal("30.00")), SimpleBigDecimalScore.of(new BigDecimal("0.00"))), 0.0); assertEquals(0.33333, termination.calculateTimeGradient( SimpleBigDecimalScore.of(new BigDecimal("10.00")), SimpleBigDecimalScore.of(new BigDecimal("40.00")), SimpleBigDecimalScore.of(new BigDecimal("20.00"))), 0.00001); } @Test public void calculateTimeGradientHardSoftScore() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(2); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, HardSoftScore.of(-10, -300), new double[] { 0.75 }); // Normal cases // Smack in the middle assertEquals(0.6, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-14, -340)), 0.0); // No hard broken, total soft broken assertEquals(0.75, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -400)), 0.0); // Total hard broken, no soft broken assertEquals(0.25, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-20, -300)), 0.0); // No hard broken, more than total soft broken assertEquals(0.75, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -900)), 0.0); // More than total hard broken, no soft broken assertEquals(0.0, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-90, -300)), 0.0); // Perfect min/max cases assertEquals(1.0, termination.calculateTimeGradient( HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -300)), 0.0); assertEquals(0.0, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-20, -400)), 0.0); assertEquals(1.0, termination.calculateTimeGradient( HardSoftScore.of(-20, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -300)), 0.0); // Hard total delta is 0 assertEquals(0.75 + (0.6 * 0.25), termination.calculateTimeGradient( HardSoftScore.of(-10, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-10, -340)), 0.0); assertEquals(0.0, termination.calculateTimeGradient( HardSoftScore.of(-10, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-20, -340)), 0.0); assertEquals(1.0, termination.calculateTimeGradient( HardSoftScore.of(-10, -400), HardSoftScore.of(-10, -300), HardSoftScore.of(-0, -340)), 0.0); // Soft total delta is 0 assertEquals((0.6 * 0.75) + 0.25, termination.calculateTimeGradient( HardSoftScore.of(-20, -300), HardSoftScore.of(-10, -300), HardSoftScore.of(-14, -300)), 0.0); assertEquals(0.6 * 0.75, termination.calculateTimeGradient( HardSoftScore.of(-20, -300), HardSoftScore.of(-10, -300), HardSoftScore.of(-14, -400)), 0.0); assertEquals((0.6 * 0.75) + 0.25, termination.calculateTimeGradient( HardSoftScore.of(-20, -300), HardSoftScore.of(-10, -300), HardSoftScore.of(-14, -0)), 0.0); } @Test public void calculateTimeGradientHardSoftBigDecimalScore() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(2); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), new double[] { 0.75 }); // hard == soft assertEquals(0.0, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00")), HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00"))), 0.0); assertEquals(0.6, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00")), HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), HardSoftBigDecimalScore.of(new BigDecimal("6.00"), new BigDecimal("6.00"))), 0.0); assertEquals(1.0, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00")), HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00"))), 0.0); assertEquals(1.0, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00")), HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), HardSoftBigDecimalScore.of(new BigDecimal("11.00"), new BigDecimal("11.00"))), 0.0); assertEquals(0.25, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("-10.00"), new BigDecimal("-10.00")), HardSoftBigDecimalScore.of(new BigDecimal("30.00"), new BigDecimal("30.00")), HardSoftBigDecimalScore.of(new BigDecimal("0.00"), new BigDecimal("0.00"))), 0.0); assertEquals(0.33333, termination.calculateTimeGradient( HardSoftBigDecimalScore.of(new BigDecimal("10.00"), new BigDecimal("10.00")), HardSoftBigDecimalScore.of(new BigDecimal("40.00"), new BigDecimal("40.00")), HardSoftBigDecimalScore.of(new BigDecimal("20.00"), new BigDecimal("20.00"))), 0.00001); } @Test public void calculateTimeGradientBendableScoreHS() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(2); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, BendableScore.of(new int[] { -10 }, new int[] { -300 }), new double[] { 0.75 }); // Normal cases // Smack in the middle assertEquals(0.6, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -14 }, new int[] { -340 })), 0.0); // No hard broken, total soft broken assertEquals(0.75, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -400 })), 0.0); // Total hard broken, no soft broken assertEquals(0.25, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -20 }, new int[] { -300 })), 0.0); // No hard broken, more than total soft broken assertEquals(0.75, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -900 })), 0.0); // More than total hard broken, no soft broken assertEquals(0.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -90 }, new int[] { -300 })), 0.0); // Perfect min/max cases assertEquals(1.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 })), 0.0); assertEquals(0.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -20 }, new int[] { -400 })), 0.0); assertEquals(1.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 })), 0.0); // Hard total delta is 0 assertEquals(0.75 + (0.6 * 0.25), termination.calculateTimeGradient( BendableScore.of(new int[] { -10 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -340 })), 0.0); assertEquals(0.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -10 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -20 }, new int[] { -340 })), 0.0); assertEquals(1.0, termination.calculateTimeGradient( BendableScore.of(new int[] { -10 }, new int[] { -400 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -0 }, new int[] { -340 })), 0.0); // Soft total delta is 0 assertEquals((0.6 * 0.75) + 0.25, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -14 }, new int[] { -300 })), 0.0); assertEquals(0.6 * 0.75, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -14 }, new int[] { -400 })), 0.0); assertEquals((0.6 * 0.75) + 0.25, termination.calculateTimeGradient( BendableScore.of(new int[] { -20 }, new int[] { -300 }), BendableScore.of(new int[] { -10 }, new int[] { -300 }), BendableScore.of(new int[] { -14 }, new int[] { -0 })), 0.0); } @Test public void calculateTimeGradientBendableScoreHHSSS() { ScoreDefinition scoreDefinition = mock(ScoreDefinition.class); when(scoreDefinition.getLevelsSize()).thenReturn(5); BestScoreTermination termination = new BestScoreTermination(scoreDefinition, BendableScore.of(new int[] { 0, 0 }, new int[] { 0, 0, -10 }), new double[] { 0.75, 0.75, 0.75, 0.75 }); // Normal cases // Smack in the middle assertEquals(0.6 * 0.75 + 0.6 * 0.25 * 0.75, termination.calculateTimeGradient( BendableScore.of(new int[] { -10, -100 }, new int[] { -50, -60, -70 }), BendableScore.of(new int[] { 0, 0 }, new int[] { 0, 0, -10 }), BendableScore.of(new int[] { -4, -40 }, new int[] { -50, -60, -70 })), 0.0); } }
tangweikun/leetcode
src/1437-check-if-all-1s-are-at-least-length-k-places-away/index.js
/** * @param {number[]} nums * @param {number} k * @return {boolean} */ var kLengthApart = function (nums, k) { const stack = []; for (let i = 0; i < nums.length; i++) { if (nums[i] === 1) { stack.push(i); } if (stack.length > 1) { if (stack[stack.length - 1] - stack[stack.length - 2] <= k) { return false; } } } return true; };
rafaelcardoso/design-system
packages/build/postcss/postcss-css-var-sass-var.js
const postcss = require('postcss') const dashify = require('../css/dashify') const createSassVar = (decl, options) => { const node = postcss.parse(` $${dashify(decl.prop.replace('--', ''))}: ${decl.value}; `) decl.root().insertAfter(decl.root(), node) } module.exports = postcss.plugin('css-var-selectors', options => { return css => { options = options || {} css.walkRules(rule => { rule.walkDecls((decl, i) => { const isCssVar = /^--/.test(decl.prop) if (isCssVar) createSassVar(decl, options) }) const isCssVarRoot = rule.selector === ':root' if (isCssVarRoot) rule.remove() }) } })
djmisterjon/PIXI.ProStageMap
js/core/polyfill.js
//============================================================================= // hack JsExtensions snippet polyfill to class //============================================================================= // see: C:\Users\InformatiqueLepage\AppData\Local\Programs\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es5.d.ts // C:\Users\InformatiqueLepage\Documents\Dev\anft_1.6.1\js\index.d.ts /** * Returns a number whose value is limited to the given range. * * @method Number.prototype.clamp * @param {Number} min The lower boundary * @param {Number} max The upper boundary * @return {Number} A number in the range (min, max) */ Number.prototype.clamp = function(min, max) { return Math.min(Math.max(this, min), max); }; /** * Returns a modulo value which is always positive. * * @method Number.prototype.mod * @param {Number} n The divisor * @return {Number} A modulo value */ Number.prototype.mod = function(n) { return ((this % n) + n) % n; }; /** * Replaces %1, %2 and so on in the string to the arguments. * * @method String.prototype.format * @param {Any} ...args The objects to format * @return {String} A formatted string */ String.prototype.format = function() { var args = arguments; return this.replace(/%([0-9]+)/g, function(s, n) { return args[Number(n) - 1]; }); }; /** * Makes a number string with leading zeros. * * @method String.prototype.padZero * @param {Number} length The length of the output string * @return {String} A string with leading zeros */ String.prototype.padZero = function(length){ var s = this; while (s.length < length) { s = '0' + s; } return s; }; /** * Makes a number string with leading zeros. * * @method Number.prototype.padZero * @param {Number} length The length of the output string * @return {String} A string with leading zeros */ Number.prototype.padZero = function(length){ return String(this).padZero(length); }; Object.defineProperties(Array.prototype, { /** * Checks whether the two arrays are same. * * @method Array.prototype.equals * @param {Array} array The array to compare to * @return {Boolean} True if the two arrays are same */ equals: { enumerable: false, value: function(array) { if (!array || this.length !== array.length) { return false; } for (var i = 0; i < this.length; i++) { if (this[i] instanceof Array && array[i] instanceof Array) { if (!this[i].equals(array[i])) { return false; } } else if (this[i] !== array[i]) { return false; } } return true; } }, /** * Makes a shallow copy of the array. * * @method Array.prototype.clone * @return {Array} A shallow copy of the array */ clone: { enumerable: false, value: function() { return this.slice(0); } }, /** * Checks whether the array contains a given element. * * @method Array.prototype.contains * @param {Any} element The element to search for * @return {Boolean} True if the array contains a given element */ contains : { enumerable: false, value: function(element) { if(Array.isArray(element)){ for (let i=0, l=element.length; i<l; i++) { if(this.indexOf(element[i]) >= 0){return true} }; }else{ return this.indexOf(element) >= 0; }; } }, }); /** * Checks whether the string contains a given string. * * @method String.prototype.contains * @param {String} string The string to search for * @return {Boolean} True if the string contains a given string */ String.prototype.contains = function(string) { return this.indexOf(string) >= 0; }; /** * Generates a random integer in the range or float with precision * * @static * @method Math.randomInt * @param {Number} min negative value will allow random negative positive result * @param {Number} max * @param {Number} precision * @return {Number} A random integer */ Math.randomFrom = function(min=0,max=1,precision=0) // min and max included { const ranNeg = min<0? (min*=-1) && this.random() >= 0.5 && 1 || -1 : 1; return precision? parseFloat(Math.min(min + (Math.random() * (max - min)),max).toFixed(precision))*ranNeg : ~~(Math.random()*(max-min+1)+min)*ranNeg; } /** calcul la base de luck par multiple 10 */ Math.ranLuckFrom = function(luck,pass) // min and max included { const rate = luck/10; // ex: lck:20 => 2; for (let i=0, l=luck/10; i<l; i++) { const test = this.randomFrom(0,100); if(test<pass){return true}; }; return false; } /** * remove specific element in array by indexOf * * @static * @method Array.prototype.remove * @param {Number} arguments * @return {Array} */ Object.defineProperty(Array.prototype, 'remove', { value: function() { let what, a = arguments, L = a.length, ax; while (L && this.length) { what = a[--L]; while ((ax = this.indexOf(what)) !== -1) { this.splice(ax, 1); } }; return this; }, }); /** * find first avaible slot index in Array * * @static * @method Array.prototype.findEmptyIndex * @return {Number} */ Array.prototype.findEmptyIndex = function() { for (let i=0, l=this.length+1; i<l; i++) { if(!this[i]){return i}; }; }; // ajouter un system integrity via hashing String.prototype.hashCode = function() { var hash = 0, i, chr; if (this.length === 0) return hash; for (i = 0; i < this.length; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; };
vineetit1991/assetgraph
testdata/transforms/bundleSystemJs/assetPlugin/main.js
<reponame>vineetit1991/assetgraph var fooOrBarTxt = require('./test-#{fooOrBar}.txt'); var iframe = document.createElement('iframe'); iframe.src = fooOrBarTxt; document.body.appendChild(iframe);
opencounter/converge
graph/merge_duplicates.go
// Copyright © 2016 Asteris, LLC // // 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 graph import ( "strings" "sync" "github.com/asteris-llc/converge/graph/node" "github.com/asteris-llc/converge/helpers/logging" "github.com/mitchellh/hashstructure" "golang.org/x/net/context" ) // SkipMergeFunc will be used to determine whether or not to merge a node type SkipMergeFunc func(*node.Node) bool // MergeDuplicates removes duplicates in the graph func MergeDuplicates(ctx context.Context, g *Graph, skip SkipMergeFunc) (*Graph, error) { lock := new(sync.Mutex) values := map[uint64]string{} logger := logging.GetLogger(ctx).WithField("function", "MergeDuplicates") return g.RootFirstTransform(ctx, func(meta *node.Node, out *Graph) error { if IsRoot(meta.ID) { return nil } if skip(meta) { logger.WithField("id", meta.ID).Debug("skipping by request") return nil } if meta.Value() == nil { return nil // not much use in hashing a nil value } lock.Lock() defer lock.Unlock() hash, err := hashstructure.Hash(meta.Value(), nil) if err != nil { return err } // if we haven't seen this value before, register it and return target, ok := values[hash] if !ok { logger.WithField("id", meta.ID).Debug("registering as original") values[hash] = meta.ID return nil } logger.WithField("id", target).WithField("duplicate", meta.ID).Debug("found duplicate") // Point all inbound links to value to target instead for _, src := range Sources(g.UpEdges(meta.ID)) { logger.WithField("src", src).WithField("duplicate", meta.ID).WithField("target", target).Debug("re-pointing dependency") out.Disconnect(src, meta.ID) out.Connect(src, target) } // Remove children and their edges for _, child := range g.Descendents(meta.ID) { logger.WithField("child", child).Debug("removing child") out.Remove(child) } // Remove value out.Remove(meta.ID) return nil }) } // helper functions for various things we need to merge. // TODO: find a better home // SkipModuleAndParams skips trimming modules and params func SkipModuleAndParams(meta *node.Node) bool { base := BaseID(meta.ID) _, isConditional := meta.LookupMetadata("conditional-switch-name") return strings.HasPrefix(base, "module") || strings.HasPrefix(base, "param") || isConditional }
PopCap/GameIdea
Engine/Source/Runtime/Engine/Private/PhysicsEngine2D/Box2DIntegration.h
<gh_stars>0 // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #if WITH_BOX2D #include <Box2D/Box2D.h> ////////////////////////////////////////////////////////////////////////// // Tick function that starts the physics tick struct FStartPhysics2DTickFunction : public FTickFunction { struct FPhysicsScene2D* Target; // FTickFunction interface virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override; virtual FString DiagnosticMessage() override; // End of FTickFunction interface }; // Tick function that ends the physics tick struct FEndPhysics2DTickFunction : public FTickFunction { struct FPhysicsScene2D* Target; // FTickFunction interface virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override; virtual FString DiagnosticMessage() override; // End of FTickFunction interface }; ////////////////////////////////////////////////////////////////////////// // FPhysicsWorld2D struct FPhysicsScene2D : public b2ContactFilter { class b2World* World; UWorld* UnrealWorld; // Tick function for starting physics FStartPhysics2DTickFunction StartPhysicsTickFunction; // Tick function for ending physics FEndPhysics2DTickFunction EndPhysicsTickFunction; public: FPhysicsScene2D(UWorld* AssociatedWorld); virtual ~FPhysicsScene2D(); // b2ContactFilter interface virtual bool ShouldCollide(b2Fixture* FixtureA, b2Fixture* FixtureB) override; // End of b2ContactFilter interface }; #endif ////////////////////////////////////////////////////////////////////////// // FPhysicsIntegration2D struct FPhysicsIntegration2D : public FGCObject { //@TODO: HACKY #define UnrealUnitsPerMeter 100.0f static void InitializePhysics(); static void ShutdownPhysics(); // FSerializableObject interface virtual void AddReferencedObjects(FReferenceCollector& Collector) override; // End of FSerializableObject static void DrawDebugPhysics(UWorld* World, FPrimitiveDrawInterface* PDI, const FSceneView* View); #if WITH_BOX2D private: static TMap< UWorld*, TSharedPtr<FPhysicsScene2D> > WorldMappings; static FWorldDelegates::FWorldInitializationEvent::FDelegate OnWorldCreatedDelegate; static FWorldDelegates::FWorldEvent::FDelegate OnWorldDestroyedDelegate; static FDelegateHandle OnWorldCreatedDelegateHandle; static FDelegateHandle OnWorldDestroyedDelegateHandle; public: //@TODO: BOX2D: These conversion functions ignore the Paper2D coordinate system (they are fixed on a XZ coordinate system) static inline FVector ConvertBoxVectorToUnreal(const b2Vec2& Vector) { return FVector(Vector.x * UnrealUnitsPerMeter, 0.0f, Vector.y * UnrealUnitsPerMeter); } static inline b2Vec2 ConvertUnrealVectorToBox(const FVector& Vector) { return b2Vec2(Vector.X / UnrealUnitsPerMeter, Vector.Z / UnrealUnitsPerMeter); } static inline float ConvertUnrealAngularVelocityToBox(const FVector& AngularVelocity) { return FMath::DegreesToRadians<float>(AngularVelocity.Y); } static inline FVector ConvertBoxAngularVelocityToUnreal(const float AngularVelocity) { return FVector(0.0f, FMath::RadiansToDegrees<float>(AngularVelocity), 0.0f); } // Converts Unreal torque to torque about the 2D 'Z' axis in Nm static inline float ConvertUnrealTorqueToBox(const FVector& Torque3D) { const FVector ProjectedTorque = Torque3D.ProjectOnTo(FVector(0.0f, -1.0f, 0.0f)); return ProjectedTorque.Size() / UnrealUnitsPerMeter; } static inline float ConvertUnrealVectorToPerpendicularDistance(const FVector& Vector) { return Vector.Y; } // Finds the scene associated with the specified UWorld static TSharedPtr<FPhysicsScene2D> FindAssociatedScene(UWorld* Source); // Finds the Box2D world associated with the specified UWorld static b2World* FindAssociatedWorld(UWorld* Source); static void OnWorldCreated(UWorld* World, const UWorld::InitializationValues IVS); static void OnWorldDestroyed(UWorld* World); #endif private: FPhysicsIntegration2D() {} };
knmcguire/gap_sdk
tools/gap8-openocd/src/target/target_request.h
/*************************************************************************** * Copyright (C) 2007 by <NAME> * * <EMAIL> * * * * Copyright (C) 2007,2008 <NAME> * * <EMAIL> * * * * Copyright (C) 2008 by <NAME> * * <EMAIL> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * 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, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #ifndef OPENOCD_TARGET_TARGET_REQUEST_H #define OPENOCD_TARGET_TARGET_REQUEST_H struct target; struct command_context; typedef enum target_req_cmd { TARGET_REQ_TRACEMSG, TARGET_REQ_DEBUGMSG, TARGET_REQ_DEBUGCHAR, /* TARGET_REQ_SEMIHOSTING, */ } target_req_cmd_t; struct debug_msg_receiver { struct command_context *cmd_ctx; struct debug_msg_receiver *next; }; int target_request(struct target *target, uint32_t request); int delete_debug_msg_receiver(struct command_context *cmd_ctx, struct target *target); int target_request_register_commands(struct command_context *cmd_ctx); /** * Read and clear the flag as to whether we got a message. * * This is used to implement the back-off algorithm on * sleeping in idle mode. */ bool target_got_message(void); #endif /* OPENOCD_TARGET_TARGET_REQUEST_H */
MalteBerlin/TerraMobile
app/src/main/java/br/org/funcate/terramobile/model/geomsource/SFSLayer.java
package br.org.funcate.terramobile.model.geomsource; import org.opengis.feature.simple.SimpleFeature; import org.osmdroid.bonuspack.kml.KmlFeature; import org.osmdroid.bonuspack.kml.KmlFolder; import java.util.List; import br.org.funcate.terramobile.model.gpkg.objects.GpkgLayer; /** * Created by bogo on 15/06/15. */ public class SFSLayer extends KmlFolder { public SFSLayer(List<SimpleFeature> features, GpkgLayer layer) { super(); if (features != null) { for (SimpleFeature sfsFeature : features) { KmlFeature feature = SFSFeature.parseSFS(sfsFeature, layer); add(feature); } } } }
saledouble/JacpFX
JacpFX-TestCases/src/main/java/org/jacp/test/main/ApplicationLauncherMissingComponentViewAnnotation.java
/************************************************************************ * * Copyright (C) 2010 - 2014 * * [ApplicationLauncher.java] * JACPFX Project (https://github.com/JacpFX/JacpFX/) * 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 org.jacp.test.main; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; import org.jacpfx.rcp.workbench.FXWorkbench; import org.jacpfx.spring.launcher.AFXSpringXmlLauncher; import org.jacp.test.workbench.WorkbenchMissingComponentViewAnnotation; import java.net.URL; import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; /** * The application launcher containing the main method * * @author <a href="mailto:<EMAIL>"> <NAME></a> */ public class ApplicationLauncherMissingComponentViewAnnotation extends AFXSpringXmlLauncher { private static final Logger log = Logger.getLogger(ApplicationLauncherMissingComponentViewAnnotation.class .getName()); public static final String[] STYLES = new String[2]; private static final String[] STYLE_FILES = {"/styles/style_light.css", "/styles/style_dark.css"}; /// binary style sheets created while deployment private static final String[] BINARY_FILES = {"/styles/style_light.bss", "/styles/style_dark.bss"}; public static CountDownLatch latch = new CountDownLatch(2); public static volatile ApplicationLauncherMissingComponentViewAnnotation[] instance = new ApplicationLauncherMissingComponentViewAnnotation[1]; public ApplicationLauncherMissingComponentViewAnnotation() { } public ApplicationLauncherMissingComponentViewAnnotation(CountDownLatch latch) { this.latch = latch; } @Override public String getXmlConfig() { return "main.xml"; } /** * @param args */ public static void main(final String[] args) { Application.launch(args); } @Override protected Class<? extends FXWorkbench> getWorkbenchClass() { return WorkbenchMissingComponentViewAnnotation.class; } @Override protected String[] getBasePackages() { return new String[]{"org.jacp.test"}; } /** * only for testing */ public void startComponentScaning() { this.scanPackegesAndInitRegestry(); } @Override public void postInit(final Stage stage) { initStyles(); stage.setMinHeight(580); stage.setMinWidth(800); final Scene scene = stage.getScene(); stage.getIcons().add(new Image("images/icons/JACP_512_512.png")); // add style sheet scene.getStylesheets().add(STYLES[0]); instance[0] = this; ApplicationLauncherMissingComponentViewAnnotation.latch.countDown(); } private static void initStyles() { for (int i = 0; i < 2; i++) { URL res = ApplicationLauncherMissingComponentViewAnnotation.class.getResource(BINARY_FILES[i]); if (res == null) res = ApplicationLauncherMissingComponentViewAnnotation.class.getResource(STYLE_FILES[i]); STYLES[i] = res.toExternalForm(); log.info("found: " + STYLES[i] + " stylesheet"); } } }
liuwake/HalconPractise
HALCON-12.0/include/cpp/HSocket.h
<reponame>liuwake/HalconPractise /***************************************************************************** * HSocket.h ***************************************************************************** * * Project: HALCON/C++ * Description: Class HSocket * * (c) 1996-2014 by MVTec Software GmbH * www.mvtec.com * ***************************************************************************** * * */ #ifndef H_SOCKET_H #define H_SOCKET_H #include "HCPPToolRef.h" namespace Halcon { class LIntExport HSocket: public HToolBase { public: // Tool-specific functional class constructors HSocket(const HTuple &Port, const Halcon::HTuple &GenParamName, const Halcon::HTuple &GenParamValue); HSocket(Hlong Port); HSocket(const HTuple &HostName, const HTuple &Port, const Halcon::HTuple &GenParamName, const Halcon::HTuple &GenParamValue); HSocket(const char *HostName, Hlong Port); // Common tool class management functionality HSocket(); const char *ClassName(void) const; void SetHandle(Hlong ID); // Tool-specific member functions // Receive an image over a socket connection. virtual HImageArray ReceiveImage() const; // Send an image over a socket connection. virtual void SendImage(const HImageArray &Image) const; // Receive regions over a socket connection. virtual HRegionArray ReceiveRegion() const; // Send regions over a socket connection. virtual void SendRegion(const HRegionArray &Region) const; // Receive an XLD object over a socket connection. virtual HXLDArray ReceiveXld() const; // Send an XLD object over a socket connection. virtual void SendXld(const HXLDArray &XLD) const; // Receive a tuple over a socket connection. virtual HTuple ReceiveTuple() const; // Send a tuple over a socket connection. virtual void SendTuple(const Halcon::HTuple &Tuple) const; // Receive arbitrary data from external devices or applications using a // generic socket connection. virtual HTuple ReceiveData(const Halcon::HTuple &Format, Halcon::HTuple *From) const; // Receive arbitrary data from external devices or applications using a // generic socket connection. virtual HTuple ReceiveData(const Halcon::HTuple &Format, char *From) const; // Receive arbitrary data from external devices or applications using a // generic socket connection. virtual HTuple ReceiveData(const char *Format, Halcon::HTuple *From) const; // Receive arbitrary data from external devices or applications using a // generic socket connection. virtual HTuple ReceiveData(const char *Format, char *From) const; // Send arbitrary data to external devices or applications using a // generic socket communication. virtual void SendData(const Halcon::HTuple &Format, const Halcon::HTuple &Data, const Halcon::HTuple &To) const; // Get the value of a socket parameter. virtual HTuple GetSocketParam(const Halcon::HTuple &ParamName) const; // Get the value of a socket parameter. virtual HTuple GetSocketParam(const char *ParamName) const; // Set a socket parameter. virtual void SetSocketParam(const Halcon::HTuple &ParamName, const Halcon::HTuple &ParamValue) const; // Determine the HALCON data type of the next socket data. virtual HTuple GetNextSocketDataType() const; // Get the socket descriptor of a socket used by the operating system. virtual Hlong GetSocketDescriptor() const; // Get the timeout of a socket. virtual double GetSocketTimeout() const; // Set the timeout of a socket. virtual void SetSocketTimeout(const Halcon::HTuple &Timeout) const; // Set the timeout of a socket. virtual void SetSocketTimeout(double Timeout) const; // Close all opened sockets. static void CloseAllSockets(void); // Accept a connection request on a listening socket of the protocol type // 'HALCON' or 'TCP'/'TCP4'/'TCP6'. virtual HSocket SocketAcceptConnect(const Halcon::HTuple &Wait) const; // Accept a connection request on a listening socket of the protocol type // 'HALCON' or 'TCP'/'TCP4'/'TCP6'. virtual HSocket SocketAcceptConnect(const char *Wait) const; // Open a socket and connect it to an accepting socket. virtual void OpenSocketConnect(const Halcon::HTuple &HostName, const Halcon::HTuple &Port, const Halcon::HTuple &GenParamName, const Halcon::HTuple &GenParamValue); // Open a socket that accepts connection requests. virtual void OpenSocketAccept(const Halcon::HTuple &Port, const Halcon::HTuple &GenParamName, const Halcon::HTuple &GenParamValue); // Receive a serialized item over a socket connection. virtual HSerializedItem ReceiveSerializedItem() const; // Send a serialized item over a socket connection. virtual void SendSerializedItem(const Halcon::HSerializedItem &SerializedItemHandle) const; }; } #endif
huangninghao/HexIntegrationTool
base/src/main/java/com/hx/base/mInterface/router/HexRouter.java
package com.hx.base.mInterface.router; import android.app.Activity; import android.content.Context; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.callback.NavigationCallback; import com.alibaba.android.arouter.launcher.ARouter; import com.hx.base.mInterface.config.HexBundle; /** * description: * update by: * update day: */ public class HexRouter { private Postcard postcard; private HexRouter(Postcard postcard) { this.postcard = postcard; } public static HexRouter newInstance(String path) { return new HexRouter(ARouter.getInstance().build(path)); } private boolean checkPostcard() { if (postcard == null) throw new IllegalArgumentException("HexRouter 的 postcard 为null"); return true; } public HexRouter withBundle(HexBundle bundle) { if (bundle == null) return this; checkPostcard(); postcard.with(bundle.build()); return this; } public HexRouter addFlag(int flag) { checkPostcard(); postcard.withFlags(flag); return this; } public Object navigation() { return navigation(null); } public Object navigation(Context context) { return navigation(context, null); } public void navigation(Activity activity, int requestCode) { navigation(activity, requestCode, null); } public Object navigation(Context context, NavigationCallback callback) { checkPostcard(); return postcard.navigation(context, callback); } public void navigation(Activity activity, int requestCode, NavigationCallback callback) { postcard.navigation(activity, requestCode, callback); } }
bakuzan/mylist
public/modules/orders/services/orders-query.service.js
(function() { 'use strict'; angular.module('orders').factory('Orders', OrdersFactory); OrdersFactory.$inject = ['$resource']; function OrdersFactory($resource) { return $resource('orders/:orderId', { orderId: '@_id' }, { update: { method: 'PUT' } }); } })();
TampereTC/tre-smartcity-keystone
keystone/common/manager.py
<filename>keystone/common/manager.py # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools from oslo.utils import importutils def response_truncated(f): """Truncate the list returned by the wrapped function. This is designed to wrap Manager list_{entity} methods to ensure that any list limits that are defined are passed to the driver layer. If a hints list is provided, the wrapper will insert the relevant limit into the hints so that the underlying driver call can try and honor it. If the driver does truncate the response, it will update the 'truncated' attribute in the 'limit' entry in the hints list, which enables the caller of this function to know if truncation has taken place. If, however, the driver layer is unable to perform truncation, the 'limit' entry is simply left in the hints list for the caller to handle. A _get_list_limit() method is required to be present in the object class hierarchy, which returns the limit for this backend to which we will truncate. If a hints list is not provided in the arguments of the wrapped call then any limits set in the config file are ignored. This allows internal use of such wrapped methods where the entire data set is needed as input for the calculations of some other API (e.g. get role assignments for a given project). """ @functools.wraps(f) def wrapper(self, *args, **kwargs): if kwargs.get('hints') is None: return f(self, *args, **kwargs) list_limit = self.driver._get_list_limit() if list_limit: kwargs['hints'].set_limit(list_limit) return f(self, *args, **kwargs) return wrapper class Manager(object): """Base class for intermediary request layer. The Manager layer exists to support additional logic that applies to all or some of the methods exposed by a service that are not specific to the HTTP interface. It also provides a stable entry point to dynamic backends. An example of a probable use case is logging all the calls. """ def __init__(self, driver_name): self.driver = importutils.import_object(driver_name) def __getattr__(self, name): """Forward calls to the underlying driver.""" f = getattr(self.driver, name) setattr(self, name, f) return f
jenfly/atmos
testing/testing-variables-streamfunction.py
import numpy as np import matplotlib.pyplot as plt import xray import atmos as atm # ---------------------------------------------------------------------- # Monthly climatology yearstr = '1979-2015' varnms = ['U', 'V'] datadir = atm.homedir() + 'datastore/merra/monthly/' filestr = datadir + 'merra_%s_%s.nc' files = {nm : filestr % (nm, yearstr) for nm in varnms} data = xray.Dataset() for nm in varnms: with xray.open_dataset(files[nm]) as ds: data[nm] = ds[nm].load() lat = atm.get_coord(data, 'lat') lon = atm.get_coord(data, 'lon') psfile = atm.homedir() + 'dynamics/python/atmos-tools/data/topo/ncep2_ps.nc' ps = atm.get_ps_clim(lat, lon, psfile) ps = ps / 100 figsize = (7, 9) omitzero = False for ssn in ['ANN', 'DJF', 'JJA', 'MAR']: for lonlims in [(0, 360), (60, 100)]: lon1, lon2 = lonlims lonstr = atm.latlon_str(lon1, lon2, 'lon') suptitle = ssn + ' ' + lonstr months = atm.season_months(ssn) v = data['V'].sel(month=months) if (lon2 - lon1) < 360: v = atm.subset(v, {'lon' : (lon1, lon2)}) sector_scale = (lon2 - lon1) / 360.0 psbar = atm.dim_mean(ps, 'lon', lon1, lon2) clev = 10 else: sector_scale = None psbar = atm.dim_mean(ps, 'lon') clev = 20 vssn = v.mean(dim='month') vssn_bar = atm.dim_mean(vssn, 'lon') psi1 = atm.streamfunction(vssn, sector_scale=sector_scale) psi1 = atm.dim_mean(psi1, 'lon') psi2 = atm.streamfunction(vssn_bar, sector_scale=sector_scale) plt.figure(figsize=figsize) plt.suptitle(suptitle) plt.subplot(2, 1, 1) atm.contour_latpres(psi1, clev=clev, omitzero=omitzero, topo=psbar) plt.title('v -> $\psi$ -> [$\psi$]') plt.xlabel('') plt.subplot(2, 1, 2) atm.contour_latpres(psi2, clev=clev, omitzero=omitzero, topo=psbar) plt.title('[v] -> [$\psi$]') # ---------------------------------------------------------------------- # Daily data datadir = atm.homedir() + 'datastore/merra/daily/' filestr = datadir + 'merra_V_sector_%s_%d.nc' year = 1980 #lon1, lon2 = 0, 360 lon1, lon2 = 60, 100 lonstr = atm.latlon_str(lon1, lon2, 'lon') filenm = filestr % (lonstr, year) with xray.open_dataset(filenm) as ds: v = ds['V'].load() if (lon2 - lon1) < 360: sector_scale = (lon2 - lon1) / 360. else: sector_scale = None clev = 10 #clev = 20 #ssn = 'ANN' #days = atm.season_days(ssn) days = range(170, 176) vbar = v.sel(day=days).mean(dim='day') psi = atm.streamfunction(vbar, sector_scale=sector_scale) plt.figure() atm.contour_latpres(psi, clev=clev, omitzero=False) # ====================================================================== # # # ---------------------------------------------------------------------- # # Read data # url = ('http://goldsmr3.sci.gsfc.nasa.gov/opendap/MERRA_MONTHLY/' # 'MAIMCPASM.5.2.0/1979/MERRA100.prod.assim.instM_3d_asm_Cp.197907.hdf') # # ds = xray.open_dataset(url) # #T = ds['T'] # #ps = ds['PS'] # #u = ds['U'] # v = ds['V'] # #q = ds['QV'] # lat = get_coord(v, 'lat') # lon = get_coord(v, 'lon') # plev = get_coord(v, 'plev') # # topo = dat.get_ps_clim(lat, lon) / 100 # topo.units = 'hPa' # # # ---------------------------------------------------------------------- # # Streamfunction - top-down, zonal mean # # # DataArray # psi = streamfunction(v) # psibar = psi.mean(axis=-1) # # # ndarray # psi2 = streamfunction(v.values, lat, plev * 100) # psibar2 = np.nanmean(psi2, axis=-1) # # topobar = topo.mean(axis=-1) # # cint = 50 # plt.figure(figsize=(7,8)) # plt.subplot(211) # ap.contour_latpres(psibar, clev=cint, topo=topobar) # plt.subplot(212) # ap.contour_latpres(psibar2, lat, plev, clev=cint, topo=topobar) # # # ---------------------------------------------------------------------- # # Sector mean, top-down # # lon1, lon2 = 60, 100 # cint=10 # # vbar = dat.subset(v, 'lon', lon1, lon2).mean(axis=-1) # # psibar = dat.subset(psi, 'lon', lon1, lon2).mean(axis=-1) # psibar = psibar * (lon2-lon1)/360 # # psibar2 = streamfunction(vbar) # psibar2 = psibar2 * (lon2-lon1)/360 # # topobar = dat.subset(topo, 'lon', lon1, lon2).mean(axis=-1) # # plt.figure(figsize=(7,8)) # plt.subplot(211) # ap.contour_latpres(psibar, clev=cint, topo=topobar) # plt.subplot(212) # ap.contour_latpres(psibar2, clev=cint, topo=topobar) # # # Note: streamfunction() doesn't work properly when you take the # # zonal/sector mean of v before computing the streamfunction. # # # ---------------------------------------------------------------------- # # Top-down and bottom-up # # psibar = psi.mean(axis=-1) # psi2 = streamfunction(v, topdown=False) # psibar2 = psi2.mean(axis=-1) # # topobar = topo.mean(axis=-1) # # cint = 50 # plt.figure(figsize=(7,8)) # plt.subplot(211) # ap.contour_latpres(psibar, clev=cint, topo=topobar) # plt.subplot(212) # ap.contour_latpres(psibar2, lat, plev, clev=cint, topo=topobar)
ielomariala/Hex-Game
gsl-2.6/doc/examples/fitreg.c
<filename>gsl-2.6/doc/examples/fitreg.c #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_multifit.h> int main() { const size_t n = 1000; /* number of observations */ const size_t p = 2; /* number of model parameters */ size_t i; gsl_rng *r = gsl_rng_alloc(gsl_rng_default); gsl_matrix *X = gsl_matrix_alloc(n, p); gsl_vector *y = gsl_vector_alloc(n); for (i = 0; i < n; ++i) { /* generate first random variable u */ double ui = 5.0 * gsl_ran_gaussian(r, 1.0); /* set v = u + noise */ double vi = ui + gsl_ran_gaussian(r, 0.001); /* set y = u + v + noise */ double yi = ui + vi + gsl_ran_gaussian(r, 1.0); /* since u =~ v, the matrix X is ill-conditioned */ gsl_matrix_set(X, i, 0, ui); gsl_matrix_set(X, i, 1, vi); /* rhs vector */ gsl_vector_set(y, i, yi); } { const size_t npoints = 200; /* number of points on L-curve and GCV curve */ gsl_multifit_linear_workspace *w = gsl_multifit_linear_alloc(n, p); gsl_vector *c = gsl_vector_alloc(p); /* OLS solution */ gsl_vector *c_lcurve = gsl_vector_alloc(p); /* regularized solution (L-curve) */ gsl_vector *c_gcv = gsl_vector_alloc(p); /* regularized solution (GCV) */ gsl_vector *reg_param = gsl_vector_alloc(npoints); gsl_vector *rho = gsl_vector_alloc(npoints); /* residual norms */ gsl_vector *eta = gsl_vector_alloc(npoints); /* solution norms */ gsl_vector *G = gsl_vector_alloc(npoints); /* GCV function values */ double lambda_l; /* optimal regularization parameter (L-curve) */ double lambda_gcv; /* optimal regularization parameter (GCV) */ double G_gcv; /* G(lambda_gcv) */ size_t reg_idx; /* index of optimal lambda */ double rcond; /* reciprocal condition number of X */ double chisq, rnorm, snorm; /* compute SVD of X */ gsl_multifit_linear_svd(X, w); rcond = gsl_multifit_linear_rcond(w); fprintf(stderr, "matrix condition number = %e\n\n", 1.0 / rcond); /* unregularized (standard) least squares fit, lambda = 0 */ gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0); fprintf(stderr, "=== Unregularized fit ===\n"); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c, 0), gsl_vector_get(c, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* calculate L-curve and find its corner */ gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w); gsl_multifit_linear_lcorner(rho, eta, &reg_idx); /* store optimal regularization parameter */ lambda_l = gsl_vector_get(reg_param, reg_idx); /* regularize with lambda_l */ gsl_multifit_linear_solve(lambda_l, X, y, c_lcurve, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0) + pow(lambda_l * snorm, 2.0); fprintf(stderr, "\n=== Regularized fit (L-curve) ===\n"); fprintf(stderr, "optimal lambda: %g\n", lambda_l); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c_lcurve, 0), gsl_vector_get(c_lcurve, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* calculate GCV curve and find its minimum */ gsl_multifit_linear_gcv(y, reg_param, G, &lambda_gcv, &G_gcv, w); /* regularize with lambda_gcv */ gsl_multifit_linear_solve(lambda_gcv, X, y, c_gcv, &rnorm, &snorm, w); chisq = pow(rnorm, 2.0) + pow(lambda_gcv * snorm, 2.0); fprintf(stderr, "\n=== Regularized fit (GCV) ===\n"); fprintf(stderr, "optimal lambda: %g\n", lambda_gcv); fprintf(stderr, "best fit: y = %g u + %g v\n", gsl_vector_get(c_gcv, 0), gsl_vector_get(c_gcv, 1)); fprintf(stderr, "residual norm = %g\n", rnorm); fprintf(stderr, "solution norm = %g\n", snorm); fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p)); /* output L-curve and GCV curve */ for (i = 0; i < npoints; ++i) { printf("%e %e %e %e\n", gsl_vector_get(reg_param, i), gsl_vector_get(rho, i), gsl_vector_get(eta, i), gsl_vector_get(G, i)); } /* output L-curve corner point */ printf("\n\n%f %f\n", gsl_vector_get(rho, reg_idx), gsl_vector_get(eta, reg_idx)); /* output GCV curve corner minimum */ printf("\n\n%e %e\n", lambda_gcv, G_gcv); gsl_multifit_linear_free(w); gsl_vector_free(c); gsl_vector_free(c_lcurve); gsl_vector_free(reg_param); gsl_vector_free(rho); gsl_vector_free(eta); gsl_vector_free(G); } gsl_rng_free(r); gsl_matrix_free(X); gsl_vector_free(y); return 0; }
stas-vilchik/bdd-ml
data/5450.js
<reponame>stas-vilchik/bdd-ml<gh_stars>0 { throw new Error("Cannot set read-only property."); }
HeRaNO/OI-ICPC-Codes
NOI[OpenJudge]/2.6/2.6.1481.cpp
//Code By HeRaNO #include <cstdio> #include <cstring> #define MAXN 50010 using namespace std; int a[MAXN]; int lmax[MAXN], rmax[MAXN]; int left[MAXN], right[MAXN]; int ans; int n, t; int mymax(int a, int b) { return a > b ? a : b; } int main() { scanf("%d", &t); while (t--) { memset(lmax, 0, sizeof(lmax)); memset(rmax, 0, sizeof(rmax)); scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); lmax[1] = a[1]; for (int i = 2; i <= n; i++) if (lmax[i - 1] <= 0) lmax[i] = a[i]; else lmax[i] = lmax[i - 1] + a[i]; for (int i = 2; i <= n; i++) lmax[i] = mymax(lmax[i - 1], lmax[i]); rmax[n] = a[n]; for (int i = n - 1; i; i--) if (rmax[i + 1] <= 0) rmax[i] = a[i]; else rmax[i] = rmax[i + 1] + a[i]; for (int i = n - 1; i; i--) rmax[i] = mymax(rmax[i + 1], rmax[i]); ans = a[1] + a[n]; for (int i = 1; i < n; i++) ans = mymax(ans, lmax[i] + rmax[i + 1]); printf("%d\n", ans); } return 0; }
stori-es/stories
dashboard/src/main/java/org/consumersunion/stories/server/api/rest/converters/UserPostConverter.java
package org.consumersunion.stories.server.api.rest.converters; import org.consumersunion.stories.common.shared.dto.post.UserPost; import org.consumersunion.stories.common.shared.model.User; import org.springframework.stereotype.Component; @Component public class UserPostConverter extends AbstractConverter<UserPost, User> { @Override public User convert(UserPost userPost) { User user = new User(); user.setHandle(userPost.getHandle()); user.setDefaultProfile(userPost.getDefaultProfileId()); return user; } }
jhermsmeier/osrm-backend
unit_tests/library/waypoint_check.hpp
#ifndef OSRM_UNIT_TEST_WAYPOINT_CHECK #define OSRM_UNIT_TEST_WAYPOINT_CHECK #include "osrm/coordinate.hpp" #include "osrm/json_container.hpp" #include "util/exception.hpp" using namespace osrm; inline bool waypoint_check(json::Value waypoint) { if (!waypoint.is<mapbox::util::recursive_wrapper<util::json::Object>>()) { throw util::exception("Must pass in a waypoint object"); } const auto waypoint_object = waypoint.get<json::Object>(); const auto waypoint_location = waypoint_object.values.at("location").get<json::Array>().values; util::FloatLongitude lon{waypoint_location[0].get<json::Number>().value}; util::FloatLatitude lat{waypoint_location[1].get<json::Number>().value}; util::Coordinate location_coordinate(lon, lat); return location_coordinate.IsValid(); } #endif
benjinx/Toon
Engine/Public/Toon/Camera.hpp
#ifndef TOON_CAMERA_H #define TOON_CAMERA_H #include <Toon/Config.hpp> #include <Toon/Entity.hpp> #include <Toon/Math.hpp> #include <Toon/String.hpp> namespace Toon { enum CameraMode { Perspective, Orthographic, }; // enum CameraMode class TOON_ENGINE_API Camera : public Entity { public: DISALLOW_COPY_AND_ASSIGN(Camera) Camera(); virtual ~Camera(); glm::mat4 GetView() const; glm::mat4 GetProjection() const; void SetMode(CameraMode mode); inline CameraMode GetMode() const { return _mode; } void SetClip(const glm::vec2& clip); inline glm::vec2 GetClip() const { return _clip; } void SetUp(const glm::vec3& up); inline glm::vec3 GetUp() const { return _up; } void SetForward(const glm::vec3& forward); glm::vec3 GetForward() const; glm::vec3 GetRight() const; void SetAspect (float aspect); void SetAspect(const glm::vec2& size); inline float GetAspect() const { return _aspect; } // Perspective void SetFOVX(float fovx); inline float GetFOVX() const { return _fovX; } void SetFOVY(float fovy); void SetLookAt(const glm::vec3& point); // Orthographic void SetViewportSize(const glm::vec2& viewSize); inline glm::vec2 GetViewportSize() const { return _viewportSize; } void SetViewportScale(const glm::vec4& viewScale); inline glm::vec4 GetViewportScale() const { return _viewportScale; } glm::vec4 GetViewport() const; // Movement void HandleMovement(float dt); void HandleRotation(float xoffset, float yoffset); void SetDirection(glm::vec3 dir); glm::vec3& GetDirection() { return _direction; } private: CameraMode _mode = CameraMode::Perspective; glm::vec2 _clip = { 0.1f, 10000.0f }; glm::vec3 _up = GetWorldUp(); float _aspect = 16.0f / 9.0f; // 16:9 unsigned _windowResizedEventHandlerID; // Perspective float _fovX = glm::radians(45.0f); // Orthographic glm::vec2 _viewportSize = glm::vec2(1920.0f, 1080.0f); glm::vec4 _viewportScale = glm::vec4(-0.5f, 0.5f, 0.5f, -0.5f); // Movement float _movementSpeed = 0.25f; float _rotateSpeed = 0.001f; bool _invserse = false; glm::vec3 _direction = glm::vec3(0); }; } // namespace Toon #endif // TOON_CAMERA_H
xzhan96/chromium.src
chrome/browser/extensions/api/developer_private/developer_private_api.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/developer_private/developer_private_api.h" #include <stddef.h> #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/extensions/api/developer_private/developer_private_mangle.h" #include "chrome/browser/extensions/api/developer_private/entry_picker.h" #include "chrome/browser/extensions/api/developer_private/extension_info_generator.h" #include "chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h" #include "chrome/browser/extensions/devtools_util.h" #include "chrome/browser/extensions/extension_commands_global_registry.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/extension_ui_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/install_verifier.h" #include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/extensions/shared_module_service.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/extensions/updater/extension_updater.h" #include "chrome/browser/extensions/webstore_reinstaller.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/apps/app_info_dialog.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/extensions/app_launch_params.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/extensions/api/developer_private.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/error_map.h" #include "extensions/browser/extension_error.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/file_highlighter.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/notification_types.h" #include "extensions/browser/warning_service.h" #include "extensions/common/constants.h" #include "extensions/common/extension_set.h" #include "extensions/common/feature_switch.h" #include "extensions/common/install_warning.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handlers/options_page_info.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/grit/extensions_browser_resources.h" #include "storage/browser/fileapi/external_mount_points.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation.h" #include "storage/browser/fileapi/file_system_operation_runner.h" #include "storage/browser/fileapi/isolated_context.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace developer = api::developer_private; namespace { const char kNoSuchExtensionError[] = "No such extension."; const char kCannotModifyPolicyExtensionError[] = "Cannot modify the extension by policy."; const char kRequiresUserGestureError[] = "This action requires a user gesture."; const char kCouldNotShowSelectFileDialogError[] = "Could not show a file chooser."; const char kFileSelectionCanceled[] = "File selection was canceled."; const char kNoSuchRendererError[] = "No such renderer."; const char kInvalidPathError[] = "Invalid path."; const char kManifestKeyIsRequiredError[] = "The 'manifestKey' argument is required for manifest files."; const char kCouldNotFindWebContentsError[] = "Could not find a valid web contents."; const char kCannotUpdateSupervisedProfileSettingsError[] = "Cannot change settings for a supervised profile."; const char kNoOptionsPageForExtensionError[] = "Extension does not have an options page."; const char kUnpackedAppsFolder[] = "apps_target"; const char kManifestFile[] = "manifest.json"; ExtensionService* GetExtensionService(content::BrowserContext* context) { return ExtensionSystem::Get(context)->extension_service(); } std::string ReadFileToString(const base::FilePath& path) { std::string data; ignore_result(base::ReadFileToString(path, &data)); return data; } bool UserCanModifyExtensionConfiguration( const Extension* extension, content::BrowserContext* browser_context, std::string* error) { ManagementPolicy* management_policy = ExtensionSystem::Get(browser_context)->management_policy(); if (!management_policy->UserMayModifySettings(extension, nullptr)) { LOG(ERROR) << "Attempt to change settings of an extension that is " << "non-usermanagable was made. Extension id : " << extension->id(); *error = kCannotModifyPolicyExtensionError; return false; } return true; } // Runs the install verifier for all extensions that are enabled, disabled, or // terminated. void PerformVerificationCheck(content::BrowserContext* context) { std::unique_ptr<ExtensionSet> extensions = ExtensionRegistry::Get(context)->GenerateInstalledExtensionsSet( ExtensionRegistry::ENABLED | ExtensionRegistry::DISABLED | ExtensionRegistry::TERMINATED); ExtensionPrefs* prefs = ExtensionPrefs::Get(context); bool should_do_verification_check = false; for (const scoped_refptr<const Extension>& extension : *extensions) { if (ui_util::ShouldDisplayInExtensionSettings(extension.get(), context) && ((prefs->GetDisableReasons(extension->id()) & Extension::DISABLE_NOT_VERIFIED) != 0)) { should_do_verification_check = true; break; } } UMA_HISTOGRAM_BOOLEAN("ExtensionSettings.ShouldDoVerificationCheck", should_do_verification_check); if (should_do_verification_check) InstallVerifier::Get(context)->VerifyAllExtensions(); } std::unique_ptr<developer::ProfileInfo> CreateProfileInfo(Profile* profile) { std::unique_ptr<developer::ProfileInfo> info(new developer::ProfileInfo()); info->is_supervised = profile->IsSupervised(); PrefService* prefs = profile->GetPrefs(); info->is_incognito_available = IncognitoModePrefs::GetAvailability(prefs) != IncognitoModePrefs::DISABLED; info->in_developer_mode = !info->is_supervised && prefs->GetBoolean(prefs::kExtensionsUIDeveloperMode); info->app_info_dialog_enabled = CanShowAppInfoDialog(); info->can_load_unpacked = !ExtensionManagementFactory::GetForBrowserContext(profile) ->BlacklistedByDefault(); return info; } } // namespace namespace ChoosePath = api::developer_private::ChoosePath; namespace GetItemsInfo = api::developer_private::GetItemsInfo; namespace PackDirectory = api::developer_private::PackDirectory; namespace Reload = api::developer_private::Reload; static base::LazyInstance<BrowserContextKeyedAPIFactory<DeveloperPrivateAPI> > g_factory = LAZY_INSTANCE_INITIALIZER; // static BrowserContextKeyedAPIFactory<DeveloperPrivateAPI>* DeveloperPrivateAPI::GetFactoryInstance() { return g_factory.Pointer(); } // static DeveloperPrivateAPI* DeveloperPrivateAPI::Get( content::BrowserContext* context) { return GetFactoryInstance()->Get(context); } DeveloperPrivateAPI::DeveloperPrivateAPI(content::BrowserContext* context) : profile_(Profile::FromBrowserContext(context)) { RegisterNotifications(); } DeveloperPrivateEventRouter::DeveloperPrivateEventRouter(Profile* profile) : extension_registry_observer_(this), error_console_observer_(this), process_manager_observer_(this), app_window_registry_observer_(this), extension_action_api_observer_(this), warning_service_observer_(this), extension_prefs_observer_(this), extension_management_observer_(this), command_service_observer_(this), profile_(profile), event_router_(EventRouter::Get(profile_)), weak_factory_(this) { extension_registry_observer_.Add(ExtensionRegistry::Get(profile_)); error_console_observer_.Add(ErrorConsole::Get(profile)); process_manager_observer_.Add(ProcessManager::Get(profile)); app_window_registry_observer_.Add(AppWindowRegistry::Get(profile)); extension_action_api_observer_.Add(ExtensionActionAPI::Get(profile)); warning_service_observer_.Add(WarningService::Get(profile)); extension_prefs_observer_.Add(ExtensionPrefs::Get(profile)); extension_management_observer_.Add( ExtensionManagementFactory::GetForBrowserContext(profile)); command_service_observer_.Add(CommandService::Get(profile)); pref_change_registrar_.Init(profile->GetPrefs()); // The unretained is safe, since the PrefChangeRegistrar unregisters the // callback on destruction. pref_change_registrar_.Add( prefs::kExtensionsUIDeveloperMode, base::Bind(&DeveloperPrivateEventRouter::OnProfilePrefChanged, base::Unretained(this))); } DeveloperPrivateEventRouter::~DeveloperPrivateEventRouter() { } void DeveloperPrivateEventRouter::AddExtensionId( const std::string& extension_id) { extension_ids_.insert(extension_id); } void DeveloperPrivateEventRouter::RemoveExtensionId( const std::string& extension_id) { extension_ids_.erase(extension_id); } void DeveloperPrivateEventRouter::OnExtensionLoaded( content::BrowserContext* browser_context, const Extension* extension) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged(developer::EVENT_TYPE_LOADED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged(developer::EVENT_TYPE_UNLOADED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionInstalled( content::BrowserContext* browser_context, const Extension* extension, bool is_update) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged(developer::EVENT_TYPE_INSTALLED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionUninstalled( content::BrowserContext* browser_context, const Extension* extension, extensions::UninstallReason reason) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged(developer::EVENT_TYPE_UNINSTALLED, extension->id()); } void DeveloperPrivateEventRouter::OnErrorAdded(const ExtensionError* error) { // We don't want to handle errors thrown by extensions subscribed to these // events (currently only the Apps Developer Tool), because doing so risks // entering a loop. if (extension_ids_.count(error->extension_id())) return; BroadcastItemStateChanged(developer::EVENT_TYPE_ERROR_ADDED, error->extension_id()); } void DeveloperPrivateEventRouter::OnErrorsRemoved( const std::set<std::string>& removed_ids) { for (const std::string& id : removed_ids) { if (!extension_ids_.count(id)) BroadcastItemStateChanged(developer::EVENT_TYPE_ERRORS_REMOVED, id); } } void DeveloperPrivateEventRouter::OnExtensionFrameRegistered( const std::string& extension_id, content::RenderFrameHost* render_frame_host) { BroadcastItemStateChanged(developer::EVENT_TYPE_VIEW_REGISTERED, extension_id); } void DeveloperPrivateEventRouter::OnExtensionFrameUnregistered( const std::string& extension_id, content::RenderFrameHost* render_frame_host) { BroadcastItemStateChanged(developer::EVENT_TYPE_VIEW_UNREGISTERED, extension_id); } void DeveloperPrivateEventRouter::OnAppWindowAdded(AppWindow* window) { BroadcastItemStateChanged(developer::EVENT_TYPE_VIEW_REGISTERED, window->extension_id()); } void DeveloperPrivateEventRouter::OnAppWindowRemoved(AppWindow* window) { BroadcastItemStateChanged(developer::EVENT_TYPE_VIEW_UNREGISTERED, window->extension_id()); } void DeveloperPrivateEventRouter::OnExtensionCommandAdded( const std::string& extension_id, const Command& added_command) { BroadcastItemStateChanged(developer::EVENT_TYPE_PREFS_CHANGED, extension_id); } void DeveloperPrivateEventRouter::OnExtensionCommandRemoved( const std::string& extension_id, const Command& removed_command) { BroadcastItemStateChanged(developer::EVENT_TYPE_PREFS_CHANGED, extension_id); } void DeveloperPrivateEventRouter::OnExtensionActionVisibilityChanged( const std::string& extension_id, bool is_now_visible) { BroadcastItemStateChanged(developer::EVENT_TYPE_PREFS_CHANGED, extension_id); } void DeveloperPrivateEventRouter::OnExtensionDisableReasonsChanged( const std::string& extension_id, int disable_reasons) { BroadcastItemStateChanged(developer::EVENT_TYPE_PREFS_CHANGED, extension_id); } void DeveloperPrivateEventRouter::OnExtensionManagementSettingsChanged() { std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Append(CreateProfileInfo(profile_)->ToValue()); std::unique_ptr<Event> event( new Event(events::DEVELOPER_PRIVATE_ON_PROFILE_STATE_CHANGED, developer::OnProfileStateChanged::kEventName, std::move(args))); event_router_->BroadcastEvent(std::move(event)); } void DeveloperPrivateEventRouter::ExtensionWarningsChanged( const ExtensionIdSet& affected_extensions) { for (const ExtensionId& id : affected_extensions) BroadcastItemStateChanged(developer::EVENT_TYPE_WARNINGS_CHANGED, id); } void DeveloperPrivateEventRouter::OnProfilePrefChanged() { std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Append(CreateProfileInfo(profile_)->ToValue()); std::unique_ptr<Event> event( new Event(events::DEVELOPER_PRIVATE_ON_PROFILE_STATE_CHANGED, developer::OnProfileStateChanged::kEventName, std::move(args))); event_router_->BroadcastEvent(std::move(event)); } void DeveloperPrivateEventRouter::BroadcastItemStateChanged( developer::EventType event_type, const std::string& extension_id) { std::unique_ptr<ExtensionInfoGenerator> info_generator( new ExtensionInfoGenerator(profile_)); ExtensionInfoGenerator* info_generator_weak = info_generator.get(); info_generator_weak->CreateExtensionInfo( extension_id, base::Bind(&DeveloperPrivateEventRouter::BroadcastItemStateChangedHelper, weak_factory_.GetWeakPtr(), event_type, extension_id, base::Passed(std::move(info_generator)))); } void DeveloperPrivateEventRouter::BroadcastItemStateChangedHelper( developer::EventType event_type, const std::string& extension_id, std::unique_ptr<ExtensionInfoGenerator> info_generator, ExtensionInfoGenerator::ExtensionInfoList infos) { DCHECK_LE(infos.size(), 1u); developer::EventData event_data; event_data.event_type = event_type; event_data.item_id = extension_id; if (!infos.empty()) { event_data.extension_info.reset( new developer::ExtensionInfo(std::move(infos[0]))); } std::unique_ptr<base::ListValue> args(new base::ListValue()); args->Append(event_data.ToValue()); std::unique_ptr<Event> event( new Event(events::DEVELOPER_PRIVATE_ON_ITEM_STATE_CHANGED, developer::OnItemStateChanged::kEventName, std::move(args))); event_router_->BroadcastEvent(std::move(event)); } void DeveloperPrivateAPI::SetLastUnpackedDirectory(const base::FilePath& path) { last_unpacked_directory_ = path; } void DeveloperPrivateAPI::RegisterNotifications() { EventRouter::Get(profile_)->RegisterObserver( this, developer::OnItemStateChanged::kEventName); } DeveloperPrivateAPI::~DeveloperPrivateAPI() {} void DeveloperPrivateAPI::Shutdown() {} void DeveloperPrivateAPI::OnListenerAdded( const EventListenerInfo& details) { if (!developer_private_event_router_) { developer_private_event_router_.reset( new DeveloperPrivateEventRouter(profile_)); } developer_private_event_router_->AddExtensionId(details.extension_id); } void DeveloperPrivateAPI::OnListenerRemoved( const EventListenerInfo& details) { if (!EventRouter::Get(profile_)->HasEventListener( developer::OnItemStateChanged::kEventName)) { developer_private_event_router_.reset(NULL); } else { developer_private_event_router_->RemoveExtensionId(details.extension_id); } } namespace api { DeveloperPrivateAPIFunction::~DeveloperPrivateAPIFunction() { } const Extension* DeveloperPrivateAPIFunction::GetExtensionById( const std::string& id) { return ExtensionRegistry::Get(browser_context())->GetExtensionById( id, ExtensionRegistry::EVERYTHING); } const Extension* DeveloperPrivateAPIFunction::GetEnabledExtensionById( const std::string& id) { return ExtensionRegistry::Get(browser_context())->enabled_extensions(). GetByID(id); } DeveloperPrivateAutoUpdateFunction::~DeveloperPrivateAutoUpdateFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateAutoUpdateFunction::Run() { ExtensionUpdater* updater = ExtensionSystem::Get(browser_context())->extension_service()->updater(); if (updater) { ExtensionUpdater::CheckParams params; params.install_immediately = true; updater->CheckNow(params); } return RespondNow(NoArguments()); } DeveloperPrivateGetExtensionsInfoFunction:: DeveloperPrivateGetExtensionsInfoFunction() { } DeveloperPrivateGetExtensionsInfoFunction:: ~DeveloperPrivateGetExtensionsInfoFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionsInfoFunction::Run() { std::unique_ptr<developer::GetExtensionsInfo::Params> params( developer::GetExtensionsInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); bool include_disabled = true; bool include_terminated = true; if (params->options) { if (params->options->include_disabled) include_disabled = *params->options->include_disabled; if (params->options->include_terminated) include_terminated = *params->options->include_terminated; } info_generator_.reset(new ExtensionInfoGenerator(browser_context())); info_generator_->CreateExtensionsInfo( include_disabled, include_terminated, base::Bind(&DeveloperPrivateGetExtensionsInfoFunction::OnInfosGenerated, this /* refcounted */)); return RespondLater(); } void DeveloperPrivateGetExtensionsInfoFunction::OnInfosGenerated( ExtensionInfoGenerator::ExtensionInfoList list) { Respond(ArgumentList(developer::GetExtensionsInfo::Results::Create(list))); } DeveloperPrivateGetExtensionInfoFunction:: DeveloperPrivateGetExtensionInfoFunction() { } DeveloperPrivateGetExtensionInfoFunction:: ~DeveloperPrivateGetExtensionInfoFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionInfoFunction::Run() { std::unique_ptr<developer::GetExtensionInfo::Params> params( developer::GetExtensionInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); info_generator_.reset(new ExtensionInfoGenerator(browser_context())); info_generator_->CreateExtensionInfo( params->id, base::Bind(&DeveloperPrivateGetExtensionInfoFunction::OnInfosGenerated, this /* refcounted */)); return RespondLater(); } void DeveloperPrivateGetExtensionInfoFunction::OnInfosGenerated( ExtensionInfoGenerator::ExtensionInfoList list) { DCHECK_LE(1u, list.size()); Respond(list.empty() ? Error(kNoSuchExtensionError) : OneArgument(list[0].ToValue())); } DeveloperPrivateGetItemsInfoFunction::DeveloperPrivateGetItemsInfoFunction() {} DeveloperPrivateGetItemsInfoFunction::~DeveloperPrivateGetItemsInfoFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateGetItemsInfoFunction::Run() { std::unique_ptr<developer::GetItemsInfo::Params> params( developer::GetItemsInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); info_generator_.reset(new ExtensionInfoGenerator(browser_context())); info_generator_->CreateExtensionsInfo( params->include_disabled, params->include_terminated, base::Bind(&DeveloperPrivateGetItemsInfoFunction::OnInfosGenerated, this /* refcounted */)); return RespondLater(); } void DeveloperPrivateGetItemsInfoFunction::OnInfosGenerated( ExtensionInfoGenerator::ExtensionInfoList list) { std::vector<developer::ItemInfo> item_list; for (const developer::ExtensionInfo& info : list) item_list.push_back(developer_private_mangle::MangleExtensionInfo(info)); Respond(ArgumentList(developer::GetItemsInfo::Results::Create(item_list))); } DeveloperPrivateGetProfileConfigurationFunction:: ~DeveloperPrivateGetProfileConfigurationFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateGetProfileConfigurationFunction::Run() { std::unique_ptr<developer::ProfileInfo> info = CreateProfileInfo(GetProfile()); // If this is called from the chrome://extensions page, we use this as a // heuristic that it's a good time to verify installs. We do this on startup, // but there's a chance that it failed erroneously, so it's good to double- // check. if (source_context_type() == Feature::WEBUI_CONTEXT) PerformVerificationCheck(browser_context()); return RespondNow(OneArgument(info->ToValue())); } DeveloperPrivateUpdateProfileConfigurationFunction:: ~DeveloperPrivateUpdateProfileConfigurationFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateUpdateProfileConfigurationFunction::Run() { std::unique_ptr<developer::UpdateProfileConfiguration::Params> params( developer::UpdateProfileConfiguration::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::ProfileConfigurationUpdate& update = params->update; PrefService* prefs = GetProfile()->GetPrefs(); if (update.in_developer_mode) { if (GetProfile()->IsSupervised()) return RespondNow(Error(kCannotUpdateSupervisedProfileSettingsError)); prefs->SetBoolean(prefs::kExtensionsUIDeveloperMode, *update.in_developer_mode); } return RespondNow(NoArguments()); } DeveloperPrivateUpdateExtensionConfigurationFunction:: ~DeveloperPrivateUpdateExtensionConfigurationFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateUpdateExtensionConfigurationFunction::Run() { std::unique_ptr<developer::UpdateExtensionConfiguration::Params> params( developer::UpdateExtensionConfiguration::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::ExtensionConfigurationUpdate& update = params->update; const Extension* extension = GetExtensionById(update.extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); if (!user_gesture()) return RespondNow(Error(kRequiresUserGestureError)); if (update.file_access) { std::string error; if (!UserCanModifyExtensionConfiguration(extension, browser_context(), &error)) { return RespondNow(Error(error)); } util::SetAllowFileAccess( extension->id(), browser_context(), *update.file_access); } if (update.incognito_access) { util::SetIsIncognitoEnabled( extension->id(), browser_context(), *update.incognito_access); } if (update.error_collection) { ErrorConsole::Get(browser_context())->SetReportingAllForExtension( extension->id(), *update.error_collection); } if (update.run_on_all_urls) { ScriptingPermissionsModifier modifier(browser_context(), extension); if (!modifier.CanAffectExtension( extension->permissions_data()->active_permissions()) && !modifier.HasAffectedExtension()) { return RespondNow( Error("Cannot modify all urls of extension: " + extension->id())); } modifier.SetAllowedOnAllUrls(*update.run_on_all_urls); } if (update.show_action_button) { ExtensionActionAPI::Get(browser_context())->SetBrowserActionVisibility( extension->id(), *update.show_action_button); } return RespondNow(NoArguments()); } DeveloperPrivateReloadFunction::~DeveloperPrivateReloadFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateReloadFunction::Run() { std::unique_ptr<Reload::Params> params(Reload::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); bool fail_quietly = params->options && params->options->fail_quietly && *params->options->fail_quietly; ExtensionService* service = GetExtensionService(browser_context()); if (fail_quietly) service->ReloadExtensionWithQuietFailure(params->extension_id); else service->ReloadExtension(params->extension_id); // TODO(devlin): We shouldn't return until the extension has finished trying // to reload (and then we could also return the error). return RespondNow(NoArguments()); } DeveloperPrivateShowPermissionsDialogFunction:: DeveloperPrivateShowPermissionsDialogFunction() {} DeveloperPrivateShowPermissionsDialogFunction:: ~DeveloperPrivateShowPermissionsDialogFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateShowPermissionsDialogFunction::Run() { std::unique_ptr<developer::ShowPermissionsDialog::Params> params( developer::ShowPermissionsDialog::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const Extension* target_extension = GetExtensionById(params->extension_id); if (!target_extension) return RespondNow(Error(kNoSuchExtensionError)); content::WebContents* web_contents = GetSenderWebContents(); if (!web_contents) return RespondNow(Error(kCouldNotFindWebContentsError)); ShowPermissionsDialogHelper::Show( browser_context(), web_contents, target_extension, source_context_type() == Feature::WEBUI_CONTEXT, base::Bind(&DeveloperPrivateShowPermissionsDialogFunction::Finish, this)); return RespondLater(); } void DeveloperPrivateShowPermissionsDialogFunction::Finish() { Respond(NoArguments()); } DeveloperPrivateLoadUnpackedFunction::DeveloperPrivateLoadUnpackedFunction() : fail_quietly_(false) { } ExtensionFunction::ResponseAction DeveloperPrivateLoadUnpackedFunction::Run() { std::unique_ptr<developer::LoadUnpacked::Params> params( developer::LoadUnpacked::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); if (!ShowPicker( ui::SelectFileDialog::SELECT_FOLDER, l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY), ui::SelectFileDialog::FileTypeInfo(), 0 /* file_type_index */)) { return RespondNow(Error(kCouldNotShowSelectFileDialogError)); } fail_quietly_ = params->options && params->options->fail_quietly && *params->options->fail_quietly; AddRef(); // Balanced in FileSelected / FileSelectionCanceled. return RespondLater(); } void DeveloperPrivateLoadUnpackedFunction::FileSelected( const base::FilePath& path) { scoped_refptr<UnpackedInstaller> installer( UnpackedInstaller::Create(GetExtensionService(browser_context()))); installer->set_be_noisy_on_failure(!fail_quietly_); installer->set_completion_callback( base::Bind(&DeveloperPrivateLoadUnpackedFunction::OnLoadComplete, this)); installer->Load(path); DeveloperPrivateAPI::Get(browser_context())->SetLastUnpackedDirectory(path); Release(); // Balanced in Run(). } void DeveloperPrivateLoadUnpackedFunction::FileSelectionCanceled() { // This isn't really an error, but we should keep it like this for // backward compatability. Respond(Error(kFileSelectionCanceled)); Release(); // Balanced in Run(). } void DeveloperPrivateLoadUnpackedFunction::OnLoadComplete( const Extension* extension, const base::FilePath& file_path, const std::string& error) { Respond(extension ? NoArguments() : Error(error)); } bool DeveloperPrivateChooseEntryFunction::ShowPicker( ui::SelectFileDialog::Type picker_type, const base::string16& select_title, const ui::SelectFileDialog::FileTypeInfo& info, int file_type_index) { content::WebContents* web_contents = GetSenderWebContents(); if (!web_contents) return false; // The entry picker will hold a reference to this function instance, // and subsequent sending of the function response) until the user has // selected a file or cancelled the picker. At that point, the picker will // delete itself. new EntryPicker(this, web_contents, picker_type, DeveloperPrivateAPI::Get(browser_context())-> GetLastUnpackedDirectory(), select_title, info, file_type_index); return true; } DeveloperPrivateChooseEntryFunction::~DeveloperPrivateChooseEntryFunction() {} void DeveloperPrivatePackDirectoryFunction::OnPackSuccess( const base::FilePath& crx_file, const base::FilePath& pem_file) { developer::PackDirectoryResponse response; response.message = base::UTF16ToUTF8( PackExtensionJob::StandardSuccessMessage(crx_file, pem_file)); response.status = developer::PACK_STATUS_SUCCESS; Respond(OneArgument(response.ToValue())); Release(); // Balanced in Run(). } void DeveloperPrivatePackDirectoryFunction::OnPackFailure( const std::string& error, ExtensionCreator::ErrorType error_type) { developer::PackDirectoryResponse response; response.message = error; if (error_type == ExtensionCreator::kCRXExists) { response.item_path = item_path_str_; response.pem_path = key_path_str_; response.override_flags = ExtensionCreator::kOverwriteCRX; response.status = developer::PACK_STATUS_WARNING; } else { response.status = developer::PACK_STATUS_ERROR; } Respond(OneArgument(response.ToValue())); Release(); // Balanced in Run(). } ExtensionFunction::ResponseAction DeveloperPrivatePackDirectoryFunction::Run() { std::unique_ptr<PackDirectory::Params> params( PackDirectory::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); int flags = params->flags ? *params->flags : 0; item_path_str_ = params->path; if (params->private_key_path) key_path_str_ = *params->private_key_path; base::FilePath root_directory = base::FilePath::FromUTF8Unsafe(item_path_str_); base::FilePath key_file = base::FilePath::FromUTF8Unsafe(key_path_str_); developer::PackDirectoryResponse response; if (root_directory.empty()) { if (item_path_str_.empty()) response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_REQUIRED); else response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_INVALID); response.status = developer::PACK_STATUS_ERROR; return RespondNow(OneArgument(response.ToValue())); } if (!key_path_str_.empty() && key_file.empty()) { response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_KEY_INVALID); response.status = developer::PACK_STATUS_ERROR; return RespondNow(OneArgument(response.ToValue())); } AddRef(); // Balanced in OnPackSuccess / OnPackFailure. // TODO(devlin): Why is PackExtensionJob ref-counted? pack_job_ = new PackExtensionJob(this, root_directory, key_file, flags); pack_job_->Start(); return RespondLater(); } DeveloperPrivatePackDirectoryFunction::DeveloperPrivatePackDirectoryFunction() { } DeveloperPrivatePackDirectoryFunction:: ~DeveloperPrivatePackDirectoryFunction() {} DeveloperPrivateLoadUnpackedFunction::~DeveloperPrivateLoadUnpackedFunction() {} bool DeveloperPrivateLoadDirectoryFunction::RunAsync() { // TODO(grv) : add unittests. std::string directory_url_str; std::string filesystem_name; std::string filesystem_path; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &directory_url_str)); context_ = content::BrowserContext::GetStoragePartition( GetProfile(), render_frame_host()->GetSiteInstance()) ->GetFileSystemContext(); // Directory url is non empty only for syncfilesystem. if (!directory_url_str.empty()) { storage::FileSystemURL directory_url = context_->CrackURL(GURL(directory_url_str)); if (!directory_url.is_valid() || directory_url.type() != storage::kFileSystemTypeSyncable) { SetError("DirectoryEntry of unsupported filesystem."); return false; } return LoadByFileSystemAPI(directory_url); } else { // Check if the DirecotryEntry is the instance of chrome filesystem. if (!app_file_handler_util::ValidateFileEntryAndGetPath( filesystem_name, filesystem_path, render_frame_host()->GetProcess()->GetID(), &project_base_path_, &error_)) { SetError("DirectoryEntry of unsupported filesystem."); return false; } // Try to load using the FileSystem API backend, in case the filesystem // points to a non-native local directory. std::string filesystem_id; bool cracked = storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id); CHECK(cracked); base::FilePath virtual_path = storage::IsolatedContext::GetInstance() ->CreateVirtualRootPath(filesystem_id) .Append(base::FilePath::FromUTF8Unsafe(filesystem_path)); storage::FileSystemURL directory_url = context_->CreateCrackedFileSystemURL( extensions::Extension::GetBaseURLFromExtensionId(extension_id()), storage::kFileSystemTypeIsolated, virtual_path); if (directory_url.is_valid() && directory_url.type() != storage::kFileSystemTypeNativeLocal && directory_url.type() != storage::kFileSystemTypeRestrictedNativeLocal && directory_url.type() != storage::kFileSystemTypeDragged) { return LoadByFileSystemAPI(directory_url); } Load(); } return true; } bool DeveloperPrivateLoadDirectoryFunction::LoadByFileSystemAPI( const storage::FileSystemURL& directory_url) { std::string directory_url_str = directory_url.ToGURL().spec(); size_t pos = 0; // Parse the project directory name from the project url. The project url is // expected to have project name as the suffix. if ((pos = directory_url_str.rfind("/")) == std::string::npos) { SetError("Invalid Directory entry."); return false; } std::string project_name; project_name = directory_url_str.substr(pos + 1); project_base_url_ = directory_url_str.substr(0, pos + 1); base::FilePath project_path(GetProfile()->GetPath()); project_path = project_path.AppendASCII(kUnpackedAppsFolder); project_path = project_path.Append( base::FilePath::FromUTF8Unsafe(project_name)); project_base_path_ = project_path; content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ClearExistingDirectoryContent, this, project_base_path_)); return true; } void DeveloperPrivateLoadDirectoryFunction::Load() { ExtensionService* service = GetExtensionService(GetProfile()); UnpackedInstaller::Create(service)->Load(project_base_path_); // TODO(grv) : The unpacked installer should fire an event when complete // and return the extension_id. SetResult(base::MakeUnique<base::StringValue>("-1")); SendResponse(true); } void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent( const base::FilePath& project_path) { // Clear the project directory before copying new files. base::DeleteFile(project_path, true /*recursive*/); pending_copy_operations_count_ = 1; content::BrowserThread::PostTask(content::BrowserThread::IO, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ReadDirectoryByFileSystemAPI, this, project_path, project_path.BaseName())); } void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI( const base::FilePath& project_path, const base::FilePath& destination_path) { GURL project_url = GURL(project_base_url_ + destination_path.AsUTF8Unsafe()); storage::FileSystemURL url = context_->CrackURL(project_url); context_->operation_runner()->ReadDirectory( url, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ReadDirectoryByFileSystemAPICb, this, project_path, destination_path)); } void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb( const base::FilePath& project_path, const base::FilePath& destination_path, base::File::Error status, const storage::FileSystemOperation::FileEntryList& file_list, bool has_more) { if (status != base::File::FILE_OK) { DLOG(ERROR) << "Error in copying files from sync filesystem."; return; } // We add 1 to the pending copy operations for both files and directories. We // release the directory copy operation once all the files under the directory // are added for copying. We do that to ensure that pendingCopyOperationsCount // does not become zero before all copy operations are finished. // In case the directory happens to be executing the last copy operation it // will call SendResponse to send the response to the API. The pending copy // operations of files are released by the CopyFile function. pending_copy_operations_count_ += file_list.size(); for (size_t i = 0; i < file_list.size(); ++i) { if (file_list[i].is_directory) { ReadDirectoryByFileSystemAPI(project_path.Append(file_list[i].name), destination_path.Append(file_list[i].name)); continue; } GURL project_url = GURL(project_base_url_ + destination_path.Append(file_list[i].name).AsUTF8Unsafe()); storage::FileSystemURL url = context_->CrackURL(project_url); base::FilePath target_path = project_path; target_path = target_path.Append(file_list[i].name); context_->operation_runner()->CreateSnapshotFile( url, base::Bind(&DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback, this, target_path)); } if (!has_more) { // Directory copy operation released here. pending_copy_operations_count_--; if (!pending_copy_operations_count_) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::SendResponse, this, success_)); } } } void DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback( const base::FilePath& target_path, base::File::Error result, const base::File::Info& file_info, const base::FilePath& src_path, const scoped_refptr<storage::ShareableFileReference>& file_ref) { if (result != base::File::FILE_OK) { SetError("Error in copying files from sync filesystem."); success_ = false; return; } content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this, src_path, target_path)); } void DeveloperPrivateLoadDirectoryFunction::CopyFile( const base::FilePath& src_path, const base::FilePath& target_path) { if (!base::CreateDirectory(target_path.DirName())) { SetError("Error in copying files from sync filesystem."); success_ = false; } if (success_) base::CopyFile(src_path, target_path); CHECK(pending_copy_operations_count_ > 0); pending_copy_operations_count_--; if (!pending_copy_operations_count_) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::Load, this)); } } DeveloperPrivateLoadDirectoryFunction::DeveloperPrivateLoadDirectoryFunction() : pending_copy_operations_count_(0), success_(true) {} DeveloperPrivateLoadDirectoryFunction::~DeveloperPrivateLoadDirectoryFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateChoosePathFunction::Run() { std::unique_ptr<developer::ChoosePath::Params> params( developer::ChoosePath::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ui::SelectFileDialog::Type type = ui::SelectFileDialog::SELECT_FOLDER; ui::SelectFileDialog::FileTypeInfo info; if (params->select_type == developer::SELECT_TYPE_FILE) type = ui::SelectFileDialog::SELECT_OPEN_FILE; base::string16 select_title; int file_type_index = 0; if (params->file_type == developer::FILE_TYPE_LOAD) { select_title = l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY); } else if (params->file_type == developer::FILE_TYPE_PEM) { select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_KEY); info.extensions.push_back(std::vector<base::FilePath::StringType>( 1, FILE_PATH_LITERAL("pem"))); info.extension_description_overrides.push_back( l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_KEY_FILE_TYPE_DESCRIPTION)); info.include_all_files = true; file_type_index = 1; } else { NOTREACHED(); } if (!ShowPicker( type, select_title, info, file_type_index)) { return RespondNow(Error(kCouldNotShowSelectFileDialogError)); } AddRef(); // Balanced by FileSelected / FileSelectionCanceled. return RespondLater(); } void DeveloperPrivateChoosePathFunction::FileSelected( const base::FilePath& path) { Respond(OneArgument( base::MakeUnique<base::StringValue>(path.LossyDisplayName()))); Release(); } void DeveloperPrivateChoosePathFunction::FileSelectionCanceled() { // This isn't really an error, but we should keep it like this for // backward compatability. Respond(Error(kFileSelectionCanceled)); Release(); } DeveloperPrivateChoosePathFunction::~DeveloperPrivateChoosePathFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateIsProfileManagedFunction::Run() { return RespondNow(OneArgument(base::MakeUnique<base::FundamentalValue>( Profile::FromBrowserContext(browser_context())->IsSupervised()))); } DeveloperPrivateIsProfileManagedFunction:: ~DeveloperPrivateIsProfileManagedFunction() { } DeveloperPrivateRequestFileSourceFunction:: DeveloperPrivateRequestFileSourceFunction() {} DeveloperPrivateRequestFileSourceFunction:: ~DeveloperPrivateRequestFileSourceFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateRequestFileSourceFunction::Run() { params_ = developer::RequestFileSource::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_); const developer::RequestFileSourceProperties& properties = params_->properties; const Extension* extension = GetExtensionById(properties.extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); // Under no circumstances should we ever need to reference a file outside of // the extension's directory. If it tries to, abort. base::FilePath path_suffix = base::FilePath::FromUTF8Unsafe(properties.path_suffix); if (path_suffix.empty() || path_suffix.ReferencesParent()) return RespondNow(Error(kInvalidPathError)); if (properties.path_suffix == kManifestFile && !properties.manifest_key) return RespondNow(Error(kManifestKeyIsRequiredError)); base::PostTaskAndReplyWithResult( content::BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&ReadFileToString, extension->path().Append(path_suffix)), base::Bind(&DeveloperPrivateRequestFileSourceFunction::Finish, this)); return RespondLater(); } void DeveloperPrivateRequestFileSourceFunction::Finish( const std::string& file_contents) { const developer::RequestFileSourceProperties& properties = params_->properties; const Extension* extension = GetExtensionById(properties.extension_id); if (!extension) { Respond(Error(kNoSuchExtensionError)); return; } developer::RequestFileSourceResponse response; base::FilePath path_suffix = base::FilePath::FromUTF8Unsafe(properties.path_suffix); base::FilePath path = extension->path().Append(path_suffix); response.title = base::StringPrintf("%s: %s", extension->name().c_str(), path.BaseName().AsUTF8Unsafe().c_str()); response.message = properties.message; std::unique_ptr<FileHighlighter> highlighter; if (properties.path_suffix == kManifestFile) { highlighter.reset(new ManifestHighlighter( file_contents, *properties.manifest_key, properties.manifest_specific ? *properties.manifest_specific : std::string())); } else { highlighter.reset(new SourceHighlighter( file_contents, properties.line_number ? *properties.line_number : 0)); } response.before_highlight = highlighter->GetBeforeFeature(); response.highlight = highlighter->GetFeature(); response.after_highlight = highlighter->GetAfterFeature(); Respond(OneArgument(response.ToValue())); } DeveloperPrivateOpenDevToolsFunction::DeveloperPrivateOpenDevToolsFunction() {} DeveloperPrivateOpenDevToolsFunction::~DeveloperPrivateOpenDevToolsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateOpenDevToolsFunction::Run() { std::unique_ptr<developer::OpenDevTools::Params> params( developer::OpenDevTools::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::OpenDevToolsProperties& properties = params->properties; if (properties.render_process_id == -1) { // This is a lazy background page. const Extension* extension = properties.extension_id ? GetEnabledExtensionById(*properties.extension_id) : nullptr; if (!extension) return RespondNow(Error(kNoSuchExtensionError)); Profile* profile = GetProfile(); if (properties.incognito && *properties.incognito) profile = profile->GetOffTheRecordProfile(); // Wakes up the background page and opens the inspect window. devtools_util::InspectBackgroundPage(extension, profile); return RespondNow(NoArguments()); } // NOTE(devlin): Even though the properties use "render_view_id", this // actually refers to a render frame. content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( properties.render_process_id, properties.render_view_id); content::WebContents* web_contents = rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; // It's possible that the render frame was closed since we last updated the // links. Handle this gracefully. if (!web_contents) return RespondNow(Error(kNoSuchRendererError)); // If we include a url, we should inspect it specifically (and not just the // render frame). if (properties.url) { // Line/column numbers are reported in display-friendly 1-based numbers, // but are inspected in zero-based numbers. // Default to the first line/column. DevToolsWindow::OpenDevToolsWindow( web_contents, DevToolsToggleAction::Reveal( base::UTF8ToUTF16(*properties.url), properties.line_number ? *properties.line_number - 1 : 0, properties.column_number ? *properties.column_number - 1 : 0)); } else { DevToolsWindow::OpenDevToolsWindow(web_contents); } // Once we open the inspector, we focus on the appropriate tab... Browser* browser = chrome::FindBrowserWithWebContents(web_contents); // ... but some pages (popups and apps) don't have tabs, and some (background // pages) don't have an associated browser. For these, the inspector opens in // a new window, and our work is done. if (!browser || !browser->is_type_tabbed()) return RespondNow(NoArguments()); TabStripModel* tab_strip = browser->tab_strip_model(); tab_strip->ActivateTabAt(tab_strip->GetIndexOfWebContents(web_contents), false); // Not through direct user gesture. return RespondNow(NoArguments()); } DeveloperPrivateDeleteExtensionErrorsFunction:: ~DeveloperPrivateDeleteExtensionErrorsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateDeleteExtensionErrorsFunction::Run() { std::unique_ptr<developer::DeleteExtensionErrors::Params> params( developer::DeleteExtensionErrors::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::DeleteExtensionErrorsProperties& properties = params->properties; ErrorConsole* error_console = ErrorConsole::Get(GetProfile()); int type = -1; if (properties.type != developer::ERROR_TYPE_NONE) { type = properties.type == developer::ERROR_TYPE_MANIFEST ? ExtensionError::MANIFEST_ERROR : ExtensionError::RUNTIME_ERROR; } std::set<int> error_ids; if (properties.error_ids) { error_ids.insert(properties.error_ids->begin(), properties.error_ids->end()); } error_console->RemoveErrors(ErrorMap::Filter( properties.extension_id, type, error_ids, false)); return RespondNow(NoArguments()); } DeveloperPrivateRepairExtensionFunction:: ~DeveloperPrivateRepairExtensionFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateRepairExtensionFunction::Run() { std::unique_ptr<developer::RepairExtension::Params> params( developer::RepairExtension::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); content::WebContents* web_contents = GetSenderWebContents(); if (!web_contents) return RespondNow(Error(kCouldNotFindWebContentsError)); scoped_refptr<WebstoreReinstaller> reinstaller(new WebstoreReinstaller( web_contents, params->extension_id, base::Bind(&DeveloperPrivateRepairExtensionFunction::OnReinstallComplete, this))); reinstaller->BeginReinstall(); return RespondLater(); } void DeveloperPrivateRepairExtensionFunction::OnReinstallComplete( bool success, const std::string& error, webstore_install::Result result) { Respond(success ? NoArguments() : Error(error)); } DeveloperPrivateShowOptionsFunction::~DeveloperPrivateShowOptionsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateShowOptionsFunction::Run() { std::unique_ptr<developer::ShowOptions::Params> params( developer::ShowOptions::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetEnabledExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); if (OptionsPageInfo::GetOptionsPage(extension).is_empty()) return RespondNow(Error(kNoOptionsPageForExtensionError)); content::WebContents* web_contents = GetSenderWebContents(); if (!web_contents) return RespondNow(Error(kCouldNotFindWebContentsError)); ExtensionTabUtil::OpenOptionsPage( extension, chrome::FindBrowserWithWebContents(web_contents)); return RespondNow(NoArguments()); } DeveloperPrivateShowPathFunction::~DeveloperPrivateShowPathFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateShowPathFunction::Run() { std::unique_ptr<developer::ShowPath::Params> params( developer::ShowPath::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); // We explicitly show manifest.json in order to work around an issue in OSX // where opening the directory doesn't focus the Finder. platform_util::ShowItemInFolder(GetProfile(), extension->path().Append(kManifestFilename)); return RespondNow(NoArguments()); } DeveloperPrivateSetShortcutHandlingSuspendedFunction:: ~DeveloperPrivateSetShortcutHandlingSuspendedFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateSetShortcutHandlingSuspendedFunction::Run() { std::unique_ptr<developer::SetShortcutHandlingSuspended::Params> params( developer::SetShortcutHandlingSuspended::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionCommandsGlobalRegistry::Get(GetProfile())-> SetShortcutHandlingSuspended(params->is_suspended); return RespondNow(NoArguments()); } DeveloperPrivateUpdateExtensionCommandFunction:: ~DeveloperPrivateUpdateExtensionCommandFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateUpdateExtensionCommandFunction::Run() { std::unique_ptr<developer::UpdateExtensionCommand::Params> params( developer::UpdateExtensionCommand::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::ExtensionCommandUpdate& update = params->update; CommandService* command_service = CommandService::Get(GetProfile()); if (update.scope != developer::COMMAND_SCOPE_NONE) { command_service->SetScope(update.extension_id, update.command_name, update.scope == developer::COMMAND_SCOPE_GLOBAL); } if (update.keybinding) { command_service->UpdateKeybindingPrefs( update.extension_id, update.command_name, *update.keybinding); } return RespondNow(NoArguments()); } } // namespace api } // namespace extensions
LioBuitrago/pp_2020_autumn_informatics
modules/task_3/alibekov_m_component_labeling/component_labeling.h
// Copyright 2020 <NAME> #ifndef MODULES_TASK_3_ALIBEKOV_M_COMPONENT_LABELING_COMPONENT_LABELING_H_ #define MODULES_TASK_3_ALIBEKOV_M_COMPONENT_LABELING_COMPONENT_LABELING_H_ #include <vector> #include <utility> std::pair<std::vector<int>, int> component_labeling_sequential(const std::vector<int>& image, int width, int height); std::pair<std::vector<int>, std::pair<std::vector<int>, int> > first_pass(const std::vector<int>& image, int width, int height, int begin_label = 0); std::vector<int> second_pass(std::vector<int> map, std::vector<int> disjoint_sets, int width, int height); std::pair<std::vector<int>, int> component_labeling_parallel(const std::vector<int>& image, int width, int height); std::vector<int> generate_random_image(int width, int height); std::vector<int> remarking(const std::vector<int>& image, int width, int height); #endif // MODULES_TASK_3_ALIBEKOV_M_COMPONENT_LABELING_COMPONENT_LABELING_H_
WDCDevTeam/jace-dps-express
src/modules/dj-dps-commands/src/service/data/sota-covid/fetch-data.js
<gh_stars>1-10 let series = require("./series-meta") let { flatten} = require("lodash") series = series.map( s => s.values.map( v => ({ column: v.field, category: s.category, title: v.title, description: `${s.category}: ${v.title}` }))) console.log(JSON.stringify(series, null, " "))
ppYoung/tdesign-mobile-vue
site/web/test-coverage.js
module.exports = { "": "93.84%", "actionSheet": "24.48%", "actionSheet/demos": "0%", "actionSheet/style": "0%", "avatar": "91.17%", "avatarGroup": "35.89%", "avatarGroup/style": "0%", "avatar/demos": "0%", "avatar/style": "0%", "backTop": "93.93%", "backTop/demos": "0%", "backTop/style": "0%", "badge": "88.57%", "badge/demos": "0%", "badge/style": "0%", "button": "91.17%", "buttonGroup": "83.33%", "buttonGroup/style": "0%", "button/demos": "0%", "button/style": "0%", "cell": "100%", "cellGroup": "92.85%", "cellGroup/style": "0%", "cell/demos": "0%", "cell/style": "0%", "checkGroup": "13.97%", "checkGroup/style": "0%", "checkbox": "35.41%", "checkbox/demos": "0%", "checkbox/style": "0%", "collapse": "27.1%", "collapse/demos": "0%", "collapse/style": "0%", "countDown": "73.68%", "countDown/demos": "0%", "countDown/style": "0%", "dateTimePicker": "12.3%", "dateTimePicker/demos": "0%", "dateTimePicker/style": "0%", "dialog": "24.13%", "dialog/demos": "0%", "dialog/style": "0%", "divider": "70%", "divider/style": "0%", "drawer": "42.85%", "drawer/demos": "0%", "drawer/style": "0%", "dropdownMenu": "0%", "dropdownMenu/demos": "0%", "dropdownMenu/style": "0%", "fab": "57.14%", "fab/style": "0%", "grid": "41.07%", "grid/demos": "0%", "grid/style": "0%", "image": "31.37%", "imageViewer": "8.62%", "imageViewer/demos": "0%", "imageViewer/style": "0%", "image/demos": "0%", "image/style": "0%", "indexes": "23.89%", "indexes/demos": "0%", "indexes/style": "0%", "input": "29.82%", "input/demos": "0%", "input/style": "0%", "list": "26.49%", "list/demos": "0%", "list/style": "0%", "loading": "39.13%", "loading/demos": "0%", "loading/icon": "57.14%", "loading/style": "0%", "mask": "76.92%", "mask/demos": "0%", "mask/style": "0%", "message": "32.75%", "message/demos": "0%", "message/style": "0%", "navbar": "50%", "navbar/demos": "0%", "navbar/style": "0%", "noticeBar": "0%", "noticeBar/demos": "0%", "noticeBar/style": "0%", "picker": "12.65%", "picker/demos": "0%", "picker/style": "0%", "popup": "34.88%", "popup/demos": "0%", "popup/style": "0%", "progress": "54.54%", "progress/style": "0%", "radio": "32.72%", "radioGroup": "48%", "radioGroup/style": "0%", "radio/demos": "0%", "radio/style": "0%", "rate": "30%", "rate/demos": "0%", "rate/style": "0%", "search": "28.94%", "search/demos": "0%", "search/style": "0%", "shared": "66.66%", "shared/useChildSlots": "10.52%", "shared/useCountDown": "21.05%", "shared/useDefault": "7.89%", "shared/useEmitEvent": "33.33%", "shared/useInterval": "0%", "shared/useToggle": "14.28%", "skeleton": "31.25%", "skeleton/demos": "0%", "skeleton/style": "0%", "slider": "10.28%", "slider/demos": "0%", "slider/style": "0%", "stepper": "35.55%", "stepper/demos": "0%", "stepper/style": "0%", "steps": "32.46%", "steps/demos": "0%", "steps/style": "0%", "sticky": "29.78%", "sticky/demos": "0%", "sticky/style": "0%", "style": "0%", "swipeCell": "15.38%", "swipeCell/demos": "0%", "swipeCell/style": "0%", "swiper": "14.28%", "swiper/demos": "0%", "swiper/style": "0%", "switch": "51.72%", "switch/demos": "0%", "switch/style": "0%", "tabBar": "40.9%", "tabBar/demos": "0%", "tabBar/style": "0%", "tabs": "29%", "tabs/demos": "0%", "tabs/style": "0%", "tag": "39.7%", "tag/demos": "0%", "tag/style": "0%", "textarea": "23.07%", "textarea/style": "0%", "toast": "34.32%", "toast/demos": "0%", "toast/style": "0%" }
ani03sha/OnlineJudge
LeetCode/src/main/java/org/redquark/onlinejudges/leetcode/math/RandomPickIndex.java
<filename>LeetCode/src/main/java/org/redquark/onlinejudges/leetcode/math/RandomPickIndex.java<gh_stars>10-100 package org.redquark.onlinejudges.leetcode.math; import java.util.ArrayList; import java.util.List; import java.util.Random; public class RandomPickIndex { private final int[] nums; private final Random random; public RandomPickIndex(int[] nums) { this.nums = nums; this.random = new Random(); } public int pickOne(int target) { // List to store the indices of the target // in the array List<Integer> indices = new ArrayList<>(); // Loop through the array for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { indices.add(i); } } // Size of the list int size = indices.size(); return indices.get(random.nextInt(size)); } public int pickTwo(int target) { // Count of the numbers equal to target in the array int count = 0; // Random index corresponds to the target element int randomIndex = 0; // Loop through the array for (int i = 0; i < nums.length; i++) { // If the current element is equal to the target if (nums[i] == target) { // Update the count count++; // Pick the current number with probability 1/count if (random.nextInt(count) == 0) { randomIndex = i; } } } return randomIndex; } }
praekelt/molo.surveys
molo/surveys/migrations/0012_add_terms_and_conditions_page.py
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-09-27 10:12 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import modelcluster.fields import molo.core.blocks import molo.core.models import wagtail.core.blocks import wagtail.core.fields import wagtail.images.blocks class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0032_add_bulk_delete_page_permission'), ('wagtailimages', '0018_remove_rendition_filter'), ('surveys', '0011_groupmembershiprule_surveysubmissiondatarule'), ] operations = [ migrations.CreateModel( name='SurveyTermsConditions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sort_order', models.IntegerField(blank=True, editable=False, null=True)), ], options={ 'ordering': ['sort_order'], 'abstract': False, }, ), migrations.CreateModel( name='TermsAndConditionsIndexPage', fields=[ ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')), ], options={ 'abstract': False, }, bases=(molo.core.models.TranslatablePageMixinNotRoutable, 'wagtailcore.page', molo.core.models.PreventDeleteMixin), ), migrations.AddField( model_name='molosurveypage', name='content', field=wagtail.core.fields.StreamField([(b'heading', wagtail.core.blocks.CharBlock(classname=b'full title')), (b'paragraph', molo.core.blocks.MarkDownBlock()), (b'image', wagtail.images.blocks.ImageChooserBlock()), (b'list', wagtail.core.blocks.ListBlock(wagtail.core.blocks.CharBlock(label=b'Item'))), (b'numbered_list', wagtail.core.blocks.ListBlock(wagtail.core.blocks.CharBlock(label=b'Item'))), (b'page', wagtail.core.blocks.PageChooserBlock())], blank=True, null=True), ), migrations.AddField( model_name='molosurveypage', name='extra_style_hints', field=models.TextField(blank=True, default=b'', help_text='Styling options that can be applied to this page and all its descendants', null=True), ), migrations.AddField( model_name='molosurveypage', name='image', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'), ), migrations.AddField( model_name='surveytermsconditions', name='page', field=modelcluster.fields.ParentalKey(on_delete=django.db.models.deletion.CASCADE, related_name='terms_and_conditions', to='surveys.MoloSurveyPage'), ), migrations.AddField( model_name='surveytermsconditions', name='terms_and_conditions', field=models.ForeignKey(blank=True, help_text='Terms and Conditions', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page'), ), ]
kokabe2/malkt
src/isr/utkernel/basic_isr.c
<gh_stars>0 // Copyright(c) 2020 <NAME> // This software is released under the MIT License, see LICENSE. #include "basic_isr.h" #include "bleu/v1/heap.h" #include "utkernel/utkernel.h" typedef struct { IsrInterfaceStruct impl; int number; int level; } BasicIsrStruct, *BasicIsr; inline static void Register(Isr self, InterruptDelegate delegate) { T_DINT packet = {.intatr = TA_HLNG, .inthdr = (FP)delegate}; tk_def_int((UINT)((BasicIsr)self)->number, &packet); } static void DummyInterrupt(int unused) {} inline static void Unregister(Isr self) { Register(self, DummyInterrupt); } static void Delete(Isr* self) { DisableInt((UINT)((BasicIsr)(*self))->number); Unregister(*self); heap->Delete((void**)self); } static void Enable(Isr self) { EnableInt((UINT)((BasicIsr)self)->number, ((BasicIsr)self)->level); } static void Disable(Isr self) { DisableInt((UINT)((BasicIsr)self)->number); } static const IsrInterfaceStruct kTheInterface = { .Delete = Delete, .Enable = Enable, .Disable = Disable, }; static Isr New(int interrupt_number, int interrupt_level, InterruptDelegate delegate) { BasicIsr self = (BasicIsr)heap->New(sizeof(BasicIsrStruct)); self->impl = kTheInterface; self->number = interrupt_number; self->level = interrupt_level; Register((Isr)self, delegate); return (Isr)self; } static const BasicIsrMethodStruct kTheMethod = { .New = New, }; const BasicIsrMethod basicIsr = &kTheMethod;
NEKERAFA/Soul-Tower
src/sprites/HectorTrigger.py
<filename>src/sprites/HectorTrigger.py # -*- coding: utf-8 -*- import pygame, os from src.sprites.ConditionalTrigger import * class HectorTrigger(ConditionalTrigger): def activate(self, player): if player.killedFriend: self.dialogueFile = self.dialogueList[0] else: self.dialogueFile = self.dialogueList[1]
mderijk/codenames
website/server/codenames/game/twoplayergame.py
<reponame>mderijk/codenames<gh_stars>1-10 from . import twoplayergame class LocalCoopGame(twoplayergame.TwoPlayerGame): def __init__(self, users, possible_words, teams=None): pass
uiters/c3t-service
module/config/index.js
const tokenConfig = require('./token') const {privatekey} = require('./common') const {logDir} = require('./logger') const dbConfig = require('./mongo') module.exports = {tokenConfig, privatekey, logDir, dbConfig}
jihwahn1018/ovirt-engine
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/action/AddSANStorageDomainParameters.java
<reponame>jihwahn1018/ovirt-engine package org.ovirt.engine.core.common.action; import java.util.HashSet; import java.util.Set; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; public class AddSANStorageDomainParameters extends StorageDomainManagementParameter { private static final long serialVersionUID = 6386931158747982426L; private Set<String> lunIds; public Set<String> getLunIds() { if (lunIds == null) { lunIds = new HashSet<>(); } return lunIds; } public void setLunIds(Set<String> value) { lunIds = value; } private boolean force; public boolean isForce() { return force; } public void setForce(boolean force) { this.force = force; } public AddSANStorageDomainParameters(StorageDomainStatic storageDomain) { super(storageDomain); } public AddSANStorageDomainParameters() { } }
andr92/neptune
core.api/src/main/java/ru/tinkoff/qa/neptune/core/api/properties/enums/EnumPropertySuppler.java
<reponame>andr92/neptune package ru.tinkoff.qa.neptune.core.api.properties.enums; import ru.tinkoff.qa.neptune.core.api.properties.PropertySupplier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import static com.google.common.reflect.TypeToken.of; import static java.lang.String.format; import static java.util.Arrays.stream; /** * This interface is designed to read properties and return single constants declared by enums. * * @param <T> is a type of enum. */ public interface EnumPropertySuppler<T extends Enum<?>> extends PropertySupplier<T, T> { @SuppressWarnings("unchecked") @Override default T parse(String name) { Class<?> cls = this.getClass(); Type[] interfaces; Type enumSupplier; while ((interfaces = cls.getGenericInterfaces()).length == 0 || (enumSupplier = stream(interfaces) .filter(type -> EnumPropertySuppler.class.isAssignableFrom(of(type).getRawType())) .findFirst() .orElse(null)) == null) { cls = cls.getSuperclass(); } var enumType = ((Class<T>) ((ParameterizedType) enumSupplier).getActualTypeArguments()[0]); return stream(enumType.getEnumConstants()).filter(t -> name.trim().equals(t.name())) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Unknown constant %s from enum %s", name, enumType.getName()))); } @Override default String readValuesToSet(T value) { return value.name(); } }
heropan/Elastos.ELA.SPV.Cpp
SDK/WalletCore/ElaWebWalletJson.cpp
// Copyright (c) 2012-2018 The Elastos Open Source Project // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "ElaWebWalletJson.h" namespace Elastos { namespace ElaWallet { ElaWebWalletJson::ElaWebWalletJson() { } ElaWebWalletJson::~ElaWebWalletJson() { _mnemonic.resize(_mnemonic.size(), 0); } nlohmann::json ElaWebWalletJson::ToJson(bool withPrivKey) const { nlohmann::json j = BitcoreWalletClientJson::ToJson(withPrivKey); if (withPrivKey) j["mnemonic"] = _mnemonic; return j; } void ElaWebWalletJson::FromJson(const nlohmann::json &j) { BitcoreWalletClientJson::FromJson(j); if (j.find("mnemonic") != j.end()) _mnemonic = j["mnemonic"].get<std::string>(); } } }
holman/tissues
vendor/octopi-0.2.9/lib/octopi/issue_set.rb
<gh_stars>1-10 require File.join(File.dirname(__FILE__), "issue") class Octopi::IssueSet < Array include Octopi attr_accessor :user, :repository def initialize(array) unless array.empty? self.user = array.first.user self.repository = array.first.repository super(array) end end def find(number) issue = detect { |issue| issue.number == number } raise NotFound, Issue if issue.nil? issue end def search(options={}) Issue.search(options.merge(:user => user, :repo => repository)) end end
tgodzik/intellij-community
java/java-tests/testData/inspection/notNullField/quickFix/afterRemoveAnnotation.java
<reponame>tgodzik/intellij-community<filename>java/java-tests/testData/inspection/notNullField/quickFix/afterRemoveAnnotation.java // "Remove not-null annotation" "true" import org.jetbrains.annotations.NotNull; class X { String x; }
scdoja/suum
client/src/components/Form/Form.js
import React, { useState } from 'react'; import { useForm } from 'react-hook-form'; import '../Button/Button.scss'; import './Form.scss'; import axios from 'axios'; import { useHistory } from "react-router-dom"; export const Form = ({ toggleForm }) => { const history = useHistory(); // type FormValues = { // habit1: string; // habit2: string; // habit3: string; // }; const { register, handleSubmit } = useForm(); const onSubmit = (data) => { console.log(data); var i; for (i = 0; i < 3; i++) { let habitSelected = ("habit" + (i + 1)); let eachNewHabit = { "habitName": data[habitSelected] }; sendNewHabits(eachNewHabit); } async function sendNewHabits(data) { // Send habit id to complete the habit; const newtHabit = await axios.post(`/api/habit`, data) .then(res => { console.log(res); }); } toggleForm(); //history.push("/home"); window.location.reload(); } const handleClick = () => { console.log("click!"); } return ( <div className="modalWrapper" id="modalbackdrop" > <div className="formInner"> <div className="formContent center-text"> <h2 style={{ color: "white", fontSize: "24px", marginBottom: "30px" }} className="extrabold">What do you want to do tomorrow?</h2> <form onSubmit={handleSubmit(onSubmit)}> <input className="inputBg margin-y" id="habit1" placeholder="take a 5min walk" {...register("habit1")} /> <input className="inputBg margin-y" id="habit2" placeholder="Drink 3 Glasses of water" {...register("habit2")} /> <input className="inputBg margin-y" id="habit3" placeholder="take a 5min walk" {...register("habit3")} /> {/* <a href="" className="helpLink">Need help finding a habit?</a> */} <input className="btn btn-lg btn-yellow bottomBtn" type="submit" value="Let's Go!" /> </form> </div> </div> </div> ); };
cyq7on/batteryhub
app/src/main/java/com/hmatalonga/greenhub/managers/sampling/DataEstimator.java
/* * Copyright (C) 2016 <NAME> & <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hmatalonga.greenhub.managers.sampling; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ReceiverCallNotAllowedException; import android.os.BatteryManager; import android.support.v4.content.WakefulBroadcastReceiver; import com.hmatalonga.greenhub.R; import com.hmatalonga.greenhub.events.BatteryLevelEvent; import com.hmatalonga.greenhub.util.Notifier; import com.hmatalonga.greenhub.util.SettingsUtils; import org.greenrobot.eventbus.EventBus; import java.util.Calendar; import static com.hmatalonga.greenhub.util.LogUtils.LOGE; import static com.hmatalonga.greenhub.util.LogUtils.LOGI; import static com.hmatalonga.greenhub.util.LogUtils.makeLogTag; /** * Provides current Device data readings. * * Created by hugo on 09-04-2016. */ public class DataEstimator extends WakefulBroadcastReceiver { private static final String TAG = makeLogTag(DataEstimator.class); private long lastNotify; private int mHealth; private int level; private int plugged; private boolean present; private int scale; private int status; private String technology; private float temperature; private float voltage; @Override public void onReceive(Context context, Intent intent) { if (context == null) { LOGE(TAG, "Error, context is null"); return; } if (intent == null) { LOGE(TAG, "Data Estimator error, received intent is null"); return; } LOGI(TAG, "onReceive action => " + intent.getAction()); if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { try { level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); mHealth = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0); plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); present = intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT); status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0); technology = intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY); temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10; voltage = ((float) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0)) / 1000; } catch (RuntimeException e) { e.printStackTrace(); } // We don't send battery level alerts here because we need to check if the level changed // So we verify that inside the DataEstimator Service if (temperature > SettingsUtils.fetchTemperatureWarning(context)) { if (SettingsUtils.isBatteryAlertsOn(context) && SettingsUtils.isTemperatureAlertsOn(context)) { // Check temperature limit rate Calendar lastAlert = Calendar.getInstance(); long lastSavedTime = SettingsUtils.fetchLastTemperatureAlertDate(context); // Set last alert time with saved preferences if (lastSavedTime != 0) { lastAlert.setTimeInMillis(lastSavedTime); } int minutes = SettingsUtils.fetchTemperatureAlertsRate(context); lastAlert.add(Calendar.MINUTE, minutes); // If last saved time isn't default and now is after limit rate then notify if (lastSavedTime == 0 || Calendar.getInstance().after(lastAlert)) { // Notify for temperature alerts... if (temperature > SettingsUtils.fetchTemperatureHigh(context)) { Notifier.batteryHighTemperature(context); SettingsUtils.saveLastTemperatureAlertDate( context, System.currentTimeMillis() ); } else if (temperature <= SettingsUtils.fetchTemperatureHigh(context) && temperature > SettingsUtils.fetchTemperatureWarning(context)) { Notifier.batteryWarningTemperature(context); SettingsUtils.saveLastTemperatureAlertDate( context, System.currentTimeMillis() ); } } } } } // On some phones, scale is always 0. if (scale == 0) scale = 100; if (level > 0) { Inspector.setCurrentBatteryLevel(level, scale); // Location updates disabled for now // requestLocationUpdates(); // Update last known location... // if (lastKnownLocation == null) { // lastKnownLocation = LocationInfo.getLastKnownLocation(context); // } Intent service = new Intent(context, DataEstimatorService.class); service.putExtra("OriginalAction", intent.getAction()); service.fillIn(intent, 0); if (SettingsUtils.isPowerIndicatorShown(context)) { LOGI(TAG, "Updating notification status bar"); Notifier.updateStatusBar(context); } EventBus.getDefault().post(new BatteryLevelEvent(level)); startWakefulService(context, service); } } public static Intent getBatteryChangedIntent(final Context context) { return context.registerReceiver( null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED) ); } // Getters & Setters public void getCurrentStatus(final Context context) { IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); try { Intent batteryStatus = context.registerReceiver(null, ifilter); if (batteryStatus != null) { level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); mHealth = batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, 0); plugged = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); present = batteryStatus.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT); status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, 0); technology = batteryStatus.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY); temperature = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10); voltage = (float) (batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) / 1000); } } catch (ReceiverCallNotAllowedException e) { LOGE(TAG, "ReceiverCallNotAllowedException from Notification Receiver?"); e.printStackTrace(); } } public String getHealthStatus() { String status = ""; switch (mHealth) { case BatteryManager.BATTERY_HEALTH_UNKNOWN: status = "Unknown"; break; case BatteryManager.BATTERY_HEALTH_GOOD: status = "Good"; break; case BatteryManager.BATTERY_HEALTH_OVERHEAT: status = "Overheat"; break; case BatteryManager.BATTERY_HEALTH_DEAD: status = "Dead"; break; case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: status = "Over Voltage"; break; case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: status = "Unspecified Failure"; break; } return status; } public String getHealthStatus(Context context) { String status = ""; switch (mHealth) { case BatteryManager.BATTERY_HEALTH_UNKNOWN: status = context.getString(R.string.battery_health_unknown); break; case BatteryManager.BATTERY_HEALTH_GOOD: status = context.getString(R.string.battery_health_good); break; case BatteryManager.BATTERY_HEALTH_OVERHEAT: status = context.getString(R.string.battery_health_overheat); break; case BatteryManager.BATTERY_HEALTH_DEAD: status = context.getString(R.string.battery_health_dead); break; case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: status = context.getString(R.string.battery_health_over_voltage); break; case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: status = context.getString(R.string.battery_health_failure); break; } return status; } public long getLastNotify() { return lastNotify; } public void setLastNotify(long now) { this.lastNotify = now; } public int getHealth() { return mHealth; } public int getLevel() { return level; } public int getPlugged() { return plugged; } public boolean isPresent() { return present; } public int getScale() { return scale; } public int getStatus() { return status; } public String getTechnology() { return technology; } public float getTemperature() { return temperature; } public float getVoltage() { return voltage; } }
dhineshkumarmcci/Catena-Arduino-Platform
src/lib/samd/CatenaRTC.cpp
/* catenartc.cpp Mon Nov 26 2018 15:02:35 chwon */ /* Module: catenartc.cpp Function: CatenaRTC class Version: V0.12.0 Mon Nov 26 2018 15:02:35 chwon Edit level 3 Copyright notice: This file copyright (C) 2016, 2018 by MCCI Corporation 3520 Krums Corners Road Ithaca, NY 14850 An unpublished work. All rights reserved. This file is proprietary information, and may not be disclosed or copied without the prior permission of MCCI Corporation. Author: <NAME>, MCCI Corporation November 2016 Revision history: 0.3.0 Tue Nov 1 2016 23:41:10 tmm Module created. 0.3.0 Thu Nov 10 2016 23:41:10 tmm Add debugging code. Disable all other interrupt sources during sleep other than RTC (don't let Systick wake us up). 0.12.0 Mon Nov 26 2018 15:02:36 chwon Remove RTCZero library. */ #ifdef ARDUINO_ARCH_SAMD #include <CatenaRTC.h> using namespace McciCatena; /****************************************************************************\ | | Manifest constants & typedefs. | | This is strictly for private types and constants which will not | be exported. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | | If program is to be ROM-able, these must all be tagged read-only | using the ROM storage class; they may be global. | \****************************************************************************/ /****************************************************************************\ | | VARIABLES: | | If program is to be ROM-able, these must be initialized | using the BSS keyword. (This allows for compilers that require | every variable to have an initializer.) Note that only those | variables owned by this module should be declared here, using the BSS | keyword; this allows for linkers that dislike multiple declarations | of objects. | \****************************************************************************/ extern "C" { static volatile uint32_t *gs_pAlarm; void RTC_Handler(void) { if (gs_pAlarm) *gs_pAlarm = 1; // must clear flag at end RTC->MODE2.INTFLAG.reg = RTC_MODE2_INTFLAG_ALARM0; } /* Wait for sync in write operations */ static inline void RtcWaitSynchronize(void) { while (RTC->MODE2.STATUS.bit.SYNCBUSY) ; } } /* extern "C" */ bool CatenaRTC::begin(bool fResetTime) { uint16_t tmp_reg = 0; /* turn on digital interface clock */ PM->APBAMASK.reg |= PM_APBAMASK_RTC; /* Configure the 32768Hz Oscillator */ SYSCTRL->XOSC32K.reg = SYSCTRL_XOSC32K_ONDEMAND | SYSCTRL_XOSC32K_RUNSTDBY | SYSCTRL_XOSC32K_EN32K | SYSCTRL_XOSC32K_XTALEN | SYSCTRL_XOSC32K_STARTUP(6) | SYSCTRL_XOSC32K_ENABLE; // If the RTC is in clock mode and the reset was // not due to POR or BOD, preserve the clock time // POR causes a reset anyway, BOD behaviour is? bool validTime = false; RTC_MODE2_CLOCK_Type oldTime; if (! fResetTime && (PM->RCAUSE.reg & (PM_RCAUSE_SYST | PM_RCAUSE_WDT | PM_RCAUSE_EXT))) { if (RTC->MODE2.CTRL.reg & RTC_MODE2_CTRL_MODE_CLOCK) { validTime = true; oldTime.reg = RTC->MODE2.CLOCK.reg; } } /* Attach peripheral clock to 32k oscillator */ GCLK->GENDIV.reg = GCLK_GENDIV_ID(2)|GCLK_GENDIV_DIV(4); while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY) ; GCLK->GENCTRL.reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_XOSC32K | GCLK_GENCTRL_ID(2) | GCLK_GENCTRL_DIVSEL; while (GCLK->STATUS.reg & GCLK_STATUS_SYNCBUSY) ; GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK2 | (RTC_GCLK_ID << GCLK_CLKCTRL_ID_Pos); while (GCLK->STATUS.bit.SYNCBUSY) ; // disable RTC RTC->MODE2.CTRL.reg &= ~RTC_MODE2_CTRL_ENABLE; RtcWaitSynchronize(); // RTC software reset RTC->MODE2.CTRL.reg |= RTC_MODE2_CTRL_SWRST; RtcWaitSynchronize(); tmp_reg |= RTC_MODE2_CTRL_MODE_CLOCK; // set clock operating mode tmp_reg |= RTC_MODE2_CTRL_PRESCALER_DIV1024; // set prescaler to 1024 for MODE2 tmp_reg &= ~RTC_MODE2_CTRL_MATCHCLR; // disable clear on match //According to the datasheet RTC_MODE2_CTRL_CLKREP = 0 for 24h tmp_reg &= ~RTC_MODE2_CTRL_CLKREP; // 24h time representation RTC->MODE2.READREQ.reg &= ~RTC_READREQ_RCONT; // disable continuously mode RTC->MODE2.CTRL.reg = tmp_reg; RtcWaitSynchronize(); NVIC_EnableIRQ(RTC_IRQn); // enable RTC interrupt NVIC_SetPriority(RTC_IRQn, 0x00); RTC->MODE2.INTENSET.reg |= RTC_MODE2_INTENSET_ALARM0; // enable alarm interrupt RTC->MODE2.Mode2Alarm[0].MASK.bit.SEL = MATCH_OFF; // default alarm match is off (disabled) RtcWaitSynchronize(); // enable RTC RTC->MODE2.CTRL.reg |= RTC_MODE2_CTRL_ENABLE; RtcWaitSynchronize(); // software reset remove RTC->MODE2.CTRL.reg &= ~RTC_MODE2_CTRL_SWRST; RtcWaitSynchronize(); // If desired and valid, restore the time value if (! fResetTime && validTime) { RTC->MODE2.CLOCK.reg = oldTime.reg; RtcWaitSynchronize(); } return true; } const uint16_t CatenaRTC::md[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; CatenaRTC::CalendarTime CatenaRTC::GetTime(void) { CalendarTime result; RTC_MODE2_CLOCK_Type Mode2Clock; RTC->MODE2.READREQ.reg = RTC_READREQ_RREQ; RtcWaitSynchronize(); Mode2Clock.reg = RTC->MODE2.CLOCK.reg; result.Second = Mode2Clock.bit.SECOND; result.Minute = Mode2Clock.bit.MINUTE; result.Hour = Mode2Clock.bit.HOUR; result.Day = Mode2Clock.bit.DAY; result.Month = Mode2Clock.bit.MONTH; result.Year = Mode2Clock.bit.YEAR; return result; } void CatenaRTC::SetAlarm(uint32_t delta) { CalendarTime now = GetTime(); now.Advance(delta); SetAlarm(&now); } void CatenaRTC::SetAlarm(const CalendarTime *pNow) { RTC_MODE2_ALARM_Type Mode2Alarm; Mode2Alarm.reg = 0; Mode2Alarm.bit.SECOND = pNow->Second; Mode2Alarm.bit.MINUTE = pNow->Minute; Mode2Alarm.bit.HOUR = pNow->Hour; Mode2Alarm.bit.DAY = pNow->Day; Mode2Alarm.bit.MONTH = pNow->Month; Mode2Alarm.bit.YEAR = pNow->Year; RTC->MODE2.Mode2Alarm[0].ALARM.reg = Mode2Alarm.reg; RtcWaitSynchronize(); } void CatenaRTC::SleepForAlarm( CatenaRTC::Alarm_Match how, CatenaRTC::SleepMode howSleep ) { uint32_t nWakes; uint32_t nvic_iser_save; uint32_t systick_ctrl_save; // fetch the bits for other than the RC, // and then disable all other sources. nvic_iser_save = NVIC->ISER[0] & ~(1 << RTC_IRQn); NVIC->ICER[0] = nvic_iser_save; // fetch the current state of SysTick, then // disable interrupts. systick_ctrl_save = SysTick->CTRL; SysTick->CTRL = systick_ctrl_save & ~SysTick_CTRL_ENABLE_Msk; // turn off alarms, just in case, so we can safely init. RTC->MODE2.Mode2Alarm[0].MASK.bit.SEL = 0x00; RtcWaitSynchronize(); this->m_Alarm = false; gs_pAlarm = &this->m_Alarm; RTC->MODE2.Mode2Alarm[0].MASK.bit.SEL = how; RtcWaitSynchronize(); /* we may want to try deep sleep, maybe not */ nWakes = 0; switch (howSleep) { default: case SleepMode::IdleCpu: while (! m_Alarm) { ++nWakes; PM->SLEEP.bit.IDLE = PM_SLEEP_IDLE_CPU_Val; SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; __WFI(); } break; case SleepMode::IdleCpuAhb: while (! m_Alarm) { ++nWakes; PM->SLEEP.bit.IDLE = PM_SLEEP_IDLE_AHB_Val; SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; __WFI(); } break; case SleepMode::IdleCpuAhbApb: while (! m_Alarm) { ++nWakes; PM->SLEEP.bit.IDLE = PM_SLEEP_IDLE_APB_Val; SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk; __WFI(); } break; case SleepMode::DeepSleep: while (! m_Alarm) { ++nWakes; // Entering standby mode when connected // via the native USB port causes issues. SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; __WFI(); } break; } RTC->MODE2.Mode2Alarm[0].MASK.bit.SEL = 0x00; RtcWaitSynchronize(); uint32_t systick_ctrl_post = SysTick->CTRL; uint32_t nvic_iser_post = NVIC->ISER[0]; // restore the ISER bits. SysTick->CTRL = systick_ctrl_save; NVIC->ISER[0] = nvic_iser_save; #if 0 if (/* nWakes > 1 && */ Serial) { Serial.print("Alarm! "); Serial.print(nWakes-1); Serial.print(" extra wakeups. NVIC_ISER: saved="); Serial.print(nvic_iser_save, HEX); Serial.print(" current="); Serial.print(nvic_iser_post, HEX); Serial.print(" SysTick.CTRL: saved ="); Serial.print(systick_ctrl_save, HEX); Serial.print(" current="); Serial.println(systick_ctrl_post, HEX); Serial.print("PORT_DIR="); Serial.print(PORT->Group[0].DIR.reg, HEX); Serial.print(" PORT_IN="); Serial.print(PORT->Group[0].IN.reg, HEX); uint32_t uIoEnables, uIoPullupEn, uIoPMuxEn; uIoEnables = uIoPullupEn = uIoPMuxEn = 0; for (uint32_t i = 0; i < 32; ++i) { uIoEnables |= (PORT->Group[0].PINCFG[i].bit.INEN << i); uIoPullupEn |= (PORT->Group[0].PINCFG[i].bit.PULLEN << i); uIoPMuxEn |= (PORT->Group[0].PINCFG[i].bit.PMUXEN << i); } Serial.print(" PORT_INEN="); Serial.print(uIoEnables, HEX); Serial.print(" PORT_PULLEN="); Serial.print(uIoPullupEn, HEX); Serial.print(" PORT_PMUXEN="); Serial.print(uIoPMuxEn, HEX); Serial.println(""); } #endif } /* || assumes that we're only advancing by a day or so -- anything more || than a day is treated as a day. */ bool CatenaRTC::CalendarTime::Advance( uint32_t delta ) { uint32_t d; bool result; result = true; if (delta > 86400) // everyone knows that one day is 86400 secs, { // right? delta = 86400; result = false; } d = delta % 60; delta /= 60; Second += d; if (Second > 59) { delta += Second / 60; Second %= 60; } if (delta == 0) return result; d = delta % 60; delta /= 60; Minute += d; if (Minute > 59) { delta += Minute / 60; Minute %= 60; } if (delta == 0) return result; d = delta % 24; delta /= 24; Hour += d; if (Hour > 23) { delta += Hour / 24; Hour %= 24; } if (delta == 0) return result; uint8_t leapYear = (Year & 0x3) ? 0 : 1; uint8_t firstDay = CatenaRTC::md[Month - 1]; uint8_t lastDay = CatenaRTC::md[Month]; if (leapYear) { if (Month >= 2) { ++lastDay; if (Month >= 3) ++firstDay; } } // now we just propagate carry ++Day; if (Day <= lastDay) return result; Day = 1; ++Month; if (Month <= 12) return result; Month = 1; ++Year; return result; } #endif // ARDUINO_ARCH_SAMD
mghgroup/Glide-Browser
ash/clipboard/clipboard_history_helper_unittest.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/clipboard/clipboard_history_helper.h" #include <string> #include <unordered_map> #include "base/optional.h" #include "base/pickle.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/icu_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard_data.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "ui/base/clipboard/custom_data_helper.h" #include "ui/gfx/image/image_unittest_util.h" namespace ash { namespace clipboard { namespace helper { namespace { // ClipboardDataBuilder -------------------------------------------------------- class ClipboardDataBuilder { public: ClipboardDataBuilder() = default; ClipboardDataBuilder(const ClipboardDataBuilder&) = delete; ClipboardDataBuilder& operator=(const ClipboardDataBuilder&) = delete; ~ClipboardDataBuilder() = default; ui::ClipboardData Build() const { ui::ClipboardData data; if (text_.has_value()) data.set_text(text_.value()); if (markup_.has_value()) data.set_markup_data(markup_.value()); if (rtf_.has_value()) data.SetRTFData(rtf_.value()); if (bookmark_title_.has_value()) data.set_bookmark_title(bookmark_title_.value()); if (bitmap_.has_value()) data.SetBitmapData(bitmap_.value()); if (custom_format_.has_value() && custom_data_.has_value()) data.SetCustomData(custom_format_.value(), custom_data_.value()); if (web_smart_paste_.has_value()) data.set_web_smart_paste(web_smart_paste_.value()); return data; } ClipboardDataBuilder& SetText(const std::string& text) { text_ = text; return *this; } ClipboardDataBuilder& ClearText() { text_ = base::nullopt; return *this; } ClipboardDataBuilder& SetMarkup(const std::string& markup) { markup_ = markup; return *this; } ClipboardDataBuilder& ClearMarkup() { markup_ = base::nullopt; return *this; } ClipboardDataBuilder& SetRtf(const std::string& rtf) { rtf_ = rtf; return *this; } ClipboardDataBuilder& ClearRtf() { rtf_ = base::nullopt; return *this; } ClipboardDataBuilder& SetBookmarkTitle(const std::string& bookmark_title) { bookmark_title_ = bookmark_title; return *this; } ClipboardDataBuilder& ClearBookmarkTitle() { bookmark_title_ = base::nullopt; return *this; } ClipboardDataBuilder& SetBitmap(const SkBitmap& bitmap) { bitmap_ = bitmap; return *this; } ClipboardDataBuilder& ClearBitmap() { bitmap_ = base::nullopt; return *this; } ClipboardDataBuilder& SetCustomData(const std::string& custom_format, const std::string& custom_data) { custom_format_ = custom_format; custom_data_ = custom_data; return *this; } ClipboardDataBuilder& ClearCustomData() { custom_format_ = base::nullopt; custom_data_ = base::nullopt; return *this; } ClipboardDataBuilder& SetFileSystemData( std::initializer_list<std::string>&& source_list) { constexpr char kFileSystemSourcesType[] = "fs/sources"; base::Pickle custom_data; ui::WriteCustomDataToPickle( std::unordered_map<base::string16, base::string16>( {{base::UTF8ToUTF16(kFileSystemSourcesType), base::UTF8ToUTF16(base::JoinString(source_list, "\n"))}}), &custom_data); return SetCustomData( ui::ClipboardFormatType::GetWebCustomDataType().GetName(), std::string(static_cast<const char*>(custom_data.data()), custom_data.size())); } ClipboardDataBuilder& SetWebSmartPaste(bool web_smart_paste) { web_smart_paste_ = web_smart_paste; return *this; } ClipboardDataBuilder& ClearWebSmartPaste() { web_smart_paste_ = base::nullopt; return *this; } private: base::Optional<std::string> text_; base::Optional<std::string> markup_; base::Optional<std::string> rtf_; base::Optional<std::string> bookmark_title_; base::Optional<SkBitmap> bitmap_; base::Optional<std::string> custom_format_; base::Optional<std::string> custom_data_; base::Optional<bool> web_smart_paste_; }; } // namespace // Tests ----------------------------------------------------------------------- using ClipboardHistoryHelperTest = testing::Test; TEST_F(ClipboardHistoryHelperTest, GetLabel) { base::test::ScopedRestoreICUDefaultLocale locale("en_US"); // Populate a builder with all the data formats that we expect to handle. ClipboardDataBuilder builder; builder.SetText("Text") .SetMarkup("Markup") .SetRtf("Rtf") .SetBookmarkTitle("Bookmark Title") .SetBitmap(gfx::test::CreateBitmap(10, 10)) .SetCustomData("Custom Format", "Custom Data") .SetWebSmartPaste(true); // Bitmap data always take precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("Image")); builder.ClearBitmap(); // In the absence of bitmap data, text data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("Text")); builder.ClearText(); // In the absence of text data, HTML data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("Markup")); builder.ClearMarkup(); // In the absence of HTML data, RTF data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("RTF Content")); builder.ClearRtf(); // In the absence of RTF data, bookmark data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("Bookmark Title")); builder.ClearBookmarkTitle(); // In the absence of bookmark data, web smart paste data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("Web Smart Paste Content")); builder.ClearWebSmartPaste(); // In the absence of web smart paste data, custom data takes precedence. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("<Custom Data>")); builder.SetFileSystemData( {"/path/to/My%20File.txt", "/path/to/My%20Other%20File.txt"}); // We specially treat custom file system data to show a list of file names. EXPECT_EQ(GetLabel(builder.Build()), base::UTF8ToUTF16("My File.txt, My Other File.txt")); } } // namespace helper } // namespace clipboard } // namespace ash
mghgroup/Glide-Browser
tools/perf/core/results_processor/processor.py
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Implements the interface of the results_processor module. Provides functions to process intermediate results, and the entry point to the standalone version of Results Processor. """ from __future__ import print_function import datetime import gzip import json import logging import os import posixpath import random import re import shutil import time from py_utils import cloud_storage from core.results_processor import command_line from core.results_processor import compute_metrics from core.results_processor import formatters from core.results_processor import util from core.tbmv3 import trace_processor from tracing.trace_data import trace_data from tracing.value.diagnostics import all_diagnostics from tracing.value.diagnostics import generic_set from tracing.value.diagnostics import reserved_infos from tracing.value import histogram from tracing.value import histogram_set from tracing.value import legacy_unit_info TEST_RESULTS = '_test_results.jsonl' DIAGNOSTICS_NAME = 'diagnostics.json' MEASUREMENTS_NAME = 'measurements.json' CONVERTED_JSON_SUFFIX = '_converted.json' FORMATS_WITH_METRICS = ['csv', 'histograms', 'html'] def ProcessResults(options): """Process intermediate results and produce the requested outputs. This function takes the intermediate results generated by Telemetry after running benchmarks (including artifacts such as traces, etc.), and processes them as requested by the result processing options. Args: options: An options object with values parsed from the command line and after any adjustments from ProcessOptions were applied. """ if not getattr(options, 'output_formats', None): return 0 test_results = _LoadTestResults(options.intermediate_dir) if not test_results: # TODO(crbug.com/981349): Make sure that no one is expecting Results # Processor to output results in the case of empty input # and make this an error. logging.warning('No test results to process.') test_suite_start = (test_results[0]['startTime'] if test_results and 'startTime' in test_results[0] else datetime.datetime.utcnow().isoformat() + 'Z') run_identifier = RunIdentifier(options.results_label, test_suite_start) should_compute_metrics = any( fmt in FORMATS_WITH_METRICS for fmt in options.output_formats) begin_time = time.time() util.ApplyInParallel( lambda result: ProcessTestResult( test_result=result, upload_bucket=options.upload_bucket, results_label=options.results_label, run_identifier=run_identifier, test_suite_start=test_suite_start, should_compute_metrics=should_compute_metrics, max_num_values=options.max_values_per_test_case, test_path_format=options.test_path_format, trace_processor_path=options.trace_processor_path, enable_tbmv3=options.experimental_tbmv3_metrics, fetch_power_profile=options.fetch_power_profile), test_results, on_failure=util.SetUnexpectedFailure, ) processing_duration = time.time() - begin_time _AmortizeProcessingDuration(processing_duration, test_results) if should_compute_metrics: histogram_dicts = ExtractHistograms(test_results) for output_format in options.output_formats: logging.info('Processing format: %s', output_format) formatter = formatters.FORMATTERS[output_format] if output_format in FORMATS_WITH_METRICS: output_file = formatter.ProcessHistogramDicts(histogram_dicts, options) else: output_file = formatter.ProcessIntermediateResults(test_results, options) print('View results at file://', output_file, sep='') return GenerateExitCode(test_results) def _AmortizeProcessingDuration(processing_duration, test_results): test_results_count = len(test_results) if test_results_count: per_story_cost = processing_duration / len(test_results) logging.info( 'Amortizing processing cost to story runtimes: %.2fs per story.', per_story_cost) for result in test_results: if 'runDuration' in result and result['runDuration']: current_duration = float(result['runDuration'].rstrip('s')) new_story_cost = current_duration + per_story_cost result['runDuration'] = unicode(str(new_story_cost) + 's', 'utf-8') def ProcessTestResult(test_result, upload_bucket, results_label, run_identifier, test_suite_start, should_compute_metrics, max_num_values, test_path_format, trace_processor_path, enable_tbmv3, fetch_power_profile): ConvertProtoTraces(test_result, trace_processor_path) AggregateTBMv2Traces(test_result) if enable_tbmv3: AggregateTBMv3Traces(test_result) if upload_bucket is not None: UploadArtifacts(test_result, upload_bucket, run_identifier) if should_compute_metrics: test_result['_histograms'] = histogram_set.HistogramSet() compute_metrics.ComputeTBMv2Metrics(test_result) if enable_tbmv3: compute_metrics.ComputeTBMv3Metrics(test_result, trace_processor_path, fetch_power_profile) ExtractMeasurements(test_result) num_values = len(test_result['_histograms']) if max_num_values is not None and num_values > max_num_values: logging.error('%s produced %d values, but only %d are allowed.', test_result['testPath'], num_values, max_num_values) util.SetUnexpectedFailure(test_result) del test_result['_histograms'] else: AddDiagnosticsToHistograms(test_result, test_suite_start, results_label, test_path_format) def ExtractHistograms(test_results): histograms = histogram_set.HistogramSet() for result in test_results: if '_histograms' in result: histograms.Merge(result['_histograms']) histograms.DeduplicateDiagnostics() return histograms.AsDicts() def GenerateExitCode(test_results): """Generate an exit code as expected by callers. Returns: 1 if there were failed tests. 111 if all tests were skipped. (See crbug.com/1019139#c8 for details). 0 otherwise. """ if any(r['status'] == 'FAIL' for r in test_results): return 1 if all(r['status'] == 'SKIP' for r in test_results): return 111 return 0 def _LoadTestResults(intermediate_dir): """Load intermediate results from a file into a list of test results.""" intermediate_file = os.path.join(intermediate_dir, TEST_RESULTS) test_results = [] with open(intermediate_file) as f: for line in f: record = json.loads(line) if 'testResult' in record: test_results.append(record['testResult']) return test_results def _IsProtoTrace(trace_name): return (trace_name.startswith('trace/') and (trace_name.endswith('.pb') or trace_name.endswith('.pb.gz'))) def _IsTBMv2Trace(trace_name): return (trace_name.startswith('trace/') and (trace_name.endswith('.json') or trace_name.endswith('.json.gz') or trace_name.endswith('.txt') or trace_name.endswith('.txt.gz'))) def _BuildOutputPath(input_files, output_name): """Build a path to a file in the same folder as input_files.""" return os.path.join( os.path.dirname(os.path.commonprefix(input_files)), output_name ) def ConvertProtoTraces(test_result, trace_processor_path): """Convert proto traces to json. For a test result with proto traces, converts them to json using trace_processor and stores the json trace as a separate artifact. """ artifacts = test_result.get('outputArtifacts', {}) proto_traces = [name for name in artifacts if _IsProtoTrace(name)] # TODO(crbug.com/990304): After implementation of TBMv3-style clock sync, # it will be possible to convert the aggregated proto trace, not # individual ones. for proto_trace_name in proto_traces: proto_file_path = artifacts[proto_trace_name]['filePath'] json_file_path = (os.path.splitext(proto_file_path)[0] + CONVERTED_JSON_SUFFIX) json_trace_name = (posixpath.splitext(proto_trace_name)[0] + CONVERTED_JSON_SUFFIX) trace_processor.ConvertProtoTraceToJson( trace_processor_path, proto_file_path, json_file_path) artifacts[json_trace_name] = { 'filePath': json_file_path, 'contentType': 'application/json', } logging.info('%s: Proto trace converted. Source: %s. Destination: %s.', test_result['testPath'], proto_file_path, json_file_path) def AggregateTBMv2Traces(test_result): """Replace individual non-proto traces with an aggregate HTML trace. For a test result with non-proto traces, generates an aggregate HTML trace. Removes all entries for individual traces and adds one entry for the aggregate one. """ artifacts = test_result.get('outputArtifacts', {}) traces = [name for name in artifacts if _IsTBMv2Trace(name)] if traces: trace_files = [artifacts[name]['filePath'] for name in traces] html_path = _BuildOutputPath(trace_files, compute_metrics.HTML_TRACE_NAME) trace_data.SerializeAsHtml(trace_files, html_path) artifacts[compute_metrics.HTML_TRACE_NAME] = { 'filePath': html_path, 'contentType': 'text/html', } logging.info('%s: TBMv2 traces aggregated. Sources: %s. Destination: %s.', test_result['testPath'], trace_files, html_path) for name in traces: del artifacts[name] def AggregateTBMv3Traces(test_result): """Replace individual proto traces with an aggregate one. For a test result with proto traces, concatenates them into one file. Removes all entries for individual traces and adds one entry for the aggregate one. """ artifacts = test_result.get('outputArtifacts', {}) traces = [name for name in artifacts if _IsProtoTrace(name)] if traces: proto_files = [artifacts[name]['filePath'] for name in traces] concatenated_path = _BuildOutputPath( proto_files, compute_metrics.CONCATENATED_PROTO_NAME) with open(concatenated_path, 'w') as concatenated_trace: for trace_file in proto_files: if trace_file.endswith('.pb.gz'): with gzip.open(trace_file, 'rb') as f: shutil.copyfileobj(f, concatenated_trace) else: with open(trace_file, 'rb') as f: shutil.copyfileobj(f, concatenated_trace) artifacts[compute_metrics.CONCATENATED_PROTO_NAME] = { 'filePath': concatenated_path, 'contentType': 'application/x-protobuf', } logging.info('%s: Proto traces aggregated. Sources: %s. Destination: %s.', test_result['testPath'], proto_files, concatenated_path) for name in traces: del artifacts[name] def RunIdentifier(results_label, test_suite_start): """Construct an identifier for the current script run""" if results_label: identifier_parts = [re.sub(r'\W+', '_', results_label)] else: identifier_parts = [] # Time is rounded to seconds and delimiters are removed. # The first 19 chars of the string match 'YYYY-MM-DDTHH:MM:SS'. identifier_parts.append(re.sub(r'\W+', '', test_suite_start[:19])) identifier_parts.append(str(random.randint(1, 1e5))) return '_'.join(identifier_parts) def UploadArtifacts(test_result, upload_bucket, run_identifier): """Upload all artifacts to cloud. For a test run, uploads all its artifacts to cloud and sets fetchUrl and viewUrl fields in intermediate_results. """ artifacts = test_result.get('outputArtifacts', {}) for name, artifact in artifacts.iteritems(): # TODO(crbug.com/981349): Think of a more general way to # specify which artifacts deserve uploading. if name in [DIAGNOSTICS_NAME, MEASUREMENTS_NAME]: continue retry_identifier = 'retry_%s' % test_result.get('resultId', '0') remote_name = '/'.join( [run_identifier, test_result['testPath'], retry_identifier, name]) urlsafe_remote_name = re.sub(r'[^A-Za-z0-9/.-]+', '_', remote_name) cloud_filepath = cloud_storage.Upload( upload_bucket, urlsafe_remote_name, artifact['filePath']) # Per crbug.com/1033755 some services require fetchUrl. artifact['fetchUrl'] = cloud_filepath.fetch_url artifact['viewUrl'] = cloud_filepath.view_url logging.info('%s: Uploaded %s to %s', test_result['testPath'], name, artifact['viewUrl']) def GetTraceUrl(test_result): artifacts = test_result.get('outputArtifacts', {}) trace_artifact = artifacts.get(compute_metrics.HTML_TRACE_NAME, {}) if 'viewUrl' in trace_artifact: return trace_artifact['viewUrl'] elif 'filePath' in trace_artifact: return 'file://' + trace_artifact['filePath'] else: return None def AddDiagnosticsToHistograms(test_result, test_suite_start, results_label, test_path_format): """Add diagnostics to all histograms of a test result. Reads diagnostics from the test artifact and adds them to all histograms. Also sets additional diagnostics based on test result metadata. This overwrites the corresponding diagnostics previously set by e.g. run_metrics. """ artifacts = test_result.get('outputArtifacts', {}) if DIAGNOSTICS_NAME in artifacts: with open(artifacts[DIAGNOSTICS_NAME]['filePath']) as f: diagnostics = json.load(f)['diagnostics'] for name, diag in diagnostics.items(): # For now, we only support GenericSet diagnostics that are serialized # as lists of values. assert isinstance(diag, list) test_result['_histograms'].AddSharedDiagnosticToAllHistograms( name, generic_set.GenericSet(diag)) del artifacts[DIAGNOSTICS_NAME] test_suite, test_case = util.SplitTestPath(test_result, test_path_format) if 'startTime' in test_result: test_start_ms = util.IsoTimestampToEpoch(test_result['startTime']) * 1e3 else: test_start_ms = None test_suite_start_ms = util.IsoTimestampToEpoch(test_suite_start) * 1e3 story_tags = [tag['value'] for tag in test_result.get('tags', []) if tag['key'] == 'story_tag'] result_id = int(test_result.get('resultId', 0)) trace_url = GetTraceUrl(test_result) additional_diagnostics = [ (reserved_infos.BENCHMARKS, test_suite), (reserved_infos.BENCHMARK_START, test_suite_start_ms), (reserved_infos.LABELS, results_label), (reserved_infos.STORIES, test_case), (reserved_infos.STORYSET_REPEATS, result_id), (reserved_infos.STORY_TAGS, story_tags), (reserved_infos.TRACE_START, test_start_ms), (reserved_infos.TRACE_URLS, trace_url), ] for name, value in _WrapDiagnostics(additional_diagnostics): test_result['_histograms'].AddSharedDiagnosticToAllHistograms(name, value) def MeasurementToHistogram(name, measurement): unit = measurement['unit'] samples = measurement['samples'] description = measurement.get('description') if unit in legacy_unit_info.LEGACY_UNIT_INFO: info = legacy_unit_info.LEGACY_UNIT_INFO[unit] unit = info.name samples = [s * info.conversion_factor for s in samples] if unit not in histogram.UNIT_NAMES: raise ValueError('Unknown unit: %s' % unit) return histogram.Histogram.Create(name, unit, samples, description=description) def _WrapDiagnostics(info_value_pairs): """Wrap diagnostic values in corresponding Diagnostics classes. Args: info_value_pairs: any iterable of pairs (info, value), where info is one of reserved infos defined in tracing.value.diagnostics.reserved_infos, and value can be any json-serializable object. Returns: An iterator over pairs (diagnostic name, diagnostic value). """ for info, value in info_value_pairs: if value is None or value == []: continue if info.type == 'GenericSet' and not isinstance(value, list): value = [value] diag_class = all_diagnostics.GetDiagnosticClassForName(info.type) yield info.name, diag_class(value) def ExtractMeasurements(test_result): """Add ad-hoc measurements to histogram dicts""" artifacts = test_result.get('outputArtifacts', {}) if MEASUREMENTS_NAME in artifacts: with open(artifacts[MEASUREMENTS_NAME]['filePath']) as f: measurements = json.load(f)['measurements'] for name, measurement in measurements.iteritems(): test_result['_histograms'].AddHistogram( MeasurementToHistogram(name, measurement)) del artifacts[MEASUREMENTS_NAME] def main(args=None): """Entry point for the standalone version of the results_processor script.""" parser = command_line.ArgumentParser(standalone=True) options = parser.parse_args(args) command_line.ProcessOptions(options) return ProcessResults(options)
yavuzahmet1/Patika
PatikaJava102Lambda/src/Main.java
<reponame>yavuzahmet1/Patika public class Main { public static void main(String[] args) { // Java 8'den öncesi Runnable runnable1 = new Runnable() { @Override public void run() { System.out.println("Before 1.8"); } }; runnable1.run(); // Java 8'den sonrası Runnable runnable2 = () -> System.out.println("1.8"); runnable2.run(); } }
vusec/firestarter
llvm/passes/hybinline/HybInlinePass.cpp
<gh_stars>1-10 /* Description: * * This pass makes preparations towards enabling hybrid transactions * and recovery mechanisms on target application. * After HybPrepPass marks library calls, call instructions and local variables of * functions with necessary metadata, this pass inlines the call instructions to * the clones in its container functions. * * Author : <NAME> * Date : 12-March-2018 * Vrije Universiteit, Amsterdam. */ #if LLVM_VERSION >= 37 #define DEBUG_TYPE "hybinline" #endif #include <hybinline/HybInlinePass.h> using namespace llvm; static cl::opt<std::string> clonePrefixOpt("hybry-clone-prefix", cl::desc("Specify the clone prefix used (in bbclone pass)."), cl::init("bbclone."), cl::NotHidden, cl::ValueRequired); static cl::list<std::string> skipSectionsOpt("hybinline-skip-sections", cl::desc("Specify comma separated names of sections to skip."), cl::ZeroOrMore, cl::CommaSeparated, cl::NotHidden, cl::ValueRequired); PASS_COMMON_INIT_ONCE(); bool HybInlinePass::runOnModule(Module &M) { if (0 != HybInlinePass::PassRunCount) { errs() << "hybry: Not rerunning this module pass.\n"; return false; } this->M = &M; DEBUG(errs() << "HybInline Pass to inline cloned function variants.\n"); this->clonePrefixStr = clonePrefixOpt; this->skipSections = &skipSectionsOpt; // bbclone already assigns IDs to libcall insts in every cloned function Module::FunctionListType &funcs = M.getFunctionList(); for (Module::iterator it = funcs.begin(); it != funcs.end(); it++) { Function *F = &(*it); if (F->isIntrinsic() || F->isDeclaration()) { continue; } if (std::string::npos != F->getName().find(clonePrefixStr)) { continue; // skip the cloned functions } if (PassUtil::isInAnyOfSections(*F, skipSectionsOpt)) { continue; } DEBUG(errs() << "Inlining calls to cloned variants in function: " << F->getName() << "\n"); inlineCloneCalls(*F); } return true; } void HybInlinePass::getAnalysisUsage(AnalysisUsage &AU) const { } char HybInlinePass::ID = 0; RegisterPass<HybInlinePass> HI("hybinline", "Inliner pass for Hybrid Tx and Recovery");
touxiong88/92_mediatek
packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/protocol/sip/SipTransactionContext.java
/******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010 France Telecom S.A. * * 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.orangelabs.rcs.core.ims.protocol.sip; import javax.sip.Transaction; import javax.sip.header.CallIdHeader; import javax.sip.message.Message; /** * SIP transaction context object composed of a request and of the corresponding * response. The Transaction context is used for waiting responses of requests * and also for waiting an ACK message (special case). * * @author <NAME> */ public class SipTransactionContext extends Object { /** * Transaction */ private Transaction transaction; /** * Received message */ private SipMessage recvMsg = null; /** * Constructor * * @param transaction SIP transaction */ public SipTransactionContext(Transaction transaction) { this.transaction = transaction; } /** * Get the SIP transaction * * @return Transaction */ public Transaction getTransaction() { return transaction; } /** * Get the SIP message that has been received * * @return SIP message */ public SipMessage getMessageReceived() { return recvMsg; } /** * Determine if a timeout has occured * * @return Returns True if there is a timeout else returns False */ public boolean isTimeout() { return (recvMsg == null); } /** * Determine if the received message is a SIP response * * @return Returns True if it's a SIP response else returns False */ public boolean isSipResponse() { if (recvMsg != null) { return (recvMsg instanceof SipResponse); } else { return false; } } /** * Determine if the received message is an intermediate response * * @return Returns True if it's an intermediate response else returns False */ public boolean isSipIntermediateResponse() { int code = getStatusCode(); return (code < 200); } /** * Determine if the received message is a successfull response * * @return Returns True if it's a successfull response else returns False */ public boolean isSipSuccessfullResponse() { int code = getStatusCode(); return ((code >= 200) && (code < 300)); } /** * Determine if the received message is a SIP ACK * * @return Returns True if it's a SIP ACK else returns False */ public boolean isSipAck() { if (recvMsg != null) { SipRequest req = (SipRequest)recvMsg; if (req.getMethod().equals("ACK")) { return true; } else { return false; } } else { return false; } } /** * Get the SIP response that has been received * * @return SIP response or null if it's not a response (e.g. ACK message) */ public SipResponse getSipResponse() { if (isSipResponse()) { return (SipResponse)recvMsg; } else { return null; } } /** * Get the status code of the received SIP response * * @return Returns a status code or -1 if it's not a SIP response (e.g. ACK message) */ public int getStatusCode() { int ret = -1; if (isSipResponse()) { SipResponse resp = (SipResponse)recvMsg; ret = resp.getStatusCode(); } return ret; } /** * Get the reason phrase of the received SIP response * * @return Returns a reason phrase or null if it's not a SIP response (e.g. ACK message) */ public String getReasonPhrase() { String ret = null; SipResponse resp = getSipResponse(); if (resp != null) { ret = resp.getReasonPhrase(); } return ret; } /** * Wait the response of a request until a timeout occurs * * @param timeout Timeout value */ public void waitResponse(int timeout) { try { if (recvMsg != null) { // Response already received, no need to wait return; } synchronized(this) { super.wait(timeout * 1000); } } catch(InterruptedException e) { // Thread has been interrupted recvMsg = null; } } /** * A response has been received (SIP response or ACK or any other SIP message) * * @param msg SIP message object */ public void responseReceived(SipMessage msg) { synchronized(this) { recvMsg = msg; super.notify(); } } /** * Reset transaction context */ public void resetContext() { synchronized (this) { recvMsg = null; super.notify(); } } /** * Get the transaction context ID associated a SIP message * * @param msg SIP message * @return Transaction context ID */ public static String getTransactionContextId(SipMessage msg) { return getTransactionContextId(msg.getStackMessage()); } /** * Get the transaction context ID associated a SIP message * * @param msg SIP message * @return Transaction context ID */ public static String getTransactionContextId(Message msg) { CallIdHeader header = (CallIdHeader)msg.getHeader(CallIdHeader.NAME); return header.getCallId(); } }
CesarAdan1/DaCodes-Pokemon
webpack.config.prod.js
const merge = require('webpack-merge') const TerserPlugin = require('terser-webpack-plugin'); const baseConfig = require('./webpack.config.base') module.exports = merge(baseConfig, { mode: 'production', optimization: { minimizer: [ new TerserPlugin({ cache: true, parallel: true, sourceMap: true, terserOptions: { // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions } }), ], noEmitOnErrors: true, namedChunks: true } })
rochakchauhan/commcare-hq
corehq/apps/userreports/expressions/__init__.py
import copy from django.conf import settings from django.utils.module_loading import import_string from corehq.apps.userreports.expressions.factory import ExpressionFactory def get_custom_ucr_expressions(): custom_ucr_expressions = copy.copy(settings.CUSTOM_UCR_EXPRESSIONS) for path_to_expression_lists in settings.CUSTOM_UCR_EXPRESSION_LISTS: custom_ucr_expressions += import_string(path_to_expression_lists) return custom_ucr_expressions # Bootstrap plugin expressions for type_name, factory_function_path in get_custom_ucr_expressions(): ExpressionFactory.register(type_name, import_string(factory_function_path))
leocamelo/tic_tac_toe_c
src/grid.c
#include <stdlib.h> #include <string.h> #include <math.h> #include "grid.h" static char *grid_row_separator(void) { int i; char *separator = malloc(sizeof(char) * (BOARD_SIZE * 4 + 2)); strcpy(separator, "\n"); for (i = 0; i < BOARD_SIZE; i++) { if (i) strcat(separator, "+"); strcat(separator, "==="); } strcat(separator, "\n"); return separator; } char *grid_from_board(Board *board) { int i, j; char fallback_cell = '1'; char *separator = grid_row_separator(); char *grid = malloc(sizeof(char) * ( 8 * pow(BOARD_SIZE, 2) - 5 * BOARD_SIZE + 2 )); strcpy(grid, "\n"); for (i = 0; i < BOARD_SIZE; i++) { if (i) strcat(grid, separator); for (j = 0; j < BOARD_SIZE; j++) { strcat(grid, j ? " | " : " "); if (cell_is_empty(board->cells[i][j])) { strcat(grid, (char[2]){fallback_cell, '\0'}); } else { strcat(grid, cell_to_string(board->cells[i][j])); } fallback_cell++; } } strcat(grid, "\n"); free(separator); return grid; }
gx19970920/pikascript
src/boot/demo06-pikamain/main.c
<reponame>gx19970920/pikascript /* this demo shows the usage of method */ #include "pikaScript.h" #include <stdio.h> void obj_runWithInfo(PikaObj *self, char *cmd) { printf(">>> %s\r\n", cmd); obj_run(self, cmd); } int main() { PikaObj *pikaMain = pikaScriptInit(); /* user input buff */ char inputBuff[256] = {0}; /* run the script with check*/ printf(">>> "); while (1) { /* get user input */ fgets(inputBuff, sizeof(inputBuff), stdin); /* run PikaScript and get res */ Args *resArgs = obj_runDirect(pikaMain, inputBuff); /* get system output of PikaScript*/ char *sysOut = args_getSysOut(resArgs); if (!strEqu("", sysOut)) { /* print out the system output */ printf("%s\r\n", sysOut); } printf(">>> "); /* deinit the res */ args_deinit(resArgs); } }
dsofowote/KW-Tool
keywordTool/pubfiles/src/code/justrunlah/126825/default.js
integration.meta = { 'sectionID' : '126825', 'siteName' : 'Just Run Lah - Smartphone - (Asia)', 'platform' : 'smartphone' }; integration.testParams = { 'mobile_resolution' : [375] }; integration.flaggedTests = []; integration.params = { 'mf_siteId' : '707097', 'plr_FluidAnchor': true, 'plr_Fluid': true, 'plr_Responsive' : true, 'plr_ShowCloseButton' : true, 'plr_ContentType': 'PAGESKINEXPRESS', 'plr_UseFullVersion': true, 'plr_UseCreativeSettings': true, 'plr_HideElementsByID' : '', 'plr_HideElementsByClass' : '' }; integration.on('adCallResult', function(e) { if (e.data.hasSkin) { $("body").addClass("inskinLoaded"); var stylesCSS = '<style type="text/css">'; stylesCSS += '.inskinLoaded #wonderplugincarousel-1 > div.amazingcarousel-list-container{width: 100%;}'; stylesCSS += '.inskinLoaded #td-outer-wrap > div.td-transition-content-and-menu.td-content-wrap > div.td-main-content-wrap.td-main-page-wrap > div > div{width: 100%;}'; stylesCSS += '.inskinLoaded #td-outer-wrap > div.td-transition-content-and-menu.td-content-wrap > div.td-main-content-wrap.td-main-page-wrap > div > div{left: 0;}'; stylesCSS += '.inskinLoaded .td-social-pinterest, .inskinLoaded .td-social-sharing-buttons{margin-right: -3px;}'; stylesCSS += '.inskinLoaded .amazingcarousel-list-wrapper{width: 100% !important;}'; stylesCSS += '.inskinLoaded #td-outer-wrap{overflow: hidden;}'; stylesCSS += '.inskinLoaded .amazingcarousel-list-container{width: 100% !important;}'; stylesCSS += '.inskinLoaded .amazingcarousel-list-container *{width: 100% !important;}'; stylesCSS += '</style>' $('head').append(stylesCSS); } }); integration.on('layoutChange', function(e) { integration.custom.FrameSideRight = e.data.plr_FrameSideRight; $("head").append("<style>.inskinLoaded .td-affix{max-width: calc(100% - " + integration.custom.FrameSideRight + "px);}</style>"); cwidth = ($(window).width() - integration.custom.FrameSideRight) $("head").append("<style>.inskinLoaded .vc_row.wpb_row.td-pb-row.td-homepage-full-row{max-width: " + cwidth + "px; padding-right: 10px !important;}</style>"); $("head").append("<style>.inskinLoaded .vc_row.wpb_row.td-pb-row{max-width: " + cwidth + "px; padding-right: 10px !important;}</style>"); integration.custom.PageSkinTopPanel = e.data.plr_FrameTop; $("head").append("<style>.inskinLoaded #td-mobile-nav{top: " + integration.custom.PageSkinTopPanel + "px;}</style>"); }); integration.on('adClose', function(e) { $('body').removeClass('inskinLoaded'); });