repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Fuzzwah/django-allauth
allauth/socialaccount/providers/twentythreeandme_provider/urls.py
<filename>allauth/socialaccount/providers/twentythreeandme_provider/urls.py from allauth.socialaccount.providers.oauth2_provider.urls import default_urlpatterns from .provider import TwentyThreeAndMeProvider urlpatterns = default_urlpatterns(TwentyThreeAndMeProvider)
jphickey/osal
src/ut-stubs/osapi-utstub-fpu.c
<gh_stars>0 /* * Copyright (c) 2004-2018, United States government as represented by the * administrator of the National Aeronautics Space Administration. * All rights reserved. This software was created at NASA Glenn * Research Center pursuant to government contracts. * * This is governed by the NASA Open Source Agreement and may be used, * distributed and modified only according to the terms of that agreement. */ /** * \file osapi_stubs.c * * Created on: Feb 25, 2015 * Author: <EMAIL> * * Stub implementations for the functions defined in the OSAL API * * The stub implementation can be used for unit testing applications built * on top of OSAL. The stubs do not do any real function, but allow * the return code to be crafted such that error paths in the application * can be executed. */ #include "utstub-helpers.h" #ifndef OSAL_OMIT_DEPRECATED /***************************************************************************** * * Stub function for OS_FPUExcAttachHandler() * *****************************************************************************/ int32 OS_FPUExcAttachHandler (uint32 ExceptionNumber, osal_task_entry ExceptionHandler , int32 parameter) { int32 status; status = UT_DEFAULT_IMPL_ARGS(OS_FPUExcAttachHandler, ExceptionNumber, ExceptionHandler, parameter); return status; } /***************************************************************************** * * Stub function for OS_FPUExcEnable() * *****************************************************************************/ int32 OS_FPUExcEnable (int32 ExceptionNumber) { int32 status; status = UT_DEFAULT_IMPL(OS_FPUExcEnable); return status; } /***************************************************************************** * * Stub function for OS_FPUExcDisable() * *****************************************************************************/ int32 OS_FPUExcDisable (int32 ExceptionNumber) { int32 status; status = UT_DEFAULT_IMPL(OS_FPUExcDisable); return status; } /***************************************************************************** * * Stub function for OS_FPUExcSetMask() * *****************************************************************************/ int32 OS_FPUExcSetMask (uint32 mask) { int32 status; status = UT_DEFAULT_IMPL(OS_FPUExcSetMask); return status; } /***************************************************************************** * * Stub function for OS_FPUExcGetMask() * *****************************************************************************/ int32 OS_FPUExcGetMask (uint32 *mask) { int32 status; status = UT_DEFAULT_IMPL(OS_FPUExcGetMask); *mask = 0x55aa55aa; return status; } #endif /* OSAL_OMIT_DEPRECATED */
CodingZeal/sufia
sufia-models/app/models/concerns/sufia/user.rb
<filename>sufia-models/app/models/concerns/sufia/user.rb module Sufia::User extend ActiveSupport::Concern included do # Adds acts_as_messageable for user mailboxes include Mailboxer::Models::Messageable # Connects this user object to Blacklight's Bookmarks and Folders. include Blacklight::User include Hydra::User delegate :can?, :cannot?, to: :ability # set this up as a messageable object acts_as_messageable # Users should be able to follow things acts_as_follower # Users should be followable acts_as_followable mount_uploader :avatar, AvatarUploader, mount_on: :avatar_file_name validates_with AvatarValidator has_many :trophies end # Format the json for select2 which requires just an id and a field called text. # If we need an alternate format we should probably look at a json template gem def as_json(opts = nil) {id: user_key, text: display_name ? "#{display_name} (#{user_key})" : user_key} end def email_address return self.email end def name return self.display_name.titleize || self.user_key rescue self.user_key end # Redefine this for more intuitive keys in Redis def to_param # hack because rails doesn't like periods in urls. user_key.gsub(/\./, '-dot-') end def trophy_files trophies.map do |t| ::GenericFile.load_instance_from_solr(Sufia::Noid.namespaceize(t.generic_file_id)) end end # method needed for messaging def mailboxer_email(obj=nil) return nil end # The basic groups method, override or will fallback to Sufia::Ldap::User def groups @groups ||= self.group_list ? self.group_list.split(";?;") : [] end def ability @ability ||= ::Ability.new(self) end module ClassMethods def permitted_attributes [:email, :login, :display_name, :address, :admin_area, :department, :title, :office, :chat_id, :website, :affiliation, :telephone, :avatar, :group_list, :groups_last_update, :facebook_handle, :twitter_handle, :googleplus_handle, :linkedin_handle] end def current Thread.current[:user] end def current=(user) Thread.current[:user] = user end # Override this method if you aren't using email/password def audituser User.find_by_user_key(audituser_key) || User.create!(Devise.authentication_keys.first => audituser_key, password: Devise.friendly_token[0,20]) end # Override this method if you aren't using email as the userkey def audituser_key '<EMAIL>' end # Override this method if you aren't using email/password def batchuser User.find_by_user_key(batchuser_key) || User.create!(Devise.authentication_keys.first => batchuser_key, password: Devise.friendly_token[0,20]) end # Override this method if you aren't using email as the userkey def batchuser_key '<EMAIL>' end def from_url_component(component) User.find_by_user_key(component.gsub(/-dot-/, '.')) end end end
SMCodesprivate/BotGame
Functions/createRichEmbed.js
<reponame>SMCodesprivate/BotGame const Discord = require("discord.js"); // const mongoose = require("mongoose"); async function createRichEmbed(title, color, fieldQuantidade, fieldsMandados, images, thumbnail) { created = new Discord.RichEmbed() .setTitle(title) .addBlankField(); if(color[0] == true) { created.setColor("#"+color[1]); } if(thumbnail && thumbnail[0] == true) { created.setThumbnail(thumbnail[1]); } x = 0; while(x <= fieldQuantidade) { teste = fieldsMandados[x]; created.addField(teste[0], teste[1], teste[2]); x = x + 1; } if(images[0] == true) { created.setTimestamp().setFooter(images[1], images[2]); } return created; } module.exports = createRichEmbed;
Zoe0123/Android-Application
Game/app/src/main/java/com/example/game/Model/BallBumpingGame/Visible.java
package com.example.game.Model.BallBumpingGame; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Typeface; import com.example.game.View.BallBumpingGame.PlayFieldView; abstract class Visible { Paint paintText; // row coordinate of visible objects int row; // column coordinate of visible objects int col; // appearance String appearance; private float characterWidth, characterHeight; Visible() { paintText = new Paint(); paintText.setTextSize(36); paintText.setTypeface(Typeface.DEFAULT_BOLD); characterWidth = paintText.measureText("W"); characterHeight = -paintText.ascent() + paintText.descent(); } Visible(int row, int col) { this.row = row; this.col = col; paintText = new Paint(); paintText.setTextSize(36); paintText.setTypeface(Typeface.DEFAULT_BOLD); characterWidth = paintText.measureText("W"); characterHeight = -paintText.ascent() + paintText.descent(); } /** * Draws the given string in the given graphics context at the given cursor location. * * @param canvas the graphics context in which to draw the string. * @param s the string to draw. * @param x the horizontal coordinate of the string's cursor location. * @param y the vertical coordinate of the string's cursor location. */ void drawString(Canvas canvas, String s, int x, int y) { canvas.drawText(s, x * PlayFieldView.charWidth, y * PlayFieldView.charHeight, paintText); } /** * Draws this item. * * @param canvas the graphics context in which to draw this item. */ public void draw(Canvas canvas) { int y_offset = 0; for (String string : appearance.split("\n")) { drawString(canvas, string, row, col + y_offset); y_offset += 1; } } public int getRow() { return row; } public int getCol() { return col; } }
IHTSDO/snow-owl
dependencies/org.eclipse.emf.cdo.server/src/org/eclipse/emf/cdo/server/IRepositoryFactory.java
<reponame>IHTSDO/snow-owl<filename>dependencies/org.eclipse.emf.cdo.server/src/org/eclipse/emf/cdo/server/IRepositoryFactory.java /* * Copyright (c) 2004 - 2012 <NAME> (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> - initial API and implementation */ package org.eclipse.emf.cdo.server; /** * Creates CDO {@link IRepository repositories}. * * @author <NAME> * @apiviz.uses {@link IRepository} - - creates */ public interface IRepositoryFactory { /** * @since 2.0 */ public static final String PRODUCT_GROUP = "org.eclipse.emf.cdo.server.repositories"; //$NON-NLS-1$ public String getRepositoryType(); public IRepository createRepository(); }
MrAwesomeRocks/caelus-cml
external/pgsl-2.3/src/eigen/hermv.c
/* eigen/hermv.c * * Copyright (C) 2001, 2007 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include <stdlib.h> #include "gsl_math.h" #include "gsl_vector.h" #include "gsl_matrix.h" #include "gsl_complex_math.h" #include "gsl_linalg.h" #include "gsl_eigen.h" /* Compute eigenvalues/eigenvectors of complex hermitian matrix using reduction to real symmetric tridiagonal form, followed by QR iteration with implicit shifts. See Golub & Van Loan, "Matrix Computations" (3rd ed), Section 8.3 */ #include "qrstep.c" gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n) { gsl_eigen_hermv_workspace * w ; if (n == 0) { GSL_ERROR_NULL ("matrix dimension must be positive integer", GSL_EINVAL); } w = (gsl_eigen_hermv_workspace *) malloc (sizeof(gsl_eigen_hermv_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->d = (double *) malloc (n * sizeof (double)); if (w->d == 0) { free (w); GSL_ERROR_NULL ("failed to allocate space for diagonal", GSL_ENOMEM); } w->sd = (double *) malloc (n * sizeof (double)); if (w->sd == 0) { free (w->d); free (w); GSL_ERROR_NULL ("failed to allocate space for subdiagonal", GSL_ENOMEM); } w->tau = (double *) malloc (2 * n * sizeof (double)); if (w->tau == 0) { free (w->sd); free (w->d); free (w); GSL_ERROR_NULL ("failed to allocate space for tau", GSL_ENOMEM); } w->gc = (double *) malloc (n * sizeof (double)); if (w->gc == 0) { free (w->tau); free (w->sd); free (w->d); free (w); GSL_ERROR_NULL ("failed to allocate space for cosines", GSL_ENOMEM); } w->gs = (double *) malloc (n * sizeof (double)); if (w->gs == 0) { free (w->gc); free (w->tau); free (w->sd); free (w->d); free (w); GSL_ERROR_NULL ("failed to allocate space for sines", GSL_ENOMEM); } w->size = n; return w; } void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w) { RETURN_IF_NULL (w); free (w->gs); free (w->gc); free (w->tau); free (w->sd); free (w->d); free (w); } int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_hermv_workspace * w) { if (A->size1 != A->size2) { GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR); } else if (eval->size != A->size1) { GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN); } else if (evec->size1 != A->size1 || evec->size2 != A->size1) { GSL_ERROR ("eigenvector matrix must match matrix size", GSL_EBADLEN); } else { const size_t N = A->size1; double *const d = w->d; double *const sd = w->sd; size_t a, b; /* handle special case */ if (N == 1) { gsl_complex A00 = gsl_matrix_complex_get (A, 0, 0); gsl_vector_set (eval, 0, GSL_REAL(A00)); gsl_matrix_complex_set (evec, 0, 0, GSL_COMPLEX_ONE); return GSL_SUCCESS; } /* Transform the matrix into a symmetric tridiagonal form */ { gsl_vector_view d_vec = gsl_vector_view_array (d, N); gsl_vector_view sd_vec = gsl_vector_view_array (sd, N - 1); gsl_vector_complex_view tau_vec = gsl_vector_complex_view_array (w->tau, N-1); gsl_linalg_hermtd_decomp (A, &tau_vec.vector); gsl_linalg_hermtd_unpack (A, &tau_vec.vector, evec, &d_vec.vector, &sd_vec.vector); } /* Make an initial pass through the tridiagonal decomposition to remove off-diagonal elements which are effectively zero */ chop_small_elements (N, d, sd); /* Progressively reduce the matrix until it is diagonal */ b = N - 1; while (b > 0) { if (sd[b - 1] == 0.0 || isnan(sd[b - 1])) { b--; continue; } /* Find the largest unreduced block (a,b) starting from b and working backwards */ a = b - 1; while (a > 0) { if (sd[a - 1] == 0.0) { break; } a--; } { size_t i; const size_t n_block = b - a + 1; double *d_block = d + a; double *sd_block = sd + a; double * const gc = w->gc; double * const gs = w->gs; /* apply QR reduction with implicit deflation to the unreduced block */ qrstep (n_block, d_block, sd_block, gc, gs); /* Apply Givens rotation Gij(c,s) to matrix Q, Q <- Q G */ for (i = 0; i < n_block - 1; i++) { const double c = gc[i], s = gs[i]; size_t k; for (k = 0; k < N; k++) { gsl_complex qki = gsl_matrix_complex_get (evec, k, a + i); gsl_complex qkj = gsl_matrix_complex_get (evec, k, a + i + 1); /* qki <= qki * c - qkj * s */ /* qkj <= qki * s + qkj * c */ gsl_complex x1 = gsl_complex_mul_real(qki, c); gsl_complex y1 = gsl_complex_mul_real(qkj, -s); gsl_complex x2 = gsl_complex_mul_real(qki, s); gsl_complex y2 = gsl_complex_mul_real(qkj, c); gsl_complex qqki = gsl_complex_add(x1, y1); gsl_complex qqkj = gsl_complex_add(x2, y2); gsl_matrix_complex_set (evec, k, a + i, qqki); gsl_matrix_complex_set (evec, k, a + i + 1, qqkj); } } /* remove any small off-diagonal elements */ chop_small_elements (n_block, d_block, sd_block); } } { gsl_vector_view d_vec = gsl_vector_view_array (d, N); gsl_vector_memcpy (eval, &d_vec.vector); } return GSL_SUCCESS; } }
yangzaiqiong/cs-summary-reflection
src/main/java/cn/edu/jxnu/tooffer/T7.java
package cn.edu.jxnu.tooffer; /** * 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。 * n<=39 */ public class T7 { public int Fibonacci(int n) { if (n <= 0) { return 0; } if (n == 1 || n == 2) { return 1; } return this.Fibonacci(n - 1) + this.Fibonacci(n - 2); } public int Fibonacci2(int n) { if (n <= 0) { return 0; } if (n == 1 || n == 2) { return 1; } int a = 1; int b = 1; int c = 0; for (int i = 3; i <= n; i++) { c = a + b; a = b; b = c; } return c; } public int Fibonacci3(int n, int acc1, int acc2) { if (n == 0) return 0; if (n == 1) return acc2; else return Fibonacci3(n - 1, acc2, acc1 + acc2); } public static void main(String[] args) { T7 t7 = new T7(); for (int i = 1; i < 40; i++) { System.out.println(t7.Fibonacci2(i)); } } }
Tarpelite/OJ_research
code/746.c
#include <stdio.h> #include <stdlib.h> int main() { int m,n,f=1,h=1,i; scanf("%d%d",&m,&n); for(f=1,i=m;i>(m-n);i--) f*=i; for(h=1;n>0;n--) h*=n; printf("%d",f/h); return 0; }
nithin2889/Hibernate5
074-HibernateDynamicFetchingViaJPAEntityGraphExample/src/main/java/com/javabotanist/client/HibernateDynamicFetchingUsingJPASubGraphClientTest.java
package com.javabotanist.client; import java.util.Collections; import java.util.List; import org.hibernate.Session; import com.javabotanist.entities.Department; import com.javabotanist.entities.Employee; import com.javabotanist.entities.Project; import com.javabotanist.util.HibernateUtil; public class HibernateDynamicFetchingUsingJPASubGraphClientTest { public static void main(String[] args) { try (Session session = HibernateUtil.getSessionFactory().openSession()) { Long projectId = 1L; Project project = session.find(Project.class, projectId, Collections.singletonMap("javax.persistence.fetchgraph", session.getEntityGraph("project.employees"))); System.out.println("::Project Details::"); System.out.println(project.getId()+"\t"+project.getProjectName()); System.out.println("::Employee Details::"); List<Employee> employees = project.getEmployees(); for (Employee employee : employees) { System.out.println(employee.getId()+"\t"+employee.getEmployeeName()+"\t"+ employee.getUserName()+"\t"+employee.getAccessLevel()); Department department = employee.getDepartment(); System.out.println("::Employee's Department Details::"); if(department != null) { System.out.println(department.getId()+"\t"+department.getDeptName()); } } } catch (Exception e) { e.printStackTrace(); } } }
vickyi/data-algorithms-book
src/main/java/org/dataalgorithms/chap29/combinesmallfilesbyhadoop/CustomCFIF256MB.java
package org.dataalgorithms.chap29.combinesmallfilesbyhadoop; /** * A custom file input format, which combines/merges smaller * files into big files controlled by MAX_SPLIT_SIZE_256MB * * @author <NAME> * */ public class CustomCFIF256MB extends CustomCFIF { final static long MAX_SPLIT_SIZE_256MB = 268435456; // 256 MB = 256*1024*1024 public CustomCFIF256MB() { super(); setMaxSplitSize(MAX_SPLIT_SIZE_256MB); } }
KaiserLancelot/Computer-Theory-Learning
CSAPP/chapter02/homework/hw_2_95.c
// // Created by kaiser on 18-10-11. // #include "../config.h" float_bits float_half(float_bits f) { unsigned frac = f & 0x7fffff; unsigned exp = (f >> 23) & 0xff; unsigned sign = f >> 31; if (exp == 0xff) return f; int carry = ((frac & 0x3) == 0x3); if (exp == 0) { frac >>= 1; frac += carry; } else if (exp == 1) { exp = 0; frac = (frac >> 1) | (1 << 22); frac += carry; } else { exp -= 1; } return (sign << 31) | (exp << 23) | frac; }
alex94puchades/node-jsapi
lib/filters/paginateOffset.js
var common = require('./common'); var _ = require('lodash'); function paginate() { return common.createFilter(queryParser, function(transaction, req, type, params) { var pageOffset = params.offset, pageLimit = params.limit; transaction.subscribe(type, 'query', function(resource, query) { query.skip(pageOffset).limit(pageLimit); }); transaction.subscribe(type, 'end', function(resource) { var selfLink = req.originalUrl; var response = transaction.response; var count = response.meta['count']; response.links['first'] = common.modifyQuery(selfLink, { page: { offset: 0 }}); response.links['last'] = common.modifyQuery(selfLink, { page: { offset: count - pageLimit }}); if (pageOffset > 0) { response.links['prev'] = common.modifyQuery(selfLink, { page: { offset: (pageOffset - pageLimit < 0) ? 0 : pageOffset - pageLimit }}); } if ((pageOffset + pageLimit) < count) { response.links['next'] = common.modifyQuery(selfLink, { page: { offset: pageOffset + pageLimit }}); } }); }); } function queryParser(req, callback) { var param = req.query['page']; var pageInfo = _.pick(param, 'offset', 'limit'); if (pageInfo.offset !== undefined && pageInfo.limit !== undefined) callback(pageInfo); } module.exports = paginate;
uwx/refinedstorage
src/main/java/com/raoulvdberge/refinedstorage/network/MessageGridItemUpdate.java
<gh_stars>0 package com.raoulvdberge.refinedstorage.network; import com.raoulvdberge.refinedstorage.api.autocrafting.ICraftingPattern; import com.raoulvdberge.refinedstorage.api.network.INetwork; import com.raoulvdberge.refinedstorage.api.storage.IStorageTracker; import com.raoulvdberge.refinedstorage.gui.GuiBase; import com.raoulvdberge.refinedstorage.gui.grid.GuiGrid; import com.raoulvdberge.refinedstorage.gui.grid.stack.GridStackItem; import com.raoulvdberge.refinedstorage.gui.grid.stack.IGridStack; import com.raoulvdberge.refinedstorage.util.StackUtils; import io.netty.buffer.ByteBuf; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; public class MessageGridItemUpdate implements IMessage, IMessageHandler<MessageGridItemUpdate, IMessage> { private Consumer<ByteBuf> sendHandler; private boolean canCraft; private List<IGridStack> stacks = new ArrayList<>(); public MessageGridItemUpdate() { } public MessageGridItemUpdate(INetwork network, boolean canCraft) { this.sendHandler = (buf) -> { int size = network.getItemStorageCache().getList().getStacks().size(); for (ICraftingPattern pattern : network.getCraftingManager().getPatterns()) { size += pattern.getOutputs().stream().filter(Objects::nonNull).count(); } buf.writeInt(size); for (ItemStack stack : network.getItemStorageCache().getList().getStacks()) { StackUtils.writeItemStack(buf, stack, network, false); IStorageTracker.IStorageTrackerEntry entry = network.getItemStorageTracker().get(stack); buf.writeBoolean(entry != null); if (entry != null) { buf.writeLong(entry.getTime()); ByteBufUtils.writeUTF8String(buf, entry.getName()); } } for (ICraftingPattern pattern : network.getCraftingManager().getPatterns()) { for (ItemStack output : pattern.getOutputs()) { if (output != null) { StackUtils.writeItemStack(buf, output, network, true); IStorageTracker.IStorageTrackerEntry entry = network.getItemStorageTracker().get(output); buf.writeBoolean(entry != null); if (entry != null) { buf.writeLong(entry.getTime()); ByteBufUtils.writeUTF8String(buf, entry.getName()); } } } } }; this.canCraft = canCraft; } public MessageGridItemUpdate(Consumer<ByteBuf> sendHandler, boolean canCraft) { this.sendHandler = sendHandler; this.canCraft = canCraft; } @Override public void fromBytes(ByteBuf buf) { canCraft = buf.readBoolean(); int items = buf.readInt(); for (int i = 0; i < items; ++i) { this.stacks.add(new GridStackItem(buf)); } } @Override public void toBytes(ByteBuf buf) { buf.writeBoolean(canCraft); sendHandler.accept(buf); } @Override public IMessage onMessage(MessageGridItemUpdate message, MessageContext ctx) { GuiBase.executeLater(GuiGrid.class, grid -> { grid.getView().setCanCraft(message.canCraft); grid.getView().setStacks(message.stacks); grid.getView().sort(); }); return null; } }
OpenSextant/giscore
src/main/java/org/opensextant/giscore/events/Feature.java
/**************************************************************************************** * Feature.java * * Created: Jan 26, 2009 * * @author DRAND * * (C) Copyright MITRE Corporation 2009 * * The program is provided "as is" without any warranty express or implied, including * the warranty of non-infringement and the implied warranties of merchantibility and * fitness for a particular purpose. The Copyright owner will not be liable for any * damages suffered by you as a result of using the Program. In no event will the * Copyright owner be liable for any special, indirect or consequential damages or * lost profits even if the Copyright owner has been advised of the possibility of * their occurrence. * ***************************************************************************************/ package org.opensextant.giscore.events; import edu.umd.cs.findbugs.annotations.CheckForNull; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.builder.EqualsBuilder; import org.opensextant.geodesy.Geodetic2DBounds; import org.opensextant.giscore.IStreamVisitor; import org.opensextant.giscore.geometry.Geometry; import org.opensextant.giscore.input.kml.IKml; import org.opensextant.giscore.utils.SimpleObjectInputStream; import org.opensextant.giscore.utils.SimpleObjectOutputStream; /** * We've seen the start of a feature set. The start of the feature set has all * the available information about the feature. After the start of a feature, * there will be zero or more geometry objects seen. * * @author DRAND */ public class Feature extends Common { private static final long serialVersionUID = 1L; private StyleSelector style; private Geometry geometry; /** * Constructs a basic Feature that may contain a geometry and a style. * In KML this represents a Placemark. */ public Feature() { // } /* * (non-Javadoc) * * @see org.mitre.giscore.events.BaseStart#readData(org.mitre.giscore.utils. * SimpleObjectInputStream) */ @Override public void readData(SimpleObjectInputStream in) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { super.readData(in); style = (StyleSelector) in.readObject(); geometry = (Geometry) in.readObject(); } /* * (non-Javadoc) * * @see * org.mitre.giscore.events.BaseStart#writeData(java.io.DataOutputStream) */ @Override public void writeData(SimpleObjectOutputStream out) throws IOException { super.writeData(out); out.writeObject(style); out.writeObject(geometry); } /** * @return the geometry */ @CheckForNull public Geometry getGeometry() { return geometry; } /** * @param geometry * the geometry to set */ public void setGeometry(Geometry geometry) { this.geometry = geometry; } /** * Get inline Style or StyleMap for this Feature * @return the Style or StyleMap */ @CheckForNull public StyleSelector getStyle() { return style; } /** * Set inline style to use with this Feature. * @param style */ public void setStyle(StyleSelector style) { this.style = style; } /** * @return the type */ public String getType() { return IKml.PLACEMARK; } public void accept(IStreamVisitor visitor) { visitor.visit(this); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((geometry == null) ? 0 : geometry.hashCode()); result = prime * result + ((endTime == null) ? 0 : endTime.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Feature other = (Feature) obj; if (geometry == null) { if (other.geometry != null) return false; } else if (other.geometry == null || !geometry.equals(other.geometry)) return false; return true; } /** * The approximately equals method checks most of the fields for equality with * the exception of the geometry which is checked for equivalence not equality. * Snippet, visibility, and elements, and extendedElements fields are not tested. * * @param other Other feature to compare against * @return true if this and other are approximately equal */ public boolean approximatelyEquals(Feature other) { EqualsBuilder eb = new EqualsBuilder(); boolean fields = eb.append(description, other.description) .append(name, other.name) .append(schema, other.schema) .append(styleUrl, other.styleUrl) .append(endTime, other.endTime) .append(startTime, other.startTime) .append(style, other.style).isEquals(); if (!fields) return false; // Check extended data Set<SimpleField> maximalSet = new HashSet<SimpleField>(); maximalSet.addAll(extendedData.keySet()); maximalSet.addAll(other.extendedData.keySet()); for (SimpleField fieldname : maximalSet) { Object val1 = extendedData.get(fieldname); Object val2 = other.extendedData.get(fieldname); if (val1 != null && val2 != null) { if (val1 instanceof Number && val2 instanceof Number) { double dv1 = ((Number) val1).doubleValue(); double dv2 = ((Number) val2).doubleValue(); return Math.abs(dv1 - dv2) < 1e-5; } else { return val1.equals(val2); } } else if (val1 != null || val2 != null) { //System.out.println("unequal name="+fieldname.getName() + " items: this=" + val1 + " " + val2); // one value is null and other is non-null return false; } } // Check geometry for equivalence if (geometry == null && other.geometry == null) { return true; } else if (geometry != null && other.geometry != null) { Geodetic2DBounds bb1 = geometry.getBoundingBox(); Geodetic2DBounds bb2 = other.geometry.getBoundingBox(); if (bb1 == null) { if (bb2 != null) return false; } else if (!bb1.equals(bb2, 1e-5)) return false; return geometry.getNumPoints() == other.geometry.getNumPoints(); } else { return false; } } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder b = new StringBuilder(super.toString()); if (geometry != null) { b.append(" geometry class=["); b.append(geometry.getClass().getName()); b.append("]\n\t center=").append(geometry.getCenter()); b.append('\n'); } if (style != null) { b.append(" style class="); b.append(style.getClass().getName()); if (style.getId() != null) b.append(" id=").append(style.getId()); b.append('\n'); } return b.toString(); } }
sunchang0124/sunchang0124.github.io
node_modules/sparqlalgebrajs/lib/util.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const algebra_1 = require("./algebra"); const factory_1 = require("./factory"); class Util { /** * Flattens an array of arrays to an array. * @param arr - Array of arrays */ static flatten(arr) { return Array.prototype.concat(...arr).filter(x => x); } /** * Detects all in-scope variables. * In practice this means iterating through the entire algebra tree, finding all variables, * and stopping when a project function is found. * @param {Operation} op - Input algebra tree. * @returns {Variable[]} - List of unique in-scope variables. */ static inScopeVariables(op) { const variables = []; function addVariable(v) { if (!variables.find(v2 => v.value === v2.value)) variables.push(v); } // https://www.w3.org/TR/sparql11-query/#variableScope Util.recurseOperation(op, { [algebra_1.types.EXPRESSION]: (op) => { let expr = op; if (expr.expressionType === 'aggregate' && expr.variable) { let agg = expr; addVariable(agg.variable); } return true; }, [algebra_1.types.EXTEND]: (op) => { let extend = op; addVariable(extend.variable); return true; }, [algebra_1.types.GRAPH]: (op) => { let graph = op; if (graph.name.termType === 'Variable') addVariable(graph.name); return true; }, [algebra_1.types.GROUP]: (op) => { let group = op; group.variables.forEach(addVariable); return true; }, [algebra_1.types.PATH]: (op) => { let path = op; if (path.subject.termType === 'Variable') addVariable(path.subject); if (path.object.termType === 'Variable') addVariable(path.object); if (path.graph.termType === 'Variable') addVariable(path.graph); return true; }, [algebra_1.types.PATTERN]: (op) => { let pattern = op; if (pattern.subject.termType === 'Variable') addVariable(pattern.subject); if (pattern.predicate.termType === 'Variable') addVariable(pattern.predicate); if (pattern.object.termType === 'Variable') addVariable(pattern.object); if (pattern.graph.termType === 'Variable') addVariable(pattern.graph); return true; }, [algebra_1.types.PROJECT]: (op) => { let project = op; project.variables.forEach(addVariable); return false; }, [algebra_1.types.SERVICE]: (op) => { let service = op; if (service.name.termType === 'Variable') addVariable(service.name); return true; }, [algebra_1.types.VALUES]: (op) => { let values = op; values.variables.forEach(addVariable); return true; }, }); return variables; } /** * Recurses through the given algebra tree * A map of callback functions can be provided for individual Operation types to gather data. * The return value of those callbacks should indicate whether recursion should be applied or not. * Making modifications will change the original input object. * @param {Operation} op - The Operation to recurse on. * @param { [type: string]: (op: Operation) => boolean } callbacks - A map of required callback Operations. */ static recurseOperation(op, callbacks) { let result = op; let doRecursion = true; if (callbacks[op.type]) doRecursion = callbacks[op.type](op); if (!doRecursion) return; let recurseOp = (op) => Util.recurseOperation(op, callbacks); switch (result.type) { case algebra_1.types.ALT: const alt = result; recurseOp(alt.left); recurseOp(alt.right); break; case algebra_1.types.ASK: const ask = result; recurseOp(ask.input); break; case algebra_1.types.BGP: const bgp = result; bgp.patterns.forEach(recurseOp); break; case algebra_1.types.CONSTRUCT: const construct = result; recurseOp(construct.input); construct.template.map(recurseOp); break; case algebra_1.types.DESCRIBE: const describe = result; recurseOp(describe.input); break; case algebra_1.types.DISTINCT: const distinct = result; recurseOp(distinct.input); break; case algebra_1.types.EXPRESSION: const expr = result; if (expr.expressionType === algebra_1.expressionTypes.EXISTENCE) { const exist = expr; recurseOp(exist.input); } break; case algebra_1.types.EXTEND: const extend = result; recurseOp(extend.input); recurseOp(extend.expression); break; case algebra_1.types.FILTER: const filter = result; recurseOp(filter.input); recurseOp(filter.expression); break; case algebra_1.types.FROM: const from = result; recurseOp(from.input); break; case algebra_1.types.GRAPH: const graph = result; recurseOp(graph.input); break; case algebra_1.types.GROUP: const group = result; recurseOp(group.input); group.aggregates.forEach(recurseOp); break; case algebra_1.types.INV: const inv = result; recurseOp(inv.path); break; case algebra_1.types.JOIN: const join = result; recurseOp(join.left); recurseOp(join.right); break; case algebra_1.types.LEFT_JOIN: const leftJoin = result; recurseOp(leftJoin.left); recurseOp(leftJoin.right); if (leftJoin.expression) recurseOp(leftJoin.expression); break; case algebra_1.types.LINK: break; case algebra_1.types.MINUS: const minus = result; recurseOp(minus.left); recurseOp(minus.right); break; case algebra_1.types.NPS: break; case algebra_1.types.ONE_OR_MORE_PATH: const oom = result; recurseOp(oom.path); break; case algebra_1.types.ORDER_BY: const order = result; recurseOp(order.input); order.expressions.forEach(recurseOp); break; case algebra_1.types.PATH: const path = result; recurseOp(path.predicate); break; case algebra_1.types.PATTERN: break; case algebra_1.types.PROJECT: const project = result; recurseOp(project.input); break; case algebra_1.types.REDUCED: const reduced = result; recurseOp(reduced.input); break; case algebra_1.types.SEQ: const seq = result; recurseOp(seq.left); recurseOp(seq.right); break; case algebra_1.types.SERVICE: const service = result; recurseOp(service.input); break; case algebra_1.types.SLICE: const slice = result; recurseOp(slice.input); break; case algebra_1.types.UNION: const union = result; recurseOp(union.left); recurseOp(union.right); break; case algebra_1.types.VALUES: break; case algebra_1.types.ZERO_OR_MORE_PATH: const zom = result; recurseOp(zom.path); break; case algebra_1.types.ZERO_OR_ONE_PATH: const zoo = result; recurseOp(zoo.path); break; // UPDATE operations case algebra_1.types.COMPOSITE_UPDATE: const cu = result; cu.updates.forEach(update => recurseOp(update)); break; case algebra_1.types.DELETE_INSERT: const di = result; if (di.delete) di.delete.forEach(pattern => recurseOp(pattern)); if (di.insert) di.insert.forEach(pattern => recurseOp(pattern)); if (di.where) recurseOp(di.where); break; // all of these only have graph IDs as values case algebra_1.types.LOAD: break; case algebra_1.types.CLEAR: break; case algebra_1.types.CREATE: break; case algebra_1.types.DROP: break; case algebra_1.types.ADD: break; case algebra_1.types.MOVE: break; case algebra_1.types.COPY: break; default: throw new Error('Unknown Operation type ' + result.type); } } /** * Creates a deep copy of the given Operation. * Creates shallow copies of the non-Operation values. * A map of callback functions can be provided for individual Operation types * to specifically modify the given objects before triggering recursion. * The return value of those callbacks should indicate whether recursion should be applied to this returned object or not. * @param {Operation} op - The Operation to recurse on. * @param { [type: string]: (op: Operation, factory: Factory) => RecurseResult } callbacks - A map of required callback Operations. * @param {Factory} factory - Factory used to create new Operations. Will use default factory if none is provided. * @returns {Operation} - The copied result. */ static mapOperation(op, callbacks, factory) { let result = op; let doRecursion = true; factory = factory || new factory_1.default(); if (callbacks[op.type]) ({ result, recurse: doRecursion } = callbacks[op.type](op, factory)); if (!doRecursion) return result; let mapOp = (op) => Util.mapOperation(op, callbacks, factory); switch (result.type) { case algebra_1.types.ALT: const alt = result; return factory.createAlt(mapOp(alt.left), mapOp(alt.right)); case algebra_1.types.ASK: const ask = result; return factory.createAsk(mapOp(ask.input)); case algebra_1.types.BGP: const bgp = result; return factory.createBgp(bgp.patterns.map(mapOp)); case algebra_1.types.CONSTRUCT: const construct = result; return factory.createConstruct(mapOp(construct.input), construct.template.map(mapOp)); case algebra_1.types.DESCRIBE: const describe = result; return factory.createDescribe(mapOp(describe.input), describe.terms); case algebra_1.types.DISTINCT: const distinct = result; return factory.createDistinct(mapOp(distinct.input)); case algebra_1.types.EXPRESSION: const expr = result; return Util.mapExpression(expr, callbacks, factory); case algebra_1.types.EXTEND: const extend = result; return factory.createExtend(mapOp(extend.input), extend.variable, mapOp(extend.expression)); case algebra_1.types.FILTER: const filter = result; return factory.createFilter(mapOp(filter.input), mapOp(filter.expression)); case algebra_1.types.FROM: const from = result; return factory.createFrom(mapOp(from.input), [].concat(from.default), [].concat(from.named)); case algebra_1.types.GRAPH: const graph = result; return factory.createGraph(mapOp(graph.input), graph.name); case algebra_1.types.GROUP: const group = result; return factory.createGroup(mapOp(group.input), [].concat(group.variables), group.aggregates.map(mapOp)); case algebra_1.types.INV: const inv = result; return factory.createInv(mapOp(inv.path)); case algebra_1.types.JOIN: const join = result; return factory.createJoin(mapOp(join.left), mapOp(join.right)); case algebra_1.types.LEFT_JOIN: const leftJoin = result; return factory.createLeftJoin(mapOp(leftJoin.left), mapOp(leftJoin.right), leftJoin.expression ? mapOp(leftJoin.expression) : undefined); case algebra_1.types.LINK: const link = result; return factory.createLink(link.iri); case algebra_1.types.MINUS: const minus = result; return factory.createMinus(mapOp(minus.left), mapOp(minus.right)); case algebra_1.types.NPS: const nps = result; return factory.createNps([].concat(nps.iris)); case algebra_1.types.ONE_OR_MORE_PATH: const oom = result; return factory.createOneOrMorePath(mapOp(oom.path)); case algebra_1.types.ORDER_BY: const order = result; return factory.createOrderBy(mapOp(order.input), order.expressions.map(mapOp)); case algebra_1.types.PATH: const path = result; return factory.createPath(path.subject, mapOp(path.predicate), path.object, path.graph); case algebra_1.types.PATTERN: const pattern = result; return factory.createPattern(pattern.subject, pattern.predicate, pattern.object, pattern.graph); case algebra_1.types.PROJECT: const project = result; return factory.createProject(mapOp(project.input), [].concat(project.variables)); case algebra_1.types.REDUCED: const reduced = result; return factory.createReduced(mapOp(reduced.input)); case algebra_1.types.SEQ: const seq = result; return factory.createSeq(mapOp(seq.left), mapOp(seq.right)); case algebra_1.types.SERVICE: const service = result; return factory.createService(mapOp(service.input), service.name, service.silent); case algebra_1.types.SLICE: const slice = result; return factory.createSlice(mapOp(slice.input), slice.start, slice.length); case algebra_1.types.UNION: const union = result; return factory.createUnion(mapOp(union.left), mapOp(union.right)); case algebra_1.types.VALUES: const values = result; return factory.createValues([].concat(values.variables), values.bindings.map(b => Object.assign({}, b))); case algebra_1.types.ZERO_OR_MORE_PATH: const zom = result; return factory.createZeroOrMorePath(mapOp(zom.path)); case algebra_1.types.ZERO_OR_ONE_PATH: const zoo = result; return factory.createZeroOrOnePath(mapOp(zoo.path)); // UPDATE operations case algebra_1.types.COMPOSITE_UPDATE: const cu = result; return factory.createCompositeUpdate(cu.updates.map(mapOp)); case algebra_1.types.DELETE_INSERT: const di = result; return factory.createDeleteInsert(di.delete ? di.delete.map(mapOp) : undefined, di.insert ? di.insert.map(mapOp) : undefined, di.where ? mapOp(di.where) : undefined); case algebra_1.types.LOAD: const load = result; return factory.createLoad(load.source, load.destination, load.silent); case algebra_1.types.CLEAR: const clear = result; return factory.createClear(clear.source, clear.silent); case algebra_1.types.CREATE: const create = result; return factory.createCreate(create.source, create.silent); case algebra_1.types.DROP: const drop = result; return factory.createDrop(drop.source, drop.silent); case algebra_1.types.ADD: const add = result; return factory.createAdd(add.source, add.destination); case algebra_1.types.MOVE: const move = result; return factory.createMove(move.source, move.destination); case algebra_1.types.COPY: const copy = result; return factory.createCopy(copy.source, copy.destination); default: throw new Error('Unknown Operation type ' + result.type); } } /** * Similar to the {@link mapOperation} function but specifically for expressions. * Both functions call each other while copying. * Should not be called directly since it does not execute the callbacks, these happen in {@link mapOperation}. * @param {Expression} expr - The Operation to recurse on. * @param { [type: string]: (op: Operation, factory: Factory) => RecurseResult } callbacks - A map of required callback Operations. * @param {Factory} factory - Factory used to create new Operations. Will use default factory if none is provided. * @returns {Operation} - The copied result. */ static mapExpression(expr, callbacks, factory) { let recurse = (op) => Util.mapOperation(op, callbacks, factory); switch (expr.expressionType) { case algebra_1.expressionTypes.AGGREGATE: if (expr.variable) { const bound = expr; return factory.createBoundAggregate(bound.variable, bound.aggregator, recurse(bound.expression), bound.distinct, bound.separator); } const aggregate = expr; return factory.createAggregateExpression(aggregate.aggregator, recurse(aggregate.expression), aggregate.distinct, aggregate.separator); case algebra_1.expressionTypes.EXISTENCE: const exist = expr; return factory.createExistenceExpression(exist.not, recurse(exist.input)); case algebra_1.expressionTypes.NAMED: const named = expr; return factory.createNamedExpression(named.name, named.args.map(recurse)); case algebra_1.expressionTypes.OPERATOR: const op = expr; return factory.createOperatorExpression(op.operator, op.args.map(recurse)); case algebra_1.expressionTypes.TERM: const term = expr; return factory.createTermExpression(term.term); case algebra_1.expressionTypes.WILDCARD: return factory.createWildcardExpression(); default: throw new Error('Unknown Expression type ' + expr.expressionType); } } static createUniqueVariable(label, variables, dataFactory) { let counter = 0; let labelLoop = label; while (variables[labelLoop]) { labelLoop = label + counter++; } return dataFactory.variable(labelLoop); } // separate terms from wildcard since we handle them differently static isTerm(term) { return term.termType !== undefined && term.termType !== 'Wildcard'; } static isWildcard(term) { return term.termType === 'Wildcard'; } } exports.default = Util; //# sourceMappingURL=util.js.map
nateglims/amazon-freertos
vendors/nxp/boards/lpc54018iotmodule/aws_demos/application_code/nxp_code/board.h
/* * Copyright (c) 2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _BOARD_H_ #define _BOARD_H_ #include "clock_config.h" #include "fsl_common.h" #include "fsl_gpio.h" /******************************************************************************* * Definitions ******************************************************************************/ /*! @brief The board name */ #define BOARD_NAME "CLICKBRD-TREAD" #define BOARD_EXTCLKINRATE (0) /*! @brief The UART to use for debug messages. */ /* TODO: rename UART to USART */ //#define BOARD_DEBUG_UART_TYPE DEBUG_CONSOLE_DEVICE_TYPE_USBCDC #define BOARD_DEBUG_UART_TYPE DEBUG_CONSOLE_DEVICE_TYPE_FLEXCOMM #define BOARD_DEBUG_UART_BASEADDR (uint32_t) USART0 #define BOARD_DEBUG_UART_INSTANCE 0U #define BOARD_DEBUG_UART_CLK_FREQ CLOCK_GetFreq(kCLOCK_Flexcomm0) #define BOARD_DEBUG_UART_CLK_ATTACH kFRO12M_to_FLEXCOMM0 #define BOARD_DEBUG_UART_RST kFC0_RST_SHIFT_RSTn #define BOARD_DEBUG_UART_CLKSRC kCLOCK_Flexcomm0 #define BOARD_UART_IRQ_HANDLER FLEXCOMM0_IRQHandler #define BOARD_UART_IRQ FLEXCOMM0_IRQn /* TODO: obsolete */ #define BOARD_DEBUG_SPI_CLK_FREQ 12000000 #ifndef BOARD_DEBUG_UART_BAUDRATE #define BOARD_DEBUG_UART_BAUDRATE 115200 #endif /* BOARD_DEBUG_UART_BAUDRATE */ /*! @brief The ENET PHY address. */ #define BOARD_ENET0_PHY_ADDRESS (0x00U) /* Phy address of enet port 0. */ #ifndef BOARD_LED1_GPIO #define BOARD_LED1_GPIO GPIO #endif #define BOARD_LED1_GPIO_PORT 3U #ifndef BOARD_LED1_GPIO_PIN #define BOARD_LED1_GPIO_PIN 13U #endif #define BOARD_SDIF_BASEADDR SDIF #define BOARD_SDIF_CLKSRC kCLOCK_SDio #define BOARD_SDIF_CLK_FREQ CLOCK_GetFreq(kCLOCK_SDio) #define BOARD_SDIF_CLK_ATTACH kMCLK_to_SDIO_CLK #define BOARD_SDIF_IRQ SDIO_IRQn #define BOARD_SDIF_CD_GPIO_INIT() \ { \ CLOCK_EnableClock(kCLOCK_Gpio2); \ GPIO_PinInit(BOARD_SD_CARD_DETECT_GPIO, BOARD_SD_CARD_DETECT_PORT, BOARD_SD_CARD_DETECT_PIN, \ &(gpio_pin_config_t){kGPIO_DigitalInput, 0U}); \ } #define BOARD_SDIF_CD_STATUS() \ GPIO_ReadPinInput(BOARD_SD_CARD_DETECT_GPIO, BOARD_SD_CARD_DETECT_PORT, BOARD_SD_CARD_DETECT_PIN) /* Board led color mapping */ #define LOGIC_LED_ON 0U #define LOGIC_LED_OFF 1U #define LED1_INIT(output) \ GPIO_PinInit(BOARD_LED1_GPIO, BOARD_LED1_GPIO_PORT, BOARD_LED1_GPIO_PIN, \ &(gpio_pin_config_t){kGPIO_DigitalOutput, (output)}) /*!< Enable target LED1 */ #define LED1_ON() \ GPIO_PortClear(BOARD_LED1_GPIO, BOARD_LED1_GPIO_PORT, 1U << BOARD_LED1_GPIO_PIN) /*!< Turn on target LED1 */ #define LED1_OFF() \ GPIO_PortSet(BOARD_LED1_GPIO, BOARD_LED1_GPIO_PORT, 1U << BOARD_LED1_GPIO_PIN) /*!< Turn off target LED1 */ #define LED1_TOGGLE() \ GPIO_PortToggle(BOARD_LED1_GPIO, BOARD_LED1_GPIO_PORT, 1U << BOARD_LED1_GPIO_PIN) /*!< Toggle on target LED1 */ #define LED2_INIT(output) \ GPIO_PinInit(BOARD_LED2_GPIO, BOARD_LED2_GPIO_PORT, BOARD_LED2_GPIO_PIN, \ &(gpio_pin_config_t){kGPIO_DigitalOutput, (output)}) /*!< Enable target LED2 */ #define LED2_ON() \ GPIO_PortClear(BOARD_LED2_GPIO, BOARD_LED2_GPIO_PORT, 1U << BOARD_LED2_GPIO_PIN) /*!< Turn on target LED2 */ #define LED2_OFF() \ GPIO_PortSet(BOARD_LED2_GPIO, BOARD_LED2_GPIO_PORT, 1U << BOARD_LED2_GPIO_PIN) /*!< Turn off target LED2 */ #define LED2_TOGGLE() \ GPIO_PortToggle(BOARD_LED2_GPIO, BOARD_LED2_GPIO_PORT, 1U << BOARD_LED2_GPIO_PIN) /*!< Toggle on target LED2 */ #define LED3_INIT(output) \ GPIO_PinInit(BOARD_LED3_GPIO, BOARD_LED3_GPIO_PORT, BOARD_LED3_GPIO_PIN, \ &(gpio_pin_config_t){kGPIO_DigitalOutput, (output)}) /*!< Enable target LED3 */ #define LED3_ON() \ GPIO_PortClear(BOARD_LED3_GPIO, BOARD_LED3_GPIO_PORT, 1U << BOARD_LED3_GPIO_PIN) /*!< Turn on target LED3 */ #define LED3_OFF() \ GPIO_PortSet(BOARD_LED3_GPIO, BOARD_LED3_GPIO_PORT, 1U << BOARD_LED3_GPIO_PIN) /*!< Turn off target LED3 */ #define LED3_TOGGLE() \ GPIO_PortToggle(BOARD_LED3_GPIO, BOARD_LED3_GPIO_PORT, 1U << BOARD_LED3_GPIO_PIN) /*!< Toggle on target LED3 */ #if defined(__cplusplus) extern "C" { #endif /* __cplusplus */ /******************************************************************************* * API ******************************************************************************/ status_t BOARD_InitDebugConsole(void); void BOARD_InitSDRAM(void); #if defined(__cplusplus) } #endif /* __cplusplus */ #endif /* _BOARD_H_ */
kxen42/Learn-Python-Programming-Third-Edition
ch15/train-project/train_schedule/models/event.py
# train-project/train_schedule/models/event.py class Event: """This class implements a callback mechanism for our models. A model can define an event by creating an `Event` instance attribute. Any objects that need to respond to event, can register callbacks using the `bind` method. When the model calls `emit` on the event, the callbacks will be invoked with any arguments passed to the `emit` method. """ def __init__(self): self.callbacks = [] def bind(self, listener): """Bind a callback to the event""" self.callbacks.append(listener) def emit(self, *args, **kwargs): """Emit the event""" for callback in self.callbacks: callback(*args, **kwargs)
RedBrumbler/virtuoso-codegen
include/Firebase/Firestore/WriteBatch.hpp
<gh_stars>0 // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Firebase::Firestore namespace Firebase::Firestore { // Forward declaring type: WriteBatchProxy class WriteBatchProxy; // Forward declaring type: DocumentReference class DocumentReference; // Forward declaring type: FieldValueProxy class FieldValueProxy; // Forward declaring type: SetOptions class SetOptions; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IDictionary`2<TKey, TValue> template<typename TKey, typename TValue> class IDictionary_2; } // Forward declaring namespace: System::Threading::Tasks namespace System::Threading::Tasks { // Forward declaring type: Task class Task; } // Completed forward declares // Type namespace: Firebase.Firestore namespace Firebase::Firestore { // Forward declaring type: WriteBatch class WriteBatch; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Firebase::Firestore::WriteBatch); DEFINE_IL2CPP_ARG_TYPE(::Firebase::Firestore::WriteBatch*, "Firebase.Firestore", "WriteBatch"); // Type namespace: Firebase.Firestore namespace Firebase::Firestore { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: Firebase.Firestore.WriteBatch // [TokenAttribute] Offset: FFFFFFFF class WriteBatch : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private readonly Firebase.Firestore.WriteBatchProxy _proxy // Size: 0x8 // Offset: 0x10 ::Firebase::Firestore::WriteBatchProxy* proxy; // Field size check static_assert(sizeof(::Firebase::Firestore::WriteBatchProxy*) == 0x8); public: // Creating conversion operator: operator ::Firebase::Firestore::WriteBatchProxy* constexpr operator ::Firebase::Firestore::WriteBatchProxy*() const noexcept { return proxy; } // Get instance field reference: private readonly Firebase.Firestore.WriteBatchProxy _proxy ::Firebase::Firestore::WriteBatchProxy*& dyn__proxy(); // System.Void .ctor(Firebase.Firestore.WriteBatchProxy proxy) // Offset: 0xC381F8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static WriteBatch* New_ctor(::Firebase::Firestore::WriteBatchProxy* proxy) { static auto ___internal__logger = ::Logger::get().WithContext("::Firebase::Firestore::WriteBatch::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<WriteBatch*, creationType>(proxy))); } // public Firebase.Firestore.WriteBatch Delete(Firebase.Firestore.DocumentReference documentReference) // Offset: 0xC41B6C ::Firebase::Firestore::WriteBatch* Delete(::Firebase::Firestore::DocumentReference* documentReference); // public Firebase.Firestore.WriteBatch Update(Firebase.Firestore.DocumentReference documentReference, System.Collections.Generic.IDictionary`2<System.String,System.Object> updates) // Offset: 0xC41BAC ::Firebase::Firestore::WriteBatch* Update(::Firebase::Firestore::DocumentReference* documentReference, ::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>* updates); // private Firebase.Firestore.FieldValueProxy ConvertToFieldValue(System.Collections.Generic.IDictionary`2<System.String,System.Object> updates) // Offset: 0xC41BF0 ::Firebase::Firestore::FieldValueProxy* ConvertToFieldValue(::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>* updates); // public Firebase.Firestore.WriteBatch Set(Firebase.Firestore.DocumentReference documentReference, System.Object documentData, Firebase.Firestore.SetOptions options) // Offset: 0xC41CC0 ::Firebase::Firestore::WriteBatch* Set(::Firebase::Firestore::DocumentReference* documentReference, ::Il2CppObject* documentData, ::Firebase::Firestore::SetOptions* options); // public System.Threading.Tasks.Task CommitAsync() // Offset: 0xC41E4C ::System::Threading::Tasks::Task* CommitAsync(); }; // Firebase.Firestore.WriteBatch #pragma pack(pop) static check_size<sizeof(WriteBatch), 16 + sizeof(::Firebase::Firestore::WriteBatchProxy*)> __Firebase_Firestore_WriteBatchSizeCheck; static_assert(sizeof(WriteBatch) == 0x18); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::Delete // Il2CppName: Delete template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::WriteBatch* (Firebase::Firestore::WriteBatch::*)(::Firebase::Firestore::DocumentReference*)>(&Firebase::Firestore::WriteBatch::Delete)> { static const MethodInfo* get() { static auto* documentReference = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReference")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::WriteBatch*), "Delete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{documentReference}); } }; // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::Update // Il2CppName: Update template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::WriteBatch* (Firebase::Firestore::WriteBatch::*)(::Firebase::Firestore::DocumentReference*, ::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>*)>(&Firebase::Firestore::WriteBatch::Update)> { static const MethodInfo* get() { static auto* documentReference = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReference")->byval_arg; static auto* updates = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "IDictionary`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Object")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::WriteBatch*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{documentReference, updates}); } }; // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::ConvertToFieldValue // Il2CppName: ConvertToFieldValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueProxy* (Firebase::Firestore::WriteBatch::*)(::System::Collections::Generic::IDictionary_2<::StringW, ::Il2CppObject*>*)>(&Firebase::Firestore::WriteBatch::ConvertToFieldValue)> { static const MethodInfo* get() { static auto* updates = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "IDictionary`2"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String"), ::il2cpp_utils::GetClassFromName("System", "Object")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::WriteBatch*), "ConvertToFieldValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{updates}); } }; // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::Set // Il2CppName: Set template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::WriteBatch* (Firebase::Firestore::WriteBatch::*)(::Firebase::Firestore::DocumentReference*, ::Il2CppObject*, ::Firebase::Firestore::SetOptions*)>(&Firebase::Firestore::WriteBatch::Set)> { static const MethodInfo* get() { static auto* documentReference = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReference")->byval_arg; static auto* documentData = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* options = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "SetOptions")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::WriteBatch*), "Set", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{documentReference, documentData, options}); } }; // Writing MetadataGetter for method: Firebase::Firestore::WriteBatch::CommitAsync // Il2CppName: CommitAsync template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Threading::Tasks::Task* (Firebase::Firestore::WriteBatch::*)()>(&Firebase::Firestore::WriteBatch::CommitAsync)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::WriteBatch*), "CommitAsync", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
xc35/dragontoolkit
src/main/java/edu/drexel/cis/dragon/nlp/compare/ConceptEntryIDComparator.java
<reponame>xc35/dragontoolkit<filename>src/main/java/edu/drexel/cis/dragon/nlp/compare/ConceptEntryIDComparator.java /* */ package edu.drexel.cis.dragon.nlp.compare; /* */ /* */ import edu.drexel.cis.dragon.nlp.Concept; /* */ import java.io.Serializable; /* */ import java.util.Comparator; /* */ /* */ public class ConceptEntryIDComparator /* */ implements Comparator, Serializable /* */ { /* */ private static final long serialVersionUID = 1L; /* */ /* */ public int compare(Object firstObj, Object secondObj) /* */ { /* 22 */ Concept first = (Concept)firstObj; /* 23 */ String cui1 = first.getEntryID(); /* 24 */ Concept second = (Concept)secondObj; /* 25 */ String cui2 = second.getEntryID(); /* 26 */ if ((cui1 != null) && (cui2 != null)) /* 27 */ return cui1.compareTo(cui2); /* 28 */ if ((cui1 == null) && (cui2 == null)) /* 29 */ return first.getName().compareToIgnoreCase(second.getName()); /* 30 */ if (cui1 == null) { /* 31 */ return -1; /* */ } /* 33 */ return 1; /* */ } /* */ /* */ public boolean equals(Object obj) { /* 37 */ return false; /* */ } /* */ } /* Location: C:\dragontoolikt\dragontool.jar * Qualified Name: dragon.nlp.compare.ConceptEntryIDComparator * JD-Core Version: 0.6.2 */
DaGeRe/TeeTime
src/integration-test/java/teetime/framework/scheduling/globaltaskpool/ProducerConsumerGlobalTaskPoolIT.java
<reponame>DaGeRe/TeeTime /** * Copyright © 2015 <NAME>, <NAME> (http://teetime-framework.github.io) * * 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 teetime.framework.scheduling.globaltaskpool; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import org.junit.Test; import teetime.framework.Configuration; import teetime.framework.Execution; import teetime.framework.TeeTimeScheduler; import teetime.framework.scheduling.globaltaskpool.GlobalTaskPoolScheduling; import teetime.stage.CollectorSink; import teetime.stage.StreamProducer; public class ProducerConsumerGlobalTaskPoolIT { @Test public void shouldExecuteProducerConsumerWithOneThread() { shouldExecuteProducerConsumer(1, 1); } @Test public void shouldExecuteProducerConsumerWithTwoThreads() { shouldExecuteProducerConsumer(2, 1); } @Test public void shouldExecuteProducerConsumerWithFourThreads() { shouldExecuteProducerConsumer(4, 1); } @Test public void shouldExecuteProducerConsumerWithOneThreadMultipleExecutions() { shouldExecuteProducerConsumer(1, 256); } @Test public void shouldExecuteProducerConsumerWithTwoThreadsMultipleExecutions() { shouldExecuteProducerConsumer(2, 256); } @Test public void shouldExecuteProducerConsumerWithFourThreadsMultipleExecutions() { shouldExecuteProducerConsumer(4, 256); } private void shouldExecuteProducerConsumer(final int numThreads, final int numExecutions) { int numElements = 10_000; List<Integer> processedElements = new ArrayList<>(); IntStream inputElements = IntStream.iterate(0, i -> i + 1).limit(numElements); Configuration config = new Configuration() .from(new StreamProducer<>(inputElements)) .end(new CollectorSink<>(processedElements)); TeeTimeScheduler scheduling = new GlobalTaskPoolScheduling(numThreads, config, numExecutions); Execution<Configuration> execution = new Execution<>(config, true, scheduling); execution.executeBlocking(); for (int i = 0; i < numElements; i++) { assertThat(processedElements.get(i), is(i)); } assertThat(processedElements, hasSize(numElements)); } }
pydata-apis/python-api-record
data/typing/Orange.misc.distmatrix.py
<gh_stars>10-100 from typing import * class DistMatrix: @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, numpy.ndarray], int ], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, float], int], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, numpy.ndarray], int ], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, float], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix], int, ], /, ): """ usage.orange3: 3 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[ Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix, ], int, ], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix], int, ], /, ): """ usage.orange3: 2 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, int], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix], int, ], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[float, Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[float, Orange.misc.distmatrix.DistMatrix], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, Orange.misc.distmatrix.DistMatrix], int, ], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[numpy.float64, Orange.misc.distmatrix.DistMatrix], int ], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, float], int], /, ): """ usage.orange3: 1 """ ... @overload def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[numpy.ufunc, Tuple[Orange.misc.distmatrix.DistMatrix, int], int], /, ): """ usage.orange3: 1 """ ... def __array_wrap__( self, _0: Orange.misc.distmatrix.DistMatrix, _1: Tuple[ numpy.ufunc, Tuple[ Union[ int, Orange.misc.distmatrix.DistMatrix, numpy.float64, numpy.ndarray, float, ], ..., ], int, ], /, ): """ usage.orange3: 29 """ ...
SergeyZadorozhniy/google-cloud-java
google-api-grpc/proto-google-cloud-language-v1/src/main/java/com/google/cloud/language/v1/SentimentOrBuilder.java
<gh_stars>1-10 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/language/v1/language_service.proto package com.google.cloud.language.v1; public interface SentimentOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.language.v1.Sentiment) com.google.protobuf.MessageOrBuilder { /** * <pre> * A non-negative number in the [0, +inf) range, which represents * the absolute magnitude of sentiment regardless of score (positive or * negative). * </pre> * * <code>float magnitude = 2;</code> */ float getMagnitude(); /** * <pre> * Sentiment score between -1.0 (negative sentiment) and 1.0 * (positive sentiment). * </pre> * * <code>float score = 3;</code> */ float getScore(); }
Brokenshire/codewars-projects
Python/eight_kyu/abbrev_name.py
<reponame>Brokenshire/codewars-projects # Python solution for 'Abbreviate a Two Word Name' codewars question. # Level: 8 kyu # Tags: FUNDAMENTALS, STRINGS, and ARRAYS. # Author: <NAME> # Date: 16/05/2020 import unittest def abbrev_name(name): """ Converts name of two words into initials. :param name: a string. :return: two capital letters with a dot separating them. """ name = name.split() return "{}.{}".format(name[0][0].upper(), name[1][0].upper()) class TestAbbrevName(unittest.TestCase): """Class to test 'abbrev_name' function""" def test_abbrev_name(self): self.assertEqual(abbrev_name("<NAME>"), "S.H") self.assertEqual(abbrev_name("<NAME>"), "P.F") self.assertEqual(abbrev_name("<NAME>"), "E.C") self.assertEqual(abbrev_name("<NAME>"), "P.F") self.assertEqual(abbrev_name("<NAME>"), "D.M") if __name__ == '__main__': unittest.main()
jaklinger/nesta_dataflow
collect_data/utils/aws/decode_lambda_output.py
<reponame>jaklinger/nesta_dataflow from __future__ import print_function import json,sys from base64 import b64decode #---- output = json.loads("".join(sys.argv[1:])) print("\tExited with Status Code:\t",output["StatusCode"],"\n") try: log = b64decode(output["LogResult"]) print("Log output is:") for line in log.split(b"\n"): print("\t>>> ",line) except: pass
MoeweX/moquette
broker/src/main/java/io/moquette/delaygrouping/peering/messaging/PeerMessage.java
package io.moquette.delaygrouping.peering.messaging; import java.io.Serializable; import java.util.UUID; public class PeerMessage implements Serializable { private static final long serialVersionUID = 1L; public final PeerMessageType type; public final String uid = UUID.randomUUID().toString(); public PeerMessage(PeerMessageType type) { this.type = type; } public void retain() { } @Override public String toString() { return "PeerMessage{" + "type=" + type + '}'; } }
geophile/sql-layer
fdb-sql-layer-core/src/test/java/com/foundationdb/util/WrappingByteSourceCompareToTest.java
<gh_stars>0 /** * The MIT License (MIT) * * Copyright (c) 2009-2015 FoundationDB, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.foundationdb.util; import com.foundationdb.junit.NamedParameterizedRunner; import com.foundationdb.junit.Parameterization; import com.foundationdb.junit.ParameterizationBuilder; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; @RunWith(NamedParameterizedRunner.class) public final class WrappingByteSourceCompareToTest { @NamedParameterizedRunner.TestParameters public static Collection<Parameterization> params() { ParameterizationBuilder pb = new ParameterizationBuilder(); build(pb, bs(), bs(), CompareResult.EQ); build(pb, bs(1), bs(), CompareResult.GT); build(pb, bs(), bs(1), CompareResult.LT); build(pb, bs(5), bs(5), CompareResult.EQ); build(pb, bs(5, 1), bs(5), CompareResult.GT); build(pb, bs(5), bs(5, 1), CompareResult.LT); build(pb, bs(4), bs(5), CompareResult.LT); build(pb, bs(4, 1), bs(5), CompareResult.LT); build(pb, bs(4), bs(5, 1), CompareResult.LT); build(pb, bs(6), bs(5), CompareResult.GT); build(pb, bs(6, 1), bs(5), CompareResult.GT); build(pb, bs(6), bs(5, 1), CompareResult.GT); return pb.asList(); } @Test public void normal() { test(new WrappingByteSource(bytesOne), new WrappingByteSource(bytesTwo)); } @Test public void oneIsOffset() { test(wrapWithOffset(bytesOne), new WrappingByteSource(bytesTwo)); } @Test public void twoIsOffset() { test(new WrappingByteSource(bytesOne), wrapWithOffset(bytesTwo)); } private ByteSource wrapWithOffset(byte[] target) { byte[] withOffset = new byte[target.length + OFFSET]; Arrays.fill(withOffset, (byte) 31); System.arraycopy(target, 0, withOffset, OFFSET, target.length); return new WrappingByteSource().wrap(withOffset, OFFSET, target.length); } public WrappingByteSourceCompareToTest(byte[] bytesOne, byte[] bytesTwo, CompareResult expected) { this.bytesOne = bytesOne; this.bytesTwo = bytesTwo; this.expected = expected; } private final byte[] bytesOne; private final byte[] bytesTwo; private final CompareResult expected; private void test(ByteSource one, ByteSource two) { CompareResult actual = CompareResult.fromInt(one.compareTo(two)); assertEquals(expected, actual); } private static void build(ParameterizationBuilder pb, byte[] one, byte[] two, CompareResult expected) { StringBuilder sb = new StringBuilder(); sb.append(Arrays.toString(one)).append(' ').append(expected).append(' ').append(Arrays.toString(two)); pb.add(sb.toString(), one, two, expected); } private static byte[] bs(int... ints) { byte[] bytes = new byte[ints.length]; for (int i=0; i < ints.length; ++i) { bytes[i] = (byte)ints[i]; } return bytes; } private static final int OFFSET = 4; private enum CompareResult { LT, EQ, GT ; public static CompareResult fromInt(int compareToResult) { if (compareToResult < 0) return LT; return (compareToResult > 0) ? GT : EQ; } } }
ikrima/immer
example/flex-vector/flex-vector.cpp
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 <NAME> // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #include <immer/flex_vector.hpp> #include <cassert> int main() { { // include:push-back/start auto v1 = immer::flex_vector<int>{1}; auto v2 = v1.push_back(8); assert((v1 == immer::flex_vector<int>{1})); assert((v2 == immer::flex_vector<int>{1, 8})); // include:push-back/end } { // include:push-front/start auto v1 = immer::flex_vector<int>{1}; auto v2 = v1.push_front(8); assert((v1 == immer::flex_vector<int>{1})); assert((v2 == immer::flex_vector<int>{8, 1})); // include:push-front/end } { // include:set/start auto v1 = immer::flex_vector<int>{1, 2, 3}; auto v2 = v1.set(0, 5); assert((v1 == immer::flex_vector<int>{1, 2, 3})); assert((v2 == immer::flex_vector<int>{5, 2, 3})); // include:set/end } { // include:update/start auto v1 = immer::flex_vector<int>{1, 2, 3, 4}; auto v2 = v1.update(2, [&](auto l) { return ++l; }); assert((v1 == immer::flex_vector<int>{1, 2, 3, 4})); assert((v2 == immer::flex_vector<int>{1, 2, 4, 4})); // include:update/end } { // include:take/start auto v1 = immer::flex_vector<int>{1, 2, 3, 4, 5, 6}; auto v2 = v1.take(3); assert((v1 == immer::flex_vector<int>{1, 2, 3, 4, 5, 6})); assert((v2 == immer::flex_vector<int>{1, 2, 3})); // include:take/end } { // include:drop/start auto v1 = immer::flex_vector<int>{1, 2, 3, 4, 5, 6}; auto v2 = v1.drop(3); assert((v1 == immer::flex_vector<int>{1, 2, 3, 4, 5, 6})); assert((v2 == immer::flex_vector<int>{4, 5, 6})); // include:drop/end } { // include:insert/start auto v1 = immer::flex_vector<int>{1, 2, 3}; auto v2 = v1.insert(0, 0); assert((v1 == immer::flex_vector<int>{1, 2, 3})); assert((v2 == immer::flex_vector<int>{0, 1, 2, 3})); // include:insert/end } { // include:erase/start auto v1 = immer::flex_vector<int>{1, 2, 3, 4, 5}; auto v2 = v1.erase(2); assert((v1 == immer::flex_vector<int>{1, 2, 3, 4, 5})); assert((v2 == immer::flex_vector<int>{1, 2, 4, 5})); // include:erase/end } { // include:concat/start auto v1 = immer::flex_vector<int>{1, 2, 3}; auto v2 = v1 + v1; assert((v1 == immer::flex_vector<int>{1, 2, 3})); assert((v2 == immer::flex_vector<int>{1, 2, 3, 1, 2, 3})); // include:concat/end } }
jbcam/codecrumbs
src/public/js/components/treeDiagram/component/StandalonePlaceholder/index.js
import React from 'react'; import { connect } from 'react-redux'; import { Upload, Icon } from 'antd'; import { uploadStore } from 'core/dataBus/actions'; import './index.scss'; const Dragger = Upload.Dragger; const StandalonePlaceholder = props => { const { onUpload } = props; const uploaderProps = { beforeUpload: file => { onUpload(file); return false; }, fileList: [] }; return ( <div className={'StandalonePlaceholder'}> <Dragger {...uploaderProps}> <p className="ant-upload-drag-icon"> <Icon type="inbox" /> </p> <p className="ant-upload-text"> Click or drag `codecrumbs` json file to this area to upload </p> <p className="ant-upload-hint">All magic will happen automatically right after!</p> </Dragger> </div> ); }; const mapDispatchToProps = { onUpload: uploadStore }; export default connect( null, mapDispatchToProps )(StandalonePlaceholder);
ghsecuritylab/tomato_egg
release/src/router/samba3/source/modules/vfs_irixacl.c
/* Unix SMB/Netbios implementation. VFS module to get and set irix acls Copyright (C) <NAME> 2006 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "includes.h" /* prototypes for private functions first - for clarity */ /* public functions - the api */ SMB_ACL_T irixacl_sys_acl_get_file(vfs_handle_struct *handle, const char *path_p, SMB_ACL_TYPE_T type) { errno = ENOTSUP; return NULL; } SMB_ACL_T irixacl_sys_acl_get_fd(vfs_handle_struct *handle, files_struct *fsp, int fd) { errno = ENOTSUP; return NULL; } int irixacl_sys_acl_set_file(vfs_handle_struct *handle, const char *name, SMB_ACL_TYPE_T type, SMB_ACL_T theacl) { errno = ENOTSUP; return -1; } int irixacl_sys_acl_set_fd(vfs_handle_struct *handle, files_struct *fsp, int fd, SMB_ACL_T theacl) { errno = ENOTSUP; return -1; } int irixacl_sys_acl_delete_def_file(vfs_handle_struct *handle, const char *path) { errno = ENOTSUP; return -1; } /* private functions */ /* VFS operations structure */ static vfs_op_tuple irixacl_op_tuples[] = { /* Disk operations */ {SMB_VFS_OP(irixacl_sys_acl_get_file), SMB_VFS_OP_SYS_ACL_GET_FILE, SMB_VFS_LAYER_TRANSPARENT}, {SMB_VFS_OP(irixacl_sys_acl_get_fd), SMB_VFS_OP_SYS_ACL_GET_FD, SMB_VFS_LAYER_TRANSPARENT}, {SMB_VFS_OP(irixacl_sys_acl_set_file), SMB_VFS_OP_SYS_ACL_SET_FILE, SMB_VFS_LAYER_TRANSPARENT}, {SMB_VFS_OP(irixacl_sys_acl_set_fd), SMB_VFS_OP_SYS_ACL_SET_FD, SMB_VFS_LAYER_TRANSPARENT}, {SMB_VFS_OP(irixacl_sys_acl_delete_def_file), SMB_VFS_OP_SYS_ACL_DELETE_DEF_FILE, SMB_VFS_LAYER_TRANSPARENT}, {SMB_VFS_OP(NULL), SMB_VFS_OP_NOOP, SMB_VFS_LAYER_NOOP} }; NTSTATUS vfs_irixacl_init(void); NTSTATUS vfs_irixacl_init(void) { return smb_register_vfs(SMB_VFS_INTERFACE_VERSION, "irixacl", irixacl_op_tuples); } /* ENTE */
finntenzor/potaotoreminder-old
app/src/main/java/com/github/potatobill/potatoreminder/MainActivity.java
package com.github.potatobill.potatoreminder; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.github.potatobill.potatoreminder.data.EntryAdapter; import com.github.potatobill.potatoreminder.data.EntryData; import java.util.ArrayList; import android.app.ProgressDialog; import com.github.potatobill.potatoreminder.data.Machine; import com.github.potatobill.potatoreminder.data.DataHandler_2; import android.os.Message; import android.app.AlertDialog; import android.content.DialogInterface; import android.widget.EditText; public class MainActivity extends Activity implements Machine.Settable { App app; ListView lvContext; TextView tvPosition; Button btStudy; Button btExport; private ProgressDialog pdLoad; private MHandler mHandler; private Thread mThread; private Planner mPlanner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (App) getApplication(); Log.i("potatoreminder","main-onCreate"); setContentView(R.layout.activity_main); lvContext = (ListView) findViewById(R.id.mainListViewEdit); btStudy = (Button) findViewById(R.id.mainButtonStudy); btExport = (Button) findViewById(R.id.mainButtonExport); tvPosition = (TextView) findViewById(R.id.mainTextViewPosition); LvContextClick lvccl = new LvContextClick(); lvContext.setOnItemClickListener(lvccl); lvContext.setOnItemLongClickListener(lvccl); Button btTest = (Button) findViewById(R.id.mainButtonTest); btTest.setOnClickListener(new OnClickListener(){ @Override public void onClick(View p1) { //app.dm.logAll(); //app.dm.down(MainActivity.this); //app.dm.temp(); } }); if (mHandler == null) mHandler = new MHandler(); mPlanner = new Planner(mHandler); mPlanner.setApp((App) getApplicationContext()); createProgressDialog(); } @Override protected void onResume() { super.onResume(); Log.i("potatoreminder","main-resume"); load(); } private void load() { ArrayList<EntryData> data = new ArrayList<EntryData>(); if (app.dm != null && app.dm.isOpen()) { app.dm.loadByPosition(data, app.position); EntryAdapter ea = new EntryAdapter(this, data); lvContext.setAdapter(ea); tvPosition.setText(app.dm.getPositionString(app.position)+"/"); } else { finish(); } } class LvContextClick implements OnItemClickListener,OnItemLongClickListener { @Override public boolean onItemLongClick(AdapterView<?> p1, View p2, int p3, long p4) { EntryData entry = (EntryData) lvContext.getItemAtPosition(p3); Intent t; Bundle b = new Bundle(); switch (entry.type) { case EntryData.TYPE_NODE: app.firstIn = true; t = new Intent(MainActivity.this,EditNodeActivity.class); b.putInt("id",entry.id); b.putInt("position",entry.id); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_LIST: app.firstIn = true; t = new Intent(MainActivity.this,EditListActivity.class); b.putInt("id",entry.id); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_POINT: app.firstIn = true; t = new Intent(MainActivity.this,EditPointActivity.class); b.putInt("id",entry.id); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_IMAGE: app.firstIn = true; t = new Intent(MainActivity.this,EditImageActivity.class); t.putExtra("id",entry.id); startActivity(t); break; case EntryData.TYPE_BACK: app.position=app.dm.getParentId(app.position); load(); break; case EntryData.TYPE_NEW_NODE: case EntryData.TYPE_NEW_LIST: case EntryData.TYPE_NEW_POINT: b.putInt("type",entry.type); b.putInt("position",app.position); t = new Intent(MainActivity.this,NewActivity.class); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_NEW_IMAGE: app.firstIn = true; startActivity(new Intent(MainActivity.this,NewImageActivity.class)); break; } return true; } @Override public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4) { EntryData entry = (EntryData) lvContext.getItemAtPosition(p3); Intent t; Bundle b = new Bundle(); switch (entry.type) { case EntryData.TYPE_NODE: app.position=entry.id; load(); break; case EntryData.TYPE_LIST: app.firstIn = true; t = new Intent(MainActivity.this,EditListActivity.class); b.putInt("id",entry.id); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_POINT: app.firstIn = true; t = new Intent(MainActivity.this,EditPointActivity.class); b.putInt("id",entry.id); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_IMAGE: app.firstIn = true; t = new Intent(MainActivity.this,EditImageActivity.class); t.putExtra("id",entry.id); startActivity(t); break; case EntryData.TYPE_BACK: app.position=app.dm.getParentId(app.position); load(); break; case EntryData.TYPE_NEW_NODE: case EntryData.TYPE_NEW_LIST: case EntryData.TYPE_NEW_POINT: b.putInt("type",entry.type); b.putInt("position",app.position); t = new Intent(MainActivity.this,NewActivity.class); t.putExtras(b); startActivity(t); break; case EntryData.TYPE_NEW_IMAGE: app.firstIn = true; startActivity(new Intent(MainActivity.this,NewImageActivity.class)); break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate main_menu.xml MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mainMenuStudy: pdLoad.setTitle("加载中"); pdLoad.setMessage("正在加载"); pdLoad.show(); if (mThread == null) { mThread = new Thread(new Runnable() { @Override public void run() { App app = (App) getApplicationContext(); app.dm.setMachine(); app.dm.getMachine().prepare(MainActivity.this,app.position); //app.dm.getMachine().LogAll(); if (app.dm.getMachine().getEntry().getInt("type") == EntryData.TYPE_BACK) unjump(); else jump(); } }); mThread.start(); } app.firstIn = true; break; case R.id.mainMenuExport: Intent toExport = new Intent(this, BrowseActivity.class); toExport.putExtra("flag", Constant.MAIN_TO_EXPORT); startActivity(toExport); break; case R.id.mainMenuImport: Intent toImport = new Intent(this, BrowseActivity.class); toImport.putExtra("flag", Constant.MAIN_TO_IMPORT); startActivity(toImport); break; case R.id.mainMenuSearch: showToast("功能暂未开发 敬请期待"); break; case R.id.mainMenuPlan: //TODO 实现计划功能 pdLoad.setTitle("调整计划"); pdLoad.setMessage("正在调整"); AlertDialog.Builder builder = new AlertDialog.Builder(this); final EditText etInput = new EditText(this); etInput.setFocusable(true); final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: String input = etInput.getText().toString(); try { int planNum = Integer.parseInt(input); mPlanner.setPlanNum(planNum); pdLoad.show(); new Thread(mPlanner).start(); } catch (NumberFormatException e) { showExcetion("您输入的不是数字哦"); } break; case DialogInterface.BUTTON_NEGATIVE: dialog.dismiss(); } } }; builder.setTitle("请输入计划").setIcon(R.drawable.ic_launcher) .setPositiveButton("确定",listener).setNegativeButton("取消",listener) .setMessage("我计划每天学习…个").setView(etInput).create().show(); } return super.onOptionsItemSelected(item); } private void createProgressDialog() { pdLoad = new ProgressDialog(this); pdLoad.setIcon(R.drawable.ic_launcher); pdLoad.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pdLoad.setMax(100); pdLoad.setProgress(0); pdLoad.setCancelable(false); } @Override public void setBoth(final int progress,final String state) { if (pdLoad != null) { mHandler.post(new Runnable() { @Override public void run() { pdLoad.setProgress(progress); pdLoad.setMessage(state); } }); } } private void jump() { mHandler.post(new Runnable() { @Override public void run() { pdLoad.dismiss(); mThread = null; Intent t = new Intent(MainActivity.this,StudyActivity.class); startActivity(t); } }); } private void unjump() { mHandler.post(new Runnable() { @Override public void run() { pdLoad.dismiss(); mThread = null; showToast("这里暂时还没有要复习的知识哦"); } }); } private void showToast(String text) { Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if (app.position==0) { if((System.currentTimeMillis()-exitTime) > 2000){ Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { app.dm.close(); app.position = 0; finish(); System.exit(0); } return true; } else { app.position = app.dm.getParentId(app.position); load(); return true; } } return super.onKeyDown(keyCode, event); } private class Planner implements Runnable, DataHandler_2.Settable { private App app; private Handler mHandler; private int planNum; private int progress; private String state; @Override public void run() { try { app.dm.setPlan(app.position, planNum, this); mHandler.sendEmptyMessage(Constant.Main.MHANDLE_HIDE_PROGRESS_DIALOG); } catch (Exception e) { e.printStackTrace(); Message exceptionMessage = Message.obtain(); exceptionMessage.what = Constant.Main.MHANDLE_SHOW_EXCEPTION; exceptionMessage.obj = e.getMessage(); mHandler.sendMessage(exceptionMessage); } } @Override public void setBoth(int progress, String state) { this.progress = progress; this.state = state; mHandler.sendEmptyMessage(Constant.Main.MHANDLE_SHOW_PLAN_PROGRESS); } public int getProgress() { return progress; } public String getState() { return state; } public void setPlanNum(int planNum) { this.planNum = planNum; } public void setApp(App app) { this.app = app; } public Planner(Handler handler) { this.mHandler = handler; } } private void showExcetion(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_launcher).setTitle("发生错误") .setMessage("错误信息:" + message).setPositiveButton("确定", null).show(); } private class MHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case Constant.Main.MHANDLE_SHOW_EXCEPTION: showExcetion((String) msg.obj); pdLoad.dismiss(); break; case Constant.Main.MHANDLE_SHOW_PLAN_PROGRESS: pdLoad.setProgress(mPlanner.getProgress()); pdLoad.setMessage(mPlanner.getState()); break; case Constant.Main.MHANDLE_HIDE_PROGRESS_DIALOG: pdLoad.dismiss(); break; default: showExcetion("意外的处理信息"); break; } } } }
vftens/MuZeroText2021
MuZero/muzero-general/games/RocAlphaGo_aug25_keras2_py35/node_modules/@consta/uikit/__internal__/cjs-src/icons/IconCamera/IconCamera.js
<gh_stars>0 "use strict"; exports.__esModule = true; exports.IconCamera = void 0; var tslib_1 = require("tslib"); var createIcon_1 = require("../createIcon/createIcon"); var IconCamera_size_m_1 = tslib_1.__importDefault(require("./IconCamera_size_m")); var IconCamera_size_s_1 = tslib_1.__importDefault(require("./IconCamera_size_s")); var IconCamera_size_xs_1 = tslib_1.__importDefault(require("./IconCamera_size_xs")); exports.IconCamera = createIcon_1.createIcon({ m: IconCamera_size_m_1["default"], s: IconCamera_size_s_1["default"], xs: IconCamera_size_xs_1["default"], name: 'IconCamera' });
iscai-msft/azure-sdk-for-python
sdk/machinelearning/azure-mgmt-machinelearningservices/azure/mgmt/machinelearningservices/operations/_machine_learning_compute_operations.py
<reponame>iscai-msft/azure-sdk-for-python<gh_stars>1-10 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrest.polling import LROPoller, NoPolling from msrestazure.polling.arm_polling import ARMPolling from .. import models class MachineLearningComputeOperations(object): """MachineLearningComputeOperations operations. You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Version of Azure Machine Learning resource provider API. Constant value: "2019-05-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2019-05-01" self.config = config def list_by_workspace( self, resource_group_name, workspace_name, skiptoken=None, custom_headers=None, raw=False, **operation_config): """Gets computes in specified workspace. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param skiptoken: Continuation token for pagination. :type skiptoken: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of ComputeResource :rtype: ~azure.mgmt.machinelearningservices.models.ComputeResourcePaged[~azure.mgmt.machinelearningservices.models.ComputeResource] :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ def prepare_request(next_link=None): if not next_link: # Construct URL url = self.list_by_workspace.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if skiptoken is not None: query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) return request def internal_paging(next_link=None): request = prepare_request(next_link) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.MachineLearningServiceErrorException(self._deserialize, response) return response # Deserialize response header_dict = None if raw: header_dict = {} deserialized = models.ComputeResourcePaged(internal_paging, self._deserialize.dependencies, header_dict) return deserialized list_by_workspace.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes'} def get( self, resource_group_name, workspace_name, compute_name, custom_headers=None, raw=False, **operation_config): """Gets compute definition by its name. Any secrets (storage keys, service credentials, etc) are not returned - use 'keys' nested resource to get them. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ComputeResource or ClientRawResponse if raw=true :rtype: ~azure.mgmt.machinelearningservices.models.ComputeResource or ~msrest.pipeline.ClientRawResponse :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ # Construct URL url = self.get.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.MachineLearningServiceErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ComputeResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}'} def _create_or_update_initial( self, resource_group_name, workspace_name, compute_name, parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.create_or_update.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'ComputeResource') # Construct and send request request = self._client.put(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 201]: raise models.MachineLearningServiceErrorException(self._deserialize, response) deserialized = None header_dict = {} if response.status_code == 200: deserialized = self._deserialize('ComputeResource', response) header_dict = { 'Azure-AsyncOperation': 'str', } if response.status_code == 201: deserialized = self._deserialize('ComputeResource', response) header_dict = { 'Azure-AsyncOperation': 'str', } if raw: client_raw_response = ClientRawResponse(deserialized, response) client_raw_response.add_headers(header_dict) return client_raw_response return deserialized def create_or_update( self, resource_group_name, workspace_name, compute_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param parameters: Payload with Machine Learning compute definition. :type parameters: ~azure.mgmt.machinelearningservices.models.ComputeResource :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns ComputeResource or ClientRawResponse<ComputeResource> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.machinelearningservices.models.ComputeResource] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.machinelearningservices.models.ComputeResource]] :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, compute_name=compute_name, parameters=parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): header_dict = { 'Azure-AsyncOperation': 'str', } deserialized = self._deserialize('ComputeResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) client_raw_response.add_headers(header_dict) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}'} def _update_initial( self, resource_group_name, workspace_name, compute_name, scale_settings=None, custom_headers=None, raw=False, **operation_config): parameters = models.ClusterUpdateParameters(scale_settings=scale_settings) # Construct URL url = self.update.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'ClusterUpdateParameters') # Construct and send request request = self._client.patch(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.MachineLearningServiceErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ComputeResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def update( self, resource_group_name, workspace_name, compute_name, scale_settings=None, custom_headers=None, raw=False, polling=True, **operation_config): """Updates properties of a compute. This call will overwrite a compute if it exists. This is a nonrecoverable operation. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param scale_settings: Scale settings. Desired scale settings for the amlCompute. :type scale_settings: ~azure.mgmt.machinelearningservices.models.ScaleSettings :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns ComputeResource or ClientRawResponse<ComputeResource> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.machinelearningservices.models.ComputeResource] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.machinelearningservices.models.ComputeResource]] :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ raw_result = self._update_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, compute_name=compute_name, scale_settings=scale_settings, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('ComputeResource', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}'} def _delete_initial( self, resource_group_name, workspace_name, compute_name, underlying_resource_action, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.delete.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') query_parameters['underlyingResourceAction'] = self._serialize.query("underlying_resource_action", underlying_resource_action, 'str') # Construct headers header_parameters = {} if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 202]: raise models.MachineLearningServiceErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) header_dict = { 'Azure-AsyncOperation': 'str', 'Location': 'str', } client_raw_response.add_headers(header_dict) return client_raw_response def delete( self, resource_group_name, workspace_name, compute_name, underlying_resource_action, custom_headers=None, raw=False, polling=True, **operation_config): """Deletes specified Machine Learning compute. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param underlying_resource_action: Delete the underlying compute if 'Delete', or detach the underlying compute from workspace if 'Detach'. Possible values include: 'Delete', 'Detach' :type underlying_resource_action: str or ~azure.mgmt.machinelearningservices.models.UnderlyingResourceAction :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns None or ClientRawResponse<None> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ raw_result = self._delete_initial( resource_group_name=resource_group_name, workspace_name=workspace_name, compute_name=compute_name, underlying_resource_action=underlying_resource_action, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): if raw: client_raw_response = ClientRawResponse(None, response) client_raw_response.add_headers({ 'Azure-AsyncOperation': 'str', 'Location': 'str', }) return client_raw_response lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}'} def list_nodes( self, resource_group_name, workspace_name, compute_name, custom_headers=None, raw=False, **operation_config): """Get the details (e.g IP address, port etc) of all the compute nodes in the compute. :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: AmlComputeNodesInformation or ClientRawResponse if raw=true :rtype: ~azure.mgmt.machinelearningservices.models.AmlComputeNodesInformation or ~msrest.pipeline.ClientRawResponse :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ # Construct URL url = self.list_nodes.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.MachineLearningServiceErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('AmlComputeNodesInformation', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized list_nodes.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}/listNodes'} def list_keys( self, resource_group_name, workspace_name, compute_name, custom_headers=None, raw=False, **operation_config): """Gets secrets related to Machine Learning compute (storage keys, service credentials, etc). :param resource_group_name: Name of the resource group in which workspace is located. :type resource_group_name: str :param workspace_name: Name of Azure Machine Learning workspace. :type workspace_name: str :param compute_name: Name of the Azure Machine Learning compute. :type compute_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: ComputeSecrets or ClientRawResponse if raw=true :rtype: ~azure.mgmt.machinelearningservices.models.ComputeSecrets or ~msrest.pipeline.ClientRawResponse :raises: :class:`MachineLearningServiceErrorException<azure.mgmt.machinelearningservices.models.MachineLearningServiceErrorException>` """ # Construct URL url = self.list_keys.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'), 'computeName': self._serialize.url("compute_name", compute_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.MachineLearningServiceErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ComputeSecrets', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}/listKeys'}
dhanu10896/tech-notes
java-persistence-api-21/08/demos/src/main/java/com/pluralsight/persistence/module07/rest/RestApplication.java
package com.pluralsight.persistence.module07.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * @author <NAME> * http://www.antoniogoncalves.org * -- */ @ApplicationPath("/rest") public class RestApplication extends Application { }
VaibhavBhujade/Blockchain-ERP-interoperability
odoo-13.0/odoo/osv/osv.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from ..exceptions import except_orm from ..models import Model, TransientModel, AbstractModel # Deprecated, kept for backward compatibility. # openerp.exceptions.Warning should be used instead. except_osv = except_orm # Deprecated, kept for backward compatibility. osv = Model osv_memory = TransientModel osv_abstract = AbstractModel # ;-)
vsona/RxJava2RetrofitDemo
app/src/main/java/net/vsona/projecta/net/http/interceptor/ParamsInterceptor.java
package net.vsona.projecta.net.http.interceptor; import android.text.TextUtils; import net.vsona.common.utils.MapUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okio.Buffer; /** * Author : roy * Data : 2016-08-18 15:59 * Describe : */ public class ParamsInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //添加服务器端需要的请求头部 Request newRequest = getNewRequestBuilder(request).build(); return chain.proceed(newRequest); } private Request.Builder getNewRequestBuilder(Request request) { Request.Builder builder = request.newBuilder(); Map<String, String> params = null; Map<String, String> headerParams = null; if (!MapUtils.isEmpty(headerParams)) { for (Map.Entry<String, String> entry : headerParams.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } if (!MapUtils.isEmpty(params)) { //接口参数 if (canSpliceBody(request)) { FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (params.size() > 0) { for (Map.Entry<String, String> entry : params.entrySet()) { formBodyBuilder.add(entry.getKey(), entry.getValue()); } } RequestBody formBody = formBodyBuilder.build(); String postBodyString = convertOkHttpBodyToString(formBody); builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString)); } else { spliceRockParams2Url(request, builder, params); } } return builder; } private Map<String, String> parseResourceRequest2Params(Request request) { HashMap<String, String> params = new HashMap<>(); params.putAll(parseGetParamsWithRequest(request)); params.putAll(parsePostParamsWithRequest(request)); return params; } private boolean canSpliceBody(Request request) { if (request == null) { return false; } if (!TextUtils.equals(request.method(), "POST")) { return false; } RequestBody body = request.body(); if (body == null) { return true; } MediaType mediaType = body.contentType(); if (mediaType == null) { return true; } if (TextUtils.equals(mediaType.subtype(), "multi-part")) { return false; } return true; } // func to inject params into url private void spliceRockParams2Url(Request request, Request.Builder requestBuilder, Map<String, String> paramsMap) { HttpUrl.Builder httpUrlBuilder = request.url().newBuilder(); if (!MapUtils.isEmpty(paramsMap)) { for (Map.Entry<String, String> entry : paramsMap.entrySet()) { httpUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } } requestBuilder.url(httpUrlBuilder.build()); } private static String convertOkHttpBodyToString(final RequestBody requestBody) { if (requestBody == null) { return ""; } try { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return buffer.readUtf8(); } catch (final IOException e) { return "did not work"; } } private static Map<String, String> parsePostParamsWithRequest(final Request request) { RequestBody requestBody = request.body(); Map<String, String> params = new HashMap<>(); String str = convertOkHttpBodyToString(requestBody); if (!TextUtils.isEmpty(str)) { String[] items = str.split("&"); if (items.length > 0) { for (String item : items) { if (!TextUtils.isEmpty(item)) { String[] kv = item.split("="); if (kv.length == 2) { try { String value = (kv[1] == null ? "" : URLDecoder.decode(kv[1], "UTF-8")); params.put(kv[0], value); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } } } return params; } private Map<String, String> parseGetParamsWithRequest(Request request) { String query = request.url().encodedQuery(); Map<String, String> params = new HashMap<>(); if (!TextUtils.isEmpty(query)) { String[] items = query.split("&"); if (items != null && items.length > 0) { for (String item : items) { if (!TextUtils.isEmpty(item)) { String[] kv = item.split("="); if (kv.length == 2) { try { String value = (kv[1] == null ? "" : URLDecoder.decode(kv[1], "UTF-8")); params.put(kv[0], value); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } } } return params; } }
cmhodgson/ols-geocoder
ols-geocoder-web/src/main/java/ca/bc/gov/ols/geocoder/rest/messageconverters/JsonpOlsResponseConverter.java
<gh_stars>1-10 /** * Copyright © 2008-2019, Province of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.bc.gov.ols.geocoder.rest.messageconverters; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.stereotype.Component; import ca.bc.gov.ols.geocoder.IGeocoder; import ca.bc.gov.ols.geocoder.config.GeocoderConfig; import ca.bc.gov.ols.geocoder.rest.OlsResponse; @Component public class JsonpOlsResponseConverter extends AbstractHttpMessageConverter<OlsResponse> { @Autowired private IGeocoder geocoder; public JsonpOlsResponseConverter() { super(new MediaType("application", "javascript", Charset.forName("UTF-8"))); } @Override protected boolean supports(Class<?> clazz) { return OlsResponse.class.isAssignableFrom(clazz); } @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { return false; } @Override protected OlsResponse readInternal(Class<? extends OlsResponse> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return null; } @Override protected void writeInternal(OlsResponse response, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { GeocoderConfig config = geocoder.getDatastore().getConfig(); Writer out = new OutputStreamWriter(outputMessage.getBody(), "UTF-8"); response.reproject(config.getBaseSrsCode(), response.getOutputSRS()); JsonpOlsResponseWriter responseWriter = new JsonpOlsResponseWriter(out, config, response.getCallback()); OlsResponseReader responseReader = new OlsResponseReader(response, responseWriter, config); responseReader.convert(); out.flush(); } }
lethien7121996/saigonnhakhoa
node_modules/devextreme/renovation/preact_wrapper/check_box.js
/** * DevExtreme (renovation/preact_wrapper/check_box.js) * Version: 20.2.6 * Build date: Tue Mar 16 2021 * * Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; exports.default = void 0; var _editor = _interopRequireDefault(require("./editor")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj } } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass) } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function(o, p) { o.__proto__ = p; return o }; return _setPrototypeOf(o, p) } var CheckBox = function(_Editor) { _inheritsLoose(CheckBox, _Editor); function CheckBox() { return _Editor.apply(this, arguments) || this } var _proto = CheckBox.prototype; _proto._optionChanged = function(option) { var _this$_valueChangeAct; var _ref = option || {}, name = _ref.name, previousValue = _ref.previousValue, value = _ref.value; switch (name) { case "value": null === (_this$_valueChangeAct = this._valueChangeAction) || void 0 === _this$_valueChangeAct ? void 0 : _this$_valueChangeAct.call(this, { element: this.$element(), previousValue: previousValue, value: value, event: this._valueChangeEventInstance }); this._valueChangeEventInstance = null; _Editor.prototype._optionChanged.call(this, option); break; case "onValueChanged": this._valueChangeAction = this._createActionByOption("onValueChanged", { excludeValidators: ["disabled", "readOnly"] }); break; default: _Editor.prototype._optionChanged.call(this, option) } this._invalidate() }; return CheckBox }(_editor.default); exports.default = CheckBox; module.exports = exports.default;
KissKissBankBank/kitten
src/esm/components/molecules/cards/team-card/components/image.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["styled", "backgroundSource"], _excluded2 = ["src", "title", "style", "className"]; import React from 'react'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import COLORS from '../../../../../constants/colors-config'; import styled from 'styled-components'; var imageHeight = 378; var imageWidth = 252; var StyledTeamCardImage = styled(function (_ref) { var styled = _ref.styled, backgroundSource = _ref.backgroundSource, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("div", props); }).withConfig({ displayName: "image__StyledTeamCardImage", componentId: "sc-dslxfe-0" })(["background-image:url(", ");background-color:", ";background-size:cover;background-position:center;background-repeat:no-repeat;width:100%;padding-bottom:", ";", ""], function (_ref2) { var backgroundSource = _ref2.backgroundSource; return backgroundSource; }, COLORS.background1, imageHeight / imageWidth * 100 + '%', function (_ref3) { var style = _ref3.style; return style; }); export var TeamCardImage = function TeamCardImage(_ref4) { var src = _ref4.src, title = _ref4.title, style = _ref4.style, className = _ref4.className, props = _objectWithoutPropertiesLoose(_ref4, _excluded2); return /*#__PURE__*/React.createElement(StyledTeamCardImage, _extends({}, props, { backgroundSource: src, title: title, className: classNames(className, 'k-u-margin-bottom-double'), style: style })); }; TeamCardImage.propTypes = { src: PropTypes.string.isRequired, title: PropTypes.string.isRequired };
philip-dds/atst
atst/domain/authnid/__init__.py
from atst.domain.exceptions import UnauthenticatedError, NotFoundError from atst.domain.users import Users from .utils import parse_sdn, email_from_certificate from .crl import CRLRevocationException, CRLInvalidException class AuthenticationContext: def __init__(self, crl_cache, auth_status, sdn, cert): if None in locals().values(): raise UnauthenticatedError( "Missing required authentication context components" ) self.crl_cache = crl_cache self.auth_status = auth_status self.sdn = sdn self.cert = cert.encode() self._parsed_sdn = None def authenticate(self): if not self.auth_status == "SUCCESS": raise UnauthenticatedError("SSL/TLS client authentication failed") self._crl_check() return True def get_user(self): try: return Users.get_by_dod_id(self.parsed_sdn["dod_id"]) except NotFoundError: email = self._get_user_email() return Users.create(permission_sets=[], email=email, **self.parsed_sdn) def _get_user_email(self): try: return email_from_certificate(self.cert) # this just means it is not an email certificate; we might choose to # log in that case except ValueError: return None def _crl_check(self): try: self.crl_cache.crl_check(self.cert) except CRLRevocationException as exc: raise UnauthenticatedError("CRL check failed. " + str(exc)) @property def parsed_sdn(self): if not self._parsed_sdn: try: self._parsed_sdn = parse_sdn(self.sdn) except ValueError as exc: raise UnauthenticatedError(str(exc)) return self._parsed_sdn
CogentEmbedded/tweaktool
tweak-pickle/test/main.c
<reponame>CogentEmbedded/tweaktool<filename>tweak-pickle/test/main.c /** * @file main.c * @ingroup tweak-internal * * @brief test suite for tweak2::transport library. * * @copyright 2018-2021 Cogent Embedded Inc. ALL RIGHTS RESERVED. * * This file is a part of Cogent Tweak Tool feature. * * It is subject to the license terms in the LICENSE file found in the top-level * directory of this distribution or by request via www.cogentembedded.com */ #include <tweak2/log.h> #include <tweak2/pickle_client.h> #include <tweak2/pickle_server.h> #include <acutest.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <math.h> static int32_t answer_count = false; static pthread_mutex_t lock; static pthread_cond_t cond; void reset_answer_count(int32_t new_value) { pthread_mutex_lock(&lock); answer_count = new_value; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } void notify_answer_received() { pthread_mutex_lock(&lock); --answer_count; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } void wait_answers() { pthread_mutex_lock(&lock); while (answer_count > 0) { pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); } static void connection_state_listener_impl(tweak_pickle_connection_state connection_state, void *cookie) { (void)connection_state; (void)cookie; notify_answer_received(); } static void handle_subscribe_impl(tweak_pickle_subscribe* subscribe, void *cookie) { (void)subscribe; (void)cookie; TEST_CHECK(strcmp(tweak_variant_string_c_str(&subscribe->uri_patterns), "*") == 0); notify_answer_received(); } static void handle_client_change_tweak_impl(tweak_pickle_change_item *change, void *cookie) { (void)change; (void)cookie; TEST_CHECK(change->tweak_id == 11); TWEAK_LOG_TEST("change->tweak_id is correct\n"); TEST_CHECK(change->value.type == TWEAK_VARIANT_TYPE_FLOAT); TWEAK_LOG_TEST("change->value.type is correct\n"); TEST_CHECK(fabsf(change->value.value.fp32 - 32.f) < .0001f); TWEAK_LOG_TEST("change->value.value.fp32 is correct\n"); notify_answer_received(); } static void handle_server_change_tweak_impl(tweak_pickle_change_item *change_item, void *cookie) { (void)change_item; (void)cookie; TEST_CHECK(change_item->tweak_id == 17); TWEAK_LOG_TEST("change_item->tweak_i is correct\n"); TEST_CHECK(change_item->value.type == TWEAK_VARIANT_TYPE_FLOAT); TWEAK_LOG_TEST("change_item->value.type is correct\n"); TEST_CHECK(fabsf(change_item->value.value.fp32 - 36.f) < .00001f ); TWEAK_LOG_TEST("change_item->value.value.fp32 is correct\n"); notify_answer_received(); } static void handle_add_item_impl(tweak_pickle_add_item *add_item, void *cookie) { (void)cookie; TEST_CHECK(add_item->tweak_id == 26); TWEAK_LOG_TEST("add_item->tweak_id is correct\n"); TEST_CHECK(strcmp(tweak_variant_string_c_str(&add_item->uri), "X") == 0); TWEAK_LOG_TEST("add_item->uri is correct\n"); TEST_CHECK(strcmp(tweak_variant_string_c_str(&add_item->meta), "spinbox") == 0); TWEAK_LOG_TEST("add_item->meta is correct\n"); TEST_CHECK(strcmp(tweak_variant_string_c_str(&add_item->description), "First control") == 0); TWEAK_LOG_TEST("add_item->description is correct\n"); TEST_CHECK(add_item->current_value.type == TWEAK_VARIANT_TYPE_FLOAT); TWEAK_LOG_TEST("add_item->current_value.type is correct\n"); TEST_CHECK(add_item->current_value.value.fp32 == 17.f); TWEAK_LOG_TEST("add_item->current_value.fp32 is correct\n"); notify_answer_received(); } static void handle_server_remove_tweak(tweak_pickle_remove_item* pickle_remove_item, void *cookie) { (void)cookie; TEST_CHECK(pickle_remove_item->tweak_id == 42); TWEAK_LOG_TEST("remove tweak_id is correct\n"); notify_answer_received(); } static tweak_variant_string create_variant_string(const char* arg) { tweak_variant_string rv = { 0 }; tweak_variant_assign_string(&rv, arg); return rv; } void test_pickle() { srand(time(NULL)); int port = 32769 + rand() % 20000; char uri0[256]; snprintf(uri0, sizeof(uri0), "tcp://0.0.0.0:%d/", port); reset_answer_count(2); pthread_mutex_init(&lock, NULL); pthread_cond_init(&cond, NULL); tweak_pickle_server_descriptor server_descriptor = { .context_type = "nng", .uri = uri0, .params = "role=server", .skeleton = { .connection_state_listener = { .callback = &connection_state_listener_impl }, .subscribe_listener = { .callback = &handle_subscribe_impl }, .change_item_listener = { .callback = &handle_client_change_tweak_impl } } }; tweak_pickle_server_endpoint sep = tweak_pickle_create_server_endpoint(&server_descriptor); TEST_CHECK(sep != NULL); tweak_pickle_client_descriptor client_descriptor = { .context_type = "nng", .uri = uri0, .params = "role=client", .skeleton = { .connection_state_listener = { .callback = &connection_state_listener_impl }, .add_item_listener = { .callback = &handle_add_item_impl }, .change_item_listener = { .callback = &handle_server_change_tweak_impl }, .remove_item_listener = { .callback = &handle_server_remove_tweak } } }; reset_answer_count(1); tweak_pickle_client_endpoint cep = tweak_pickle_create_client_endpoint(&client_descriptor); TEST_CHECK(sep != NULL); wait_answers(); tweak_pickle_add_item new_item = { .uri = create_variant_string("X"), .tweak_id = 26, .meta = create_variant_string("spinbox"), .description = create_variant_string("First control"), .default_value = { .type = TWEAK_VARIANT_TYPE_FLOAT, .value = { .fp32 = 3.f } }, .current_value = { .type = TWEAK_VARIANT_TYPE_FLOAT, .value = { .fp32 = 17.f } } }; tweak_pickle_change_item change_item = { .tweak_id = 17, .value = { .type = TWEAK_VARIANT_TYPE_FLOAT, .value = { .fp32 = 36.f } } }; tweak_pickle_change_item change_item_client = { .tweak_id = 11, .value = { .type = TWEAK_VARIANT_TYPE_FLOAT, .value = { .fp32 = 32.f } } }; reset_answer_count(1); TWEAK_LOG_TEST("test server_add_item..."); tweak_pickle_server_add_item(sep, &new_item); wait_answers(); TWEAK_LOG_TEST("DONE\n"); reset_answer_count(1); TWEAK_LOG_TEST("test push_item_changes..."); tweak_pickle_server_change_item(sep, &change_item); wait_answers(); TWEAK_LOG_TEST("DONE\n"); reset_answer_count(1); TWEAK_LOG_TEST("test remove_item..."); tweak_pickle_remove_item pickle_remove_item = { .tweak_id = 42 }; tweak_pickle_server_remove_item(sep, &pickle_remove_item); wait_answers(); TWEAK_LOG_TEST("DONE\n"); reset_answer_count(1); TWEAK_LOG_TEST("test client_subscribe..."); tweak_pickle_client_subscribe(cep, NULL); wait_answers(); TWEAK_LOG_TEST("DONE\n"); reset_answer_count(1); TWEAK_LOG_TEST("test client_change_item..."); tweak_pickle_client_change_item(cep, &change_item_client); wait_answers(); TWEAK_LOG_TEST("DONE\n"); tweak_pickle_destroy_client_endpoint(cep); tweak_pickle_destroy_server_endpoint(sep); pthread_cond_destroy(&cond); pthread_mutex_destroy(&lock); } TEST_LIST = { { "test-pickle", test_pickle }, { NULL, NULL } /* zeroed record marking the end of the list */ };
highlands/formulae
app/models/question_dependency.rb
# frozen_string_literal: true class QuestionDependency < ApplicationRecord include Uuidable belongs_to :question has_many :question_dependency_choices, dependent: :destroy accepts_nested_attributes_for :question_dependency_choices, allow_destroy: true end
TinyPlanetStudios/Project-Crash-Land
export/windows/cpp/obj/src/openfl/events/IOErrorEvent.cpp
<reponame>TinyPlanetStudios/Project-Crash-Land // Generated by Haxe 3.3.0 #include <hxcpp.h> #ifndef INCLUDED_openfl__legacy_events_Event #include <openfl/_legacy/events/Event.h> #endif #ifndef INCLUDED_openfl_events_ErrorEvent #include <openfl/events/ErrorEvent.h> #endif #ifndef INCLUDED_openfl_events_IOErrorEvent #include <openfl/events/IOErrorEvent.h> #endif #ifndef INCLUDED_openfl_events_TextEvent #include <openfl/events/TextEvent.h> #endif static const ::String _hx_array_data_0[] = { HX_("type",ba,f2,08,4d),HX_("bubbles",67,bb,56,61),HX_("cancelable",14,a0,79,c4),HX_("text",ad,cc,f9,4c),HX_("errorID",a3,8d,0a,ea), }; namespace openfl{ namespace events{ void IOErrorEvent_obj::__construct(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable,::String __o_text,hx::Null< Int > __o_id){ Bool bubbles = __o_bubbles.Default(true); Bool cancelable = __o_cancelable.Default(false); ::String text = __o_text.Default(HX_HCSTRING("","\x00","\x00","\x00","\x00")); Int id = __o_id.Default(0); HX_STACK_FRAME("openfl.events.IOErrorEvent","new",0x69722dc1,"openfl.events.IOErrorEvent.new","openfl/events/IOErrorEvent.hx",12,0x9ba976af) HX_STACK_THIS(this) HX_STACK_ARG(type,"type") HX_STACK_ARG(bubbles,"bubbles") HX_STACK_ARG(cancelable,"cancelable") HX_STACK_ARG(text,"text") HX_STACK_ARG(id,"id") HXLINE( 12) super::__construct(type,bubbles,cancelable,text,id); } Dynamic IOErrorEvent_obj::__CreateEmpty() { return new IOErrorEvent_obj; } hx::ObjectPtr< IOErrorEvent_obj > IOErrorEvent_obj::__new(::String type,hx::Null< Bool > __o_bubbles,hx::Null< Bool > __o_cancelable,::String __o_text,hx::Null< Int > __o_id) { hx::ObjectPtr< IOErrorEvent_obj > _hx_result = new IOErrorEvent_obj(); _hx_result->__construct(type,__o_bubbles,__o_cancelable,__o_text,__o_id); return _hx_result; } Dynamic IOErrorEvent_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< IOErrorEvent_obj > _hx_result = new IOErrorEvent_obj(); _hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]); return _hx_result; } ::openfl::_legacy::events::Event IOErrorEvent_obj::clone(){ HX_STACK_FRAME("openfl.events.IOErrorEvent","clone",0xfbdc4afe,"openfl.events.IOErrorEvent.clone","openfl/events/IOErrorEvent.hx",17,0x9ba976af) HX_STACK_THIS(this) HXLINE( 19) ::String _hx_tmp = this->get_type(); HXDLIN( 19) Bool _hx_tmp1 = this->get_bubbles(); HXDLIN( 19) Bool _hx_tmp2 = this->get_cancelable(); HXDLIN( 19) HX_VARI( ::openfl::events::IOErrorEvent,event) = ::openfl::events::IOErrorEvent_obj::__new(_hx_tmp,_hx_tmp1,_hx_tmp2,this->text,this->errorID); HXLINE( 20) ::Dynamic _hx_tmp3 = this->get_target(); HXDLIN( 20) event->set_target(_hx_tmp3); HXLINE( 21) ::Dynamic _hx_tmp4 = this->get_currentTarget(); HXDLIN( 21) event->set_currentTarget(_hx_tmp4); HXLINE( 25) return event; } ::String IOErrorEvent_obj::toString(){ HX_STACK_FRAME("openfl.events.IOErrorEvent","toString",0xfbbd53ab,"openfl.events.IOErrorEvent.toString","openfl/events/IOErrorEvent.hx",32,0x9ba976af) HX_STACK_THIS(this) HXLINE( 32) return this->_hx___formatToString(HX_("IOErrorEvent",b8,16,b3,65),::Array_obj< ::String >::fromData( _hx_array_data_0,5)); } ::String IOErrorEvent_obj::IO_ERROR; IOErrorEvent_obj::IOErrorEvent_obj() { } hx::Val IOErrorEvent_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); } break; case 8: if (HX_FIELD_EQ(inName,"toString") ) { return hx::Val( toString_dyn()); } } return super::__Field(inName,inCallProp); } #if HXCPP_SCRIPTABLE static hx::StorageInfo *IOErrorEvent_obj_sMemberStorageInfo = 0; static hx::StaticInfo IOErrorEvent_obj_sStaticStorageInfo[] = { {hx::fsString,(void *) &IOErrorEvent_obj::IO_ERROR,HX_HCSTRING("IO_ERROR","\x4f","\x7b","\x81","\x11")}, { hx::fsUnknown, 0, null()} }; #endif static ::String IOErrorEvent_obj_sMemberFields[] = { HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"), HX_HCSTRING("toString","\xac","\xd0","\x6e","\x38"), ::String(null()) }; static void IOErrorEvent_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(IOErrorEvent_obj::__mClass,"__mClass"); HX_MARK_MEMBER_NAME(IOErrorEvent_obj::IO_ERROR,"IO_ERROR"); }; #ifdef HXCPP_VISIT_ALLOCS static void IOErrorEvent_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(IOErrorEvent_obj::__mClass,"__mClass"); HX_VISIT_MEMBER_NAME(IOErrorEvent_obj::IO_ERROR,"IO_ERROR"); }; #endif hx::Class IOErrorEvent_obj::__mClass; static ::String IOErrorEvent_obj_sStaticFields[] = { HX_HCSTRING("IO_ERROR","\x4f","\x7b","\x81","\x11"), ::String(null()) }; void IOErrorEvent_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl.events.IOErrorEvent","\x4f","\x39","\xfe","\x1f"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = IOErrorEvent_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(IOErrorEvent_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(IOErrorEvent_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< IOErrorEvent_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = IOErrorEvent_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = IOErrorEvent_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = IOErrorEvent_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void IOErrorEvent_obj::__boot() { { HX_STACK_FRAME("openfl.events.IOErrorEvent","boot",0xd28edbb1,"openfl.events.IOErrorEvent.boot","openfl/events/IOErrorEvent.hx",7,0x9ba976af) HXLINE( 7) IO_ERROR = HX_("ioError",02,fe,41,76); } } } // end namespace openfl } // end namespace events
VladimirAnaniev/JS-Web
ReactJS-Fundamentals/Hotels-System/frontend/src/auth/login/Login.js
import React, {Component} from 'react' import {connect} from 'react-redux' import LoginForm from './LoginForm' import { changeLoginForm, login } from '../authActions' import FormHelper from '../../utils/formHelper' class Login extends Component { onFormChange = event => { let newState = FormHelper.handleFormChange(event, this.props.formState) this.props.onFormChange(newState) } onFormSubmit = event => { event.preventDefault() this.props.onFormSubmit(this.props.formState) } render () { const {formState} = this.props return ( <div> <LoginForm formState={formState} onChange={this.onFormChange} onSubmit={this.onFormSubmit} /> </div> ) } } const mapStateToProps = (state) => { return { formState: state.auth.loginForm } } const mapDispatchToProps = (dispatch, ownProps) => { return { onFormChange: newState => { dispatch(changeLoginForm(newState)) }, onFormSubmit: user => { dispatch(login(user)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Login)
Dbevan/SunderingShadows
d/realm/inherits/mr_mh_i.c
#include <std.h> #include <area_stuff.h> #include <daemons.h> inherit RA_MR_HALL; string wwall, hidden_room; void create() { ::create(); } void init() { ::init(); add_action("enter_mural", "enter"); } void reset() { ::reset(); } int enter_mural(string arg) { object hidroom; if(!arg && arg != "mural") return 0; if(!objectp(TP)) return 0; tell_room(TO, TPQCN+"%^BOLD%^%^WHITE%^ walks up to a mural on the "+ wwall + " wall and steps through it!%^RESET%^", TP); tell_object(TP, "%^BOLD%^%^WHITE%^You walk up a mural on the "+wwall+ " wall and step through it!%^RESET%^"); hidroom = find_object_or_load(hidden_room); if(!objectp(hidroom)) { tell_object(TP, "%^B_CYAN%^%^BOLD%^%^GREEN%^Could not find "+ "the destination room - please let Saide know - do <bug here>"); return 1; } tell_room(hidroom, "%^BOLD%^%^WHITE%^Steps out from one of the "+ "murals!%^RESET%^", TP); TP->move_player(hidroom); return 1; } int mural_search(string ob) { if(!objectp(TP)) return 0; if(!objectp(TO)) return 0; tell_room(TO, TPQCN +"%^BOLD%^%^BLUE%^ searches the murals "+ "carefully!%^RESET%^", TP); tell_object(TP, "%^BOLD%^%^BLUE%^You search over the murals "+ "carefully and realize that one of them on the "+wwall+ " wall is actually a portal, you could %^BOLD%^%^WHITE%^"+ "enter%^BOLD%^%^BLUE%^ it, if you were brave enough.%^RESET%^"); return 1; }
shamblett/axis2c-unofficial
guththila/tests/test_utf8_decoder.c
<gh_stars>10-100 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <guththila.h> #include <check.h> #include <string.h> #include "test.h" static guththila_utf8_decoder_t *decoder = NULL; void setup_utf8_decoder( void) { allocator = axutil_allocator_init(NULL); env = axutil_env_create(allocator); decoder = guththila_utf8_decoder_create(env); } void teardown_utf8_decoder( void) { guththila_utf8_decoder_free(decoder, env); axutil_env_free(env); } START_TEST(test_decode_1_byte_letter) { int code_point; int is_done = guththila_utf8_decoder_decode(decoder, 'A', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 'A', "guththila code_point not A"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 'A', "guththila decoder code_point not A"); } END_TEST START_TEST(test_decode_2_byte_letter) { // Greek Alpha: Code point: 913 UTF-8: \xCE\x91 int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xCE', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x91', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 913, "guththila code_point not Greek alpha"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 913, "guththila decoder code_point not Greek alpha"); } END_TEST START_TEST(test_decode_3_byte_letter) { // Thai Sara U: Code point: 3640 UTF-8: \xE0\xB8\xB8 int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xE0', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xB8', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xB8', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 3640, "guththila code_point not Thai Sara U"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 3640, "guththila decoder code_point not Thai Sara U"); } END_TEST START_TEST(test_decode_4_byte_letter) { // Chinese Treestump: Code point: 144308 UTF-8: \xF0\xA3\x8E\xB4 int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xF0', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xA3', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x8E', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xB4', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 144308, "guththila code_point not Chinese Treestump"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 144308, "guththila decoder code_point not Chinese Treestump"); } END_TEST START_TEST(test_decode_1_byte_lower_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * From 0 0x00000000 0000 0000 0000 0000 0000 0000 * 0 * 0x00 * 0000 0000 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\0', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x00000000, "guththila code_point not 0x00000000"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x00000000, "guththila decoder code_point not 0x00000000"); } END_TEST START_TEST(test_decode_1_byte_upper_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 127 0x0000007f 0000 0000 0000 0000 0111 1111 * 127 * 0x7f * 0111 1111 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\x7F', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x0000007f, "guththila code_point not 0x0000007f"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x0000007f, "guththila decoder code_point not 0x0000007f"); } END_TEST START_TEST(test_decode_2_byte_lower_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * From 128 0x00000080 0000 0000 0000 0000 1000 0000 * 194 128 * 0xc2 0x80 * 1100 0010 1000 0000 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xC2', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x00000080, "guththila code_point not 0x00000080"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x00000080, "guththila decoder code_point not 0x00000080"); } END_TEST START_TEST(test_decode_2_byte_upper_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 2,047 0x000007ff 0000 0000 0000 0111 1111 1111 * 223 191 * 0xdf 0xbf * 1101 1111 1011 1111 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xDF', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xBF', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x000007ff, "guththila code_point not 0x000007ff"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x000007ff, "guththila decoder code_point not 0x000007ff"); } END_TEST START_TEST(test_decode_3_byte_lower_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * From 2,048 0x00000800 0000 0000 0000 1000 0000 0000 * 224 160 128 * 0xe0 0xa0 0x80 * 1110 0000 1010 0000 1000 0000 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xE0', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xA0', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x00000800, "guththila code_point not 0x00000800"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x00000800, "guththila decoder code_point not 0x00000800"); } END_TEST START_TEST(test_decode_3_byte_upper_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 65,535 0x0000ffff 0000 0000 1111 1111 1111 1111 * 239 191 191 * 0xef 0xbf 0xbf * 1110 1111 1011 1111 1011 1111 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xEF', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xBF', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xBF', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x0000ffff, "guththila code_point not 0x0000ffff"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x0000ffff, "guththila decoder code_point not 0x0000ffff"); } END_TEST START_TEST(test_decode_4_byte_lower_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * From 65,536 0x00010000 0000 0001 0000 0000 0000 0000 * 240 144 128 128 * 0xf0 0x90 0x80 0x80 * 1111 0000 1001 0000 1000 0000 1000 0000 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xF0', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x90', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x00010000, "guththila code_point not 0x00010000"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x00010000, "guththila decoder code_point not 0x00010000"); } END_TEST START_TEST(test_decode_4_byte_upper_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 1,114,111 0x0010ffff 0001 0000 1111 1111 1111 1111 * 244 143 191 191 * 0xf4 0x8f 0xbf 0xbf * 1111 0100 1000 1111 1011 1111 1011 1111 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xF4', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x8F', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xBF', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\xBF', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 0x0010ffff, "guththila code_point not 0x0010ffff"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 0x0010ffff, "guththila decoder code_point not 0x0010ffff"); } END_TEST START_TEST(test_decode_2_byte_overlong) { // Overlong 0x0000: \xC0\x80 int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xC0', &code_point, env); fail_if(is_done == 0, "guththila decoder is not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) == 0, "guththila decoder not detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder has code point"); } END_TEST START_TEST(test_decode_4_byte_over_upper_bound) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 1,114,112 0x00110000 0001 0001 0000 0000 0000 0000 * 244 143 128 128 * 0xf4 0x90 0x80 0x80 * 1111 0100 1001 0000 1000 0000 1000 0000 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xF4', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x90', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, '\x80', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) == 0, "guththila decoder not detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder has code point"); } END_TEST START_TEST(test_decode_2_byte_missing_continuation) { /* * Code Point * Decimal Hex Binary * UTF-8 Encoding * To 2,047 0x000007ff 0000 0000 0000 0111 1111 1111 * 223 191 * 0xdf 0xbf * 1101 1111 1011 1111 */ int code_point; int is_done = guththila_utf8_decoder_decode(decoder, '\xDF', &code_point, env); fail_if(is_done != 0, "guththila decoder already done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); is_done = guththila_utf8_decoder_decode(decoder, 'A', &code_point, env); fail_if(is_done == 0, "guththila decoder not done"); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) == 0, "guththila decoder not detected error"); fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); fail_if(code_point != 'A', "guththila code_point not A"); fail_if(GUTHTHILA_UTF8_DECODER_GET_CODE_POINT(decoder) != 'A', "guththila decoder code_point not A"); } END_TEST START_TEST(test_encode_decode_all_1_to_3_byte) { int code_point; guththila_utf8_encoder_t *encoder = guththila_utf8_encoder_create(env); for (code_point = 0; code_point <= 0x0000ffff; code_point++) { //fprintf(stderr, "CODE POINT: %d\n", code_point); guththila_char_t buffer[10]; int buffer_length = 10; int is_done = guththila_utf8_encoder_encode(encoder, code_point, buffer, &buffer_length, env); fail_if(is_done == 0, "guththila encoder is not done"); fail_if(GUTHTHILA_UTF8_ENCODER_IS_ERROR(encoder) != 0, "guththila encoder detected error"); fail_if(GUTHTHILA_UTF8_ENCODER_IS_BUFFERED(encoder) == 0, "guththila encoder has no buffer space"); int encoded_length = 10 - buffer_length; int decoded_code_point = 0; int index; //fprintf(stderr, "Encoding: %d = ", encoded_length); //for (index = 0; index < encoded_length; index++) //{ // fprintf(stderr, " %02x", (0x00ff & buffer[index])); //} //fprintf(stderr, "\n"); for (index = 0; index < encoded_length; index++) { is_done = guththila_utf8_decoder_decode(decoder, buffer[index], &decoded_code_point, env); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); if (index == encoded_length - 1) { fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); } else { fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); } } fail_if(decoded_code_point != code_point, "guththila decoded code point not the same"); } guththila_utf8_encoder_free(encoder, env); } END_TEST START_TEST(test_encode_decode_all_4_byte) { int code_point; guththila_utf8_encoder_t *encoder = guththila_utf8_encoder_create(env); for (code_point = 0x00010000; code_point <= 0x0010ffff; code_point++) { //fprintf(stderr, "CODE POINT: %d\n", code_point); guththila_char_t buffer[10]; int buffer_length = 10; int is_done = guththila_utf8_encoder_encode(encoder, code_point, buffer, &buffer_length, env); fail_if(is_done == 0, "guththila encoder is not done"); fail_if(GUTHTHILA_UTF8_ENCODER_IS_ERROR(encoder) != 0, "guththila encoder detected error"); fail_if(GUTHTHILA_UTF8_ENCODER_IS_BUFFERED(encoder) == 0, "guththila encoder has no buffer space"); int encoded_length = 10 - buffer_length; int decoded_code_point = 0; int index; //fprintf(stderr, "Encoding: %d = ", encoded_length); //for (index = 0; index < encoded_length; index++) //{ // fprintf(stderr, " %02x", (0x00ff & buffer[index])); //} //fprintf(stderr, "\n"); for (index = 0; index < encoded_length; index++) { is_done = guththila_utf8_decoder_decode(decoder, buffer[index], &decoded_code_point, env); fail_if(GUTHTHILA_UTF8_DECODER_IS_ERROR(decoder) != 0, "guththila decoder detected error"); if (index == encoded_length - 1) { fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) == 0, "guththila decoder has no code point"); } else { fail_if(GUTHTHILA_UTF8_DECODER_IS_CODE_POINT(decoder) != 0, "guththila decoder already has code point"); } } fail_if(decoded_code_point != code_point, "guththila decoded code point not the same"); } guththila_utf8_encoder_free(encoder, env); } END_TEST Suite * guththila_utf8_decoder_suite(void) { Suite *s = suite_create("Guththila_utf8_decoder"); /* Core test case */ TCase *tc_core = tcase_create("utf8_decoder"); tcase_add_checked_fixture(tc_core, setup_utf8_decoder, teardown_utf8_decoder); tcase_add_test(tc_core, test_decode_1_byte_letter); tcase_add_test(tc_core, test_decode_2_byte_letter); tcase_add_test(tc_core, test_decode_3_byte_letter); tcase_add_test(tc_core, test_decode_4_byte_letter); tcase_add_test(tc_core, test_decode_1_byte_lower_bound); tcase_add_test(tc_core, test_decode_1_byte_upper_bound); tcase_add_test(tc_core, test_decode_2_byte_lower_bound); tcase_add_test(tc_core, test_decode_2_byte_upper_bound); tcase_add_test(tc_core, test_decode_3_byte_lower_bound); tcase_add_test(tc_core, test_decode_3_byte_upper_bound); tcase_add_test(tc_core, test_decode_4_byte_lower_bound); tcase_add_test(tc_core, test_decode_4_byte_upper_bound); tcase_add_test(tc_core, test_decode_2_byte_overlong); tcase_add_test(tc_core, test_decode_4_byte_over_upper_bound); tcase_add_test(tc_core, test_decode_2_byte_missing_continuation); tcase_add_test(tc_core, test_encode_decode_all_1_to_3_byte); tcase_set_timeout(tc_core, 600); tcase_add_test(tc_core, test_encode_decode_all_4_byte); suite_add_tcase(s, tc_core); return s; }
bitriddler/graphql-relay-starter
server/auth/repositories/UserRepository.js
<gh_stars>0 const IoC = require('AppIoC'); const ValidationError = require( '@server/errors/ValidationError'); const ForbiddenError = require( '@server/errors/ForbiddenError'); const UnauthorizedError = require( '@server/errors/UnauthorizedError'); class UserRepository { constructor(userModel) { this.userModel = userModel; } /** * Use this method to query users * @param {User} viewer * @param {object} inputs * @return {Promise<User[]>} * @throws {ForbiddenError} If not an admin */ async query(viewer, inputs) { // Guests cant query users if(viewer.isGuest()) { throw new UnauthorizedError(`You must login to make this request`); } // Only admins can query users if(! viewer.isAdmin()) { throw new ForbiddenError(`You dont have access to query users`); } // Create a new query const query = this.userModel.find(); // Search users by email if(inputs.email) { query.where('email', inputs.email); } // return query executed promise return query.exec(); } /** * Find user by id * @param {User} viewer * @param {ObjectId} id * @return {Promise<User>} * @throws {ForbiddenError} If not an admin */ async findById(viewer, id) { // Guests cant query users if(viewer.isGuest()) { throw new UnauthorizedError(`You must login to make this request`); } // Only admins can query users if(! viewer.isAdmin()) { throw new ForbiddenError(`You dont have access to query users`); } // Find user by id return this.userModel.findById(id).exec(); } /** * Get viewer by email and password * @param {string} email * @param {string} password * @return {Promise<User>} * @throws {ValidationError} If invalid credentials */ async getViewer(email, password) { // Get user by email const user = await this.userModel.findOne({ email }).exec(); // Throw error if he doesnt exist if(! user) { throw new ValidationError({ email: "No user with this email" }); } // Check the user password const verified = await user.verifyPassword(password); // Throw error if password is incorrect if(! verified) { throw new ValidationError({ password: "<PASSWORD>" }); } return user; } /** * Create a new user * @param {User} viewer * @param {Object} attributes * @return {Promise<User>} */ async update(viewer, user, attributes) { // Guests cant create users if(viewer.isGuest()) { throw new UnauthorizedError(`You must login to make this request`); } // Only admins can update users if(! viewer.isAdmin()) { throw new ForbiddenError(`You dont have access to update users`); } user.set(attributes); return user.save(attributes); } /** * Create a new user * @param {User} viewer * @param {Object} attributes * @return {Promise<User>} */ async create(viewer, attributes) { // Guests cant create users if(viewer.isGuest()) { throw new UnauthorizedError(`You must login to make this request`); } // Only admins can create users if(! viewer.isAdmin()) { throw new ForbiddenError(`You dont have access to create users`); } // Create the user return this.userModel.create(attributes); } /** * Remove user by id * @param {User} viewer * @param {ObjectId} id */ async remove(viewer, id) { // Guests cant remove users if(viewer.isGuest()) { throw new UnauthorizedError(`You must login to make this request`); } // Only admins can remove users if(! viewer.isAdmin()) { throw new ForbiddenError(`You dont have access to query users`); } return this.userModel.remove({ _id: id }).exec(); } } IoC.singleton('auth.userRepository', [ 'auth.userModel', ], UserRepository);
xiabee/BIT-CS
C语言程序设计基础/选择题.cpp
<filename>C语言程序设计基础/选择题.cpp struct sk { int a; float b; }data,*p=&data; int main() { (*p).a; }
cegganesh84/hive
ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java
<gh_stars>10-100 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.optimizer.ppr; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.Warehouse; import org.apache.hadoop.hive.ql.exec.FunctionRegistry; import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker; import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher; import org.apache.hadoop.hive.ql.lib.Dispatcher; import org.apache.hadoop.hive.ql.lib.GraphWalker; import org.apache.hadoop.hive.ql.lib.Node; import org.apache.hadoop.hive.ql.lib.NodeProcessor; import org.apache.hadoop.hive.ql.lib.Rule; import org.apache.hadoop.hive.ql.lib.RuleRegExp; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.optimizer.Transform; import org.apache.hadoop.hive.ql.parse.ErrorMsg; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.parse.PrunedPartitionList; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; /** * The transformation step that does partition pruning. * */ public class PartitionPruner implements Transform { // The log private static final Log LOG = LogFactory .getLog("hive.ql.optimizer.ppr.PartitionPruner"); /* * (non-Javadoc) * * @see * org.apache.hadoop.hive.ql.optimizer.Transform#transform(org.apache.hadoop * .hive.ql.parse.ParseContext) */ @Override public ParseContext transform(ParseContext pctx) throws SemanticException { // create a the context for walking operators OpWalkerCtx opWalkerCtx = new OpWalkerCtx(pctx.getOpToPartPruner()); Map<Rule, NodeProcessor> opRules = new LinkedHashMap<Rule, NodeProcessor>(); opRules.put(new RuleRegExp("R1", "(TS%FIL%)|(TS%FIL%FIL%)"), OpProcFactory .getFilterProc()); // The dispatcher fires the processor corresponding to the closest matching // rule and passes the context along Dispatcher disp = new DefaultRuleDispatcher(OpProcFactory.getDefaultProc(), opRules, opWalkerCtx); GraphWalker ogw = new DefaultGraphWalker(disp); // Create a list of topop nodes ArrayList<Node> topNodes = new ArrayList<Node>(); topNodes.addAll(pctx.getTopOps().values()); ogw.startWalking(topNodes, null); pctx.setHasNonPartCols(opWalkerCtx.getHasNonPartCols()); return pctx; } /** * Find out whether the condition only contains partitioned columns. Note that * if the table is not partitioned, the function always returns true. * condition. * * @param tab * the table object * @param expr * the pruner expression for the table */ public static boolean onlyContainsPartnCols(Table tab, ExprNodeDesc expr) { if (!tab.isPartitioned() || (expr == null)) { return true; } if (expr instanceof ExprNodeColumnDesc) { String colName = ((ExprNodeColumnDesc) expr).getColumn(); return tab.isPartitionKey(colName); } // It cannot contain a non-deterministic function if ((expr instanceof ExprNodeGenericFuncDesc) && !FunctionRegistry.isDeterministic(((ExprNodeGenericFuncDesc) expr) .getGenericUDF())) { return false; } // All columns of the expression must be parttioned columns List<ExprNodeDesc> children = expr.getChildren(); if (children != null) { for (int i = 0; i < children.size(); i++) { if (!onlyContainsPartnCols(tab, children.get(i))) { return false; } } } return true; } /** * Get the partition list for the table that satisfies the partition pruner * condition. * * @param tab * the table object for the alias * @param prunerExpr * the pruner expression for the alias * @param conf * for checking whether "strict" mode is on. * @param alias * for generating error message only. * @return the partition list for the table that satisfies the partition * pruner condition. * @throws HiveException */ public static PrunedPartitionList prune(Table tab, ExprNodeDesc prunerExpr, HiveConf conf, String alias, Map<String, PrunedPartitionList> prunedPartitionsMap) throws HiveException { LOG.trace("Started pruning partiton"); LOG.trace("tabname = " + tab.getTableName()); LOG.trace("prune Expression = " + prunerExpr); String key = tab.getTableName() + ";"; if (prunerExpr != null) { key = key + prunerExpr.getExprString(); } PrunedPartitionList ret = prunedPartitionsMap.get(key); if (ret != null) { return ret; } LinkedHashSet<Partition> true_parts = new LinkedHashSet<Partition>(); LinkedHashSet<Partition> unkn_parts = new LinkedHashSet<Partition>(); LinkedHashSet<Partition> denied_parts = new LinkedHashSet<Partition>(); try { StructObjectInspector rowObjectInspector = (StructObjectInspector) tab .getDeserializer().getObjectInspector(); Object[] rowWithPart = new Object[2]; if (tab.isPartitioned()) { LOG.debug("tabname = " + tab.getTableName() + " is partitioned"); for (String partName : Hive.get().getPartitionNames(tab.getDbName(), tab.getTableName(), (short) -1)) { // If the "strict" mode is on, we have to provide partition pruner for // each table. if ("strict".equalsIgnoreCase(HiveConf.getVar(conf, HiveConf.ConfVars.HIVEMAPREDMODE))) { if (!hasColumnExpr(prunerExpr)) { throw new SemanticException(ErrorMsg.NO_PARTITION_PREDICATE .getMsg("for Alias \"" + alias + "\" Table \"" + tab.getTableName() + "\"")); } } // Set all the variables here LinkedHashMap<String, String> partSpec = Warehouse .makeSpecFromName(partName); LOG.trace("about to process partition " + partSpec + " for pruning "); // evaluate the expression tree if (prunerExpr != null) { Boolean r = (Boolean) PartExprEvalUtils.evalExprWithPart(prunerExpr, partSpec, rowObjectInspector); LOG.trace("prune result for partition " + partSpec + ": " + r); if (Boolean.FALSE.equals(r)) { if (denied_parts.isEmpty()) { Partition part = Hive.get().getPartition(tab, partSpec, Boolean.FALSE); denied_parts.add(part); } LOG.trace("pruned partition: " + partSpec); } else { Partition part = Hive.get().getPartition(tab, partSpec, Boolean.FALSE); String state = "retained"; if (Boolean.TRUE.equals(r)) { true_parts.add(part); } else { unkn_parts.add(part); state = "unknown"; } if (LOG.isDebugEnabled()) { LOG.debug(state + " partition: " + partSpec); } } } else { // is there is no parition pruning, all of them are needed true_parts.add(Hive.get() .getPartition(tab, partSpec, Boolean.FALSE)); } } } else { true_parts.addAll(Hive.get().getPartitions(tab)); } } catch (HiveException e) { throw e; } catch (Exception e) { throw new HiveException(e); } // Now return the set of partitions ret = new PrunedPartitionList(true_parts, unkn_parts, denied_parts); prunedPartitionsMap.put(key, ret); return ret; } /** * Whether the expression contains a column node or not. */ public static boolean hasColumnExpr(ExprNodeDesc desc) { // Return false for null if (desc == null) { return false; } // Return true for exprNodeColumnDesc if (desc instanceof ExprNodeColumnDesc) { return true; } // Return true in case one of the children is column expr. List<ExprNodeDesc> children = desc.getChildren(); if (children != null) { for (int i = 0; i < children.size(); i++) { if (hasColumnExpr(children.get(i))) { return true; } } } // Return false otherwise return false; } }
poviliukas/openldap
servers/slapd/back-monitor/entry.c
/* entry.c - monitor backend entry handling routines */ /* $OpenLDAP$ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 2001-2012 The OpenLDAP Foundation. * Portions Copyright 2001-2003 <NAME>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ /* ACKNOWLEDGEMENTS: * This work was initially developed by <NAME> for inclusion * in OpenLDAP Software. */ #include "portable.h" #include <slap.h> #include "back-monitor.h" int monitor_entry_update( Operation *op, SlapReply *rs, Entry *e ) { monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; monitor_entry_t *mp; int rc = SLAP_CB_CONTINUE; assert( mi != NULL ); assert( e != NULL ); assert( e->e_private != NULL ); mp = ( monitor_entry_t * )e->e_private; if ( mp->mp_cb ) { struct monitor_callback_t *mc; for ( mc = mp->mp_cb; mc; mc = mc->mc_next ) { if ( mc->mc_update ) { rc = mc->mc_update( op, rs, e, mc->mc_private ); if ( rc != SLAP_CB_CONTINUE ) { break; } } } } if ( rc == SLAP_CB_CONTINUE && mp->mp_info && mp->mp_info->mss_update ) { rc = mp->mp_info->mss_update( op, rs, e ); } if ( rc == SLAP_CB_CONTINUE ) { rc = LDAP_SUCCESS; } return rc; } int monitor_entry_create( Operation *op, SlapReply *rs, struct berval *ndn, Entry *e_parent, Entry **ep ) { monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; monitor_entry_t *mp; int rc = SLAP_CB_CONTINUE; assert( mi != NULL ); assert( e_parent != NULL ); assert( e_parent->e_private != NULL ); assert( ep != NULL ); mp = ( monitor_entry_t * )e_parent->e_private; if ( mp->mp_info && mp->mp_info->mss_create ) { rc = mp->mp_info->mss_create( op, rs, ndn, e_parent, ep ); } if ( rc == SLAP_CB_CONTINUE ) { rc = LDAP_SUCCESS; } return rc; } int monitor_entry_modify( Operation *op, SlapReply *rs, Entry *e ) { monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; monitor_entry_t *mp; int rc = SLAP_CB_CONTINUE; assert( mi != NULL ); assert( e != NULL ); assert( e->e_private != NULL ); mp = ( monitor_entry_t * )e->e_private; if ( mp->mp_cb ) { struct monitor_callback_t *mc; for ( mc = mp->mp_cb; mc; mc = mc->mc_next ) { if ( mc->mc_modify ) { rc = mc->mc_modify( op, rs, e, mc->mc_private ); if ( rc != SLAP_CB_CONTINUE ) { break; } } } } if ( rc == SLAP_CB_CONTINUE && mp->mp_info && mp->mp_info->mss_modify ) { rc = mp->mp_info->mss_modify( op, rs, e ); } if ( rc == SLAP_CB_CONTINUE ) { rc = LDAP_SUCCESS; } return rc; } int monitor_entry_test_flags( monitor_entry_t *mp, int cond ) { assert( mp != NULL ); return( ( mp->mp_flags & cond ) || ( mp->mp_info->mss_flags & cond ) ); } monitor_entry_t * monitor_back_entrypriv_create( void ) { monitor_entry_t *mp; mp = ( monitor_entry_t * )ch_calloc( sizeof( monitor_entry_t ), 1 ); mp->mp_next = NULL; mp->mp_children = NULL; mp->mp_info = NULL; mp->mp_flags = MONITOR_F_NONE; mp->mp_cb = NULL; ldap_pvt_thread_mutex_init( &mp->mp_mutex ); return mp; } Entry * monitor_entry_stub( struct berval *pdn, struct berval *pndn, struct berval *rdn, ObjectClass *oc, struct berval *create, struct berval *modify ) { monitor_info_t *mi; AttributeDescription *nad = NULL; Entry *e; struct berval nat; char *ptr; const char *text; int rc; mi = ( monitor_info_t * )be_monitor->be_private; nat = *rdn; ptr = strchr( nat.bv_val, '=' ); nat.bv_len = ptr - nat.bv_val; rc = slap_bv2ad( &nat, &nad, &text ); if ( rc ) return NULL; e = entry_alloc(); if ( e ) { struct berval nrdn; rdnNormalize( 0, NULL, NULL, rdn, &nrdn, NULL ); build_new_dn( &e->e_name, pdn, rdn, NULL ); build_new_dn( &e->e_nname, pndn, &nrdn, NULL ); ber_memfree( nrdn.bv_val ); nat.bv_val = ptr + 1; nat.bv_len = rdn->bv_len - ( nat.bv_val - rdn->bv_val ); attr_merge_normalize_one( e, slap_schema.si_ad_objectClass, &oc->soc_cname, NULL ); attr_merge_normalize_one( e, slap_schema.si_ad_structuralObjectClass, &oc->soc_cname, NULL ); attr_merge_normalize_one( e, nad, &nat, NULL ); attr_merge_one( e, slap_schema.si_ad_creatorsName, &mi->mi_creatorsName, &mi->mi_ncreatorsName ); attr_merge_one( e, slap_schema.si_ad_modifiersName, &mi->mi_creatorsName, &mi->mi_ncreatorsName ); attr_merge_normalize_one( e, slap_schema.si_ad_createTimestamp, create ? create : &mi->mi_startTime, NULL ); attr_merge_normalize_one( e, slap_schema.si_ad_modifyTimestamp, modify ? modify : &mi->mi_startTime, NULL ); } return e; }
joaoinaciozup/charlescd
ui/stub/metrics/index.js
<gh_stars>0 import mock from './mock'; const API = '/moove/metrics'; const CIRCLES_API = '/moove/v2/circles'; const DEPLOYMENTS_API = '/moove/v2/deployments'; const findCircleMetrics = { method: 'GET', path: `${API}/circle/{circleId}/components'`, handler: (req, h) => h.response(mock.circlesMetrics) }; const findDeployMetrics = { method: 'GET', path: `${API}/deployments`, handler: (req, h) => h.response(mock.deployMetrics()) }; const findAllCirclesMetrics = { method: 'GET', path: `${API}/circles`, handler: (req, h) => h.response(mock.circlesMetricsDashboard) }; const findAllCirclesHistory = { method: 'GET', path: `${CIRCLES_API}/history`, handler: async (req, h) => h.response(mock.circlesHistory) }; const findAllCirclesReleases = { method: 'GET', path: `${DEPLOYMENTS_API}/circles/{circleId}/history`, handler: async (req, h) => h.response(mock.allCircleReleases) }; const findAllReleases = { method: 'POST', path: `${DEPLOYMENTS_API}/history`, handler: (req, h) => h.response(mock.allDeployReleases) }; export default { findCircleMetrics, findDeployMetrics, findAllCirclesHistory, findAllCirclesReleases, findAllCirclesMetrics, findAllReleases };
rvs/node9
src/styx/svcs/proc.c
#include "nine.h" #include "interp.h" /* kernel process support functions: * * note: the list of kernel procs are tracked in the "procs" list while the list * of interpreter procs are stored in the "progs" list. * * hosted virtual proc functions are located in vm.c * */ static int gpid = 0; // global kernel process pid list /* make a new bare kernel proc */ kproc_t* new_kproc(void) { kproc_t* p; p = malloc(sizeof(kproc_t)); if(p == nil) return nil; p->killed = 0; p->env = &p->defenv; kstrdup(&p->env->user, "*nouser"); p->env->errstr = p->env->errbuf0; p->env->syserrstr = p->env->errbuf1; p->pid = gpid++; p->ptype = Kern_proc; /* by default this proc is self-hosting */ p->hproc = (hproc_t*)p; return p; } void async_debug(uv_async_t *handle) { fprintf(stderr, "--------------->>>loop woke up<<<----------------------\n"); } /* make a new kernel proc that hosts user vprocs on event 'loop' */ hproc_t* new_hproc(uv_loop_t* loop) { hproc_t* p; p = malloc(sizeof(hproc_t)); if(p == nil) return nil; p->killed = 0; p->env = &p->defenv; kstrdup(&p->env->user, "*nouser"); p->env->errstr = p->env->errbuf0; p->env->syserrstr = p->env->errbuf1; p->pid = gpid++; p->ptype = Host_proc; /* by default this kproc is self hosting */ p->hproc = p; /* initialize interpreter instance fields */ p->pidnum = 0; p->isched.head = p->isched.tail = nil; /* initialize it's request/reply queues */ QUEUE_INIT(&p->reqq); QUEUE_INIT(&p->repq); /* initialize it's event loop and wake signal */ p->loop = loop; uv_async_init(p->loop, &p->ev_wake, async_debug); return p; } /* * sleep and wakeup implement a kind of condition variable semantic for process * synchronization. these are used heavily in the device drivers and qio subsystem. * while we could re-implement them by artificially grafting them to the libuv * evented I/O subsystem that would be redundant. probably easier to simply * change the request flow in the drivers to match the event I/O model and let * the callbacks wakeup and reschedule the fibers etc. until then the lower-level * enabling calls on these like osblock/osready etc are no-ops. */ void Sleep(Rendez *r, int (*f)(void*), void *arg) { kproc_t* p = (kproc_t*)up; lock(&p->rlock); lock(&r->l); // if interrupted or more work, don't sleep if(p->killed || f(arg)) { unlock(&r->l); }else{ //print("sleeping on %p\n",r); if(r->p != nil) panic("double sleep pc=0x%lux %s[%lud] %s[%lud] r=0x%lux\n", getcallerpc(&r), r->p->text, r->p->pid, up->text, up->pid, r); r->p = p; unlock(&r->l); p->swipend = 0; p->r = r; // for swiproc unlock(&p->rlock); //print("sleeping on %p and blocking\n", r); osblock(); lock(&p->rlock); p->r = nil; } if(p->killed || p->swipend) { //print("sleeping on %p and killed\n", r); p->killed = 0; p->swipend = 0; unlock(&p->rlock); error(Eintr); } unlock(&p->rlock); } int Wakeup(Rendez *r) { kproc_t *p; lock(&r->l); p = r->p; if(p != nil) { r->p = nil; osready(p); } unlock(&r->l); return p != nil; } /* probably easier ways to do swiproc also, but we'll leave as is * for now. swiproc is used by dis.c and exportfs.c for proc synchro. * otherwise swiproc is a "software interrupt" mechanism using the * already established process synch mechanisms. we'll probably have * to replace it with an async_send in libuv. */ void swiproc(kproc_t *p, int interp) { Rendez *r; print("swiproc: %p, interp=%d\n",p,interp); if(p == nil) return; // Pull out of emu Sleep lock(&p->rlock); if(!interp) p->killed = 1; r = p->r; //print("swiproc: %p is killed is %d on rendez %p\n",p,p->killed, r); if(r != nil) { lock(&r->l); if(r->p == p) { //print("swiproc: setting software interrupt pending\n"); p->swipend = 1; r->p = nil; osready(p); } unlock(&r->l); unlock(&p->rlock); return; } unlock(&p->rlock); // Exit any executing Host OS command lock(&p->sysio); if(p->syscall && p->intwait == 0) { p->swipend = 1; p->intwait = 1; unlock(&p->sysio); oshostintr(p); return; } unlock(&p->sysio); } void notkilled(void) { kproc_t* kp = (kproc_t*)up; lock(&kp->rlock); kp->killed = 0; unlock(&kp->rlock); } /* osenter is called just before making a call to the host operating system. * osleave is called just after making a call to the host operating system. * these are both handled asynchronously by the libuv worker thread, so all * we do is flag the state and use it if we need to. * * note: in both of these the syscall is flagged in the current proc, not * the underlying kernel proc since it can't afford to stop */ void osenter(void) { up->syscall = 1; } void osleave(void) { up->syscall = 0; }
rcmorano/react-polymorph-fix
source/components/NumericInput.js
<filename>source/components/NumericInput.js<gh_stars>0 // @flow import React, { Component } from 'react'; // $FlowFixMe import type { ComponentType, SyntheticInputEvent, Element } from 'react'; // external libraries import createRef from 'create-react-ref/lib/createRef'; import { flow } from 'lodash'; // internal utility functions import { createEmptyContext, withTheme } from './HOC/withTheme'; import { composeTheme, addThemeId, didThemePropsChange } from '../utils/themes'; // import constants import { IDENTIFIERS } from '.'; import type { ThemeContextProp } from './HOC/withTheme'; type Props = { autoFocus?: boolean, className?: string, context: ThemeContextProp, disabled?: boolean, enforceMax: boolean, label?: string | Element<any>, enforceMin: boolean, error?: string, onBlur?: Function, onChange?: Function, onFocus?: Function, maxAfterDot?: number, maxBeforeDot?: number, maxValue?: number, minValue?: number, readOnly?: boolean, placeholder?: string, setError?: Function, skin?: ComponentType<any>, theme: ?Object, // will take precedence over theme in context if passed themeId: string, themeOverrides: Object, value: string }; type State = { composedTheme: Object, caretPosition: number, separatorsCount: number, error: string, oldValue: string }; class NumericInputBase extends Component<Props, State> { // declare ref types inputElement: Element<'input'>; // define static properties static displayName = 'NumericInput'; static defaultProps = { context: createEmptyContext(), enforceMax: false, enforceMin: false, readOnly: false, theme: null, themeId: IDENTIFIERS.INPUT, themeOverrides: {}, value: '' }; constructor(props: Props) { super(props); const { context, minValue, maxBeforeDot, maxAfterDot, themeId, theme, themeOverrides } = props; const minValueIsNum = typeof minValue === 'number'; // if minValue is a number and user supplied maxBeforeDot and/or maxAfterDot if (minValue && minValueIsNum && (maxBeforeDot || maxAfterDot)) { // check combination of values for validity this._validateLimitProps(minValue, maxBeforeDot, maxAfterDot); } // define ref this.inputElement = createRef(); this.state = { composedTheme: composeTheme( addThemeId(theme || context.theme, themeId), addThemeId(themeOverrides, themeId), context.ROOT_THEME_API ), caretPosition: 0, separatorsCount: 0, error: '', oldValue: '' }; } componentDidMount() { const { inputElement } = this; // check for autoFocus prop if (this.props.autoFocus) this.focus(); // Set last input caret position on updates if (inputElement && inputElement.current) { this.setState({ caretPosition: inputElement.current.selectionStart }); } } componentWillReceiveProps(nextProps: Props) { didThemePropsChange(this.props, nextProps, this.setState.bind(this)); } componentDidUpdate(prevProps: Props, prevState: State) { const { inputElement } = this; if (inputElement && inputElement.current !== document.activeElement) { return; } // caret position calculation after separators injection let caretPosition; // prevent unnecessary changes on re-rendering if ( this.state.oldValue !== prevState.oldValue || this.state.caretPosition !== prevState.caretPosition ) { if ( this.state.separatorsCount !== prevState.separatorsCount && this.state.separatorsCount - prevState.separatorsCount <= 1 && this.state.separatorsCount - prevState.separatorsCount >= -1 ) { caretPosition = this.state.caretPosition + (this.state.separatorsCount - prevState.separatorsCount); } else { caretPosition = this.state.caretPosition; } caretPosition = caretPosition >= 0 ? caretPosition : 0; if (inputElement && inputElement.current) { inputElement.current.selectionEnd = caretPosition; inputElement.current.selectionStart = caretPosition; } } } onChange = (event: SyntheticInputEvent<Element<'input'>>) => { event.preventDefault(); const { onChange, disabled } = this.props; if (disabled) { return; } // it is crucial to remove whitespace from input value // with String.trim() const processedValue = this._processValue( event.target.value.trim(), event.target.selectionStart ); // if the processed value is the same, then the user probably entered // invalid input such as nonnumeric characters, do not call onChange if (processedValue === this.state.oldValue) { return; } if (onChange) { onChange(processedValue, event); } }; focus = () => { const { inputElement } = this; if (!inputElement.current) return; inputElement.current.focus(); }; _validateLimitProps(minValue?: number, maxBeforeDot?: number, maxAfterDot?: number) { if (typeof minValue !== 'number') return; const maxBeforeDotIsNum = typeof maxBeforeDot === 'number'; const maxAfterDotIsNum = typeof maxAfterDot === 'number'; // if minValue is a float, it will split at the decimal // trailing zeros are dropped with parseFloat const minValParts = parseFloat(minValue).toString().split('.'); // if minValParts array has length of 2, it is a float if (minValParts.length >= 2) { const minValBeforeDot = minValParts[0]; const minValAfterDot = minValParts[1]; // if the number of integers in minValue is greater than maxBeforeDot if (maxBeforeDot && maxBeforeDotIsNum && (minValBeforeDot.length > maxBeforeDot)) { // the combo is incompatible, throw error const error = ` minValue: ${minValue} exceeds the limit of maxBeforeDot: ${maxBeforeDot}. Adjust the values of these properties. `; throw new Error(error); // if the number of decimal spaces in minValue is greater than maxBeforeDot } else if (maxAfterDot && maxAfterDotIsNum && (minValAfterDot.length > maxAfterDot)) { const error = ` minValue: ${minValue} exceeds the limit of maxAfterDot: ${maxAfterDot}. Adjust the values of these properties. `; throw new Error(error); } } } _setError = (error: string) => { const { setError } = this.props; // checks for setError func from FormField component // if this NumericInput instance is rendered within FormField's render prop, // FormField's local state.error will also be set via props.setError if (setError) setError(error); // also set (this: NumericInput)'s state.error this.setState({ error }); }; _processValue(value: string, position: number) { return flow([ this._enforceNumericValue, this._parseToParts, this._enforceValueLimits, this._separate ]).call(this, value, position); } _enforceNumericValue(value: string, position: number) { const regex = /^[0-9.,]+$/; const isValueRegular = regex.test(value); const { maxBeforeDot } = this.props; let handledValue; const lastValidValue = this.state.oldValue; if (!isValueRegular && value !== '') { // input contains invalid value // e.g. 1,00AAbasdasd.asdasd123123 // - reject it and show last valid value handledValue = lastValidValue || '0.000000'; position -= 1; } else if (!this._isNumeric(value)) { // input contains comma separated number // e.g. 1,000,000.123456 // - make sure commas and caret are at correct position const splitedValue = value.split('.'); // check if input value contains more than one decimal if (splitedValue.length === 3) { const splitedOldValue = lastValidValue.split('.'); let beforeDot = splitedValue[0] + splitedValue[1]; // variable for value before the decimal containing a comma. Ex: 1,425 let beforeDotWithoutComma = beforeDot; // if comma exists, remove before comparing length in next if-else statement if (beforeDot.includes(',')) { const beforeComma = beforeDot.slice(0, beforeDot.indexOf(',')); const afterComma = beforeDot.slice(beforeDot.indexOf(',') + 1); beforeDotWithoutComma = beforeComma + afterComma; } if ( (!beforeDot.includes(',') && splitedOldValue[0].length < beforeDot.length) || (beforeDot.includes(',') && splitedOldValue[0].length < beforeDotWithoutComma.length) ) { // dot is in decimal part position -= 1; handledValue = beforeDot + '.' + splitedValue[2]; beforeDot = beforeDot.replace(/,/g, ''); // prevent replace dot if length before dot is greater then max before dot length if (maxBeforeDot && beforeDot.length > maxBeforeDot) { handledValue = lastValidValue; } } else { handledValue = splitedValue[0] + '.' + splitedValue[1] + splitedValue[2]; // Second dot was entered after current one -> stay in same position (swallow dot) if (position > beforeDot.length + 1) { position -= 1; } } } else if ( splitedValue.length === 2 && splitedValue[0] === '' && splitedValue[1] === '' ) { // special case when dot is inserted in an empty input // - return 0.|00000 handledValue = '0.000000'; position = 2; // position caret after the dot } else if (value !== '') { // special case when user selects part of an input value and hits ',' key // - reject it and show last valid value handledValue = lastValidValue; } } const lastInsertedCharacter = value.substring(position - 1, position); if (lastInsertedCharacter === ',') { // prevent move caret position on hit ',' position -= 1; } return !this._isNumeric(value) ? { value: handledValue, position } : { value, position }; } _parseToParts(data: { value: string, position: number }) { const value = data.value; let position = data.position; // show placeholder on select all and delete/backspace key action if (!value) return; let beforeDot; let afterDot; if (data.value.length > 1 && value.split('.').length < 2) { // handle numbers deletion from both integer and decimal parts at once beforeDot = value.substring(0, position) || '0'; afterDot = value.substring(position, value.length); } else { // split float number to integer and decimal part - regular way const splitedValue = value.split('.'); beforeDot = splitedValue[0] ? splitedValue[0] : '0'; afterDot = splitedValue[1] ? splitedValue[1] : '000000'; } // remove leading zero and update caret position if (value.charAt(0) === '0' && parseInt(beforeDot.replace(/,/g, ''), 10) > 0) { beforeDot = parseInt(beforeDot.replace(/,/g, ''), 10); if (position !== 2) { position = 0; } else { position = 1; } } else if (parseInt(beforeDot.replace(/,/g, ''), 10) === 0) { beforeDot = parseInt(beforeDot.replace(/,/g, ''), 10); } return { value, position, parts: { beforeDot, afterDot } }; } // enforces props.maxValue and props.minValue _enforceValueLimits(data: { value: string, position: number, parts: { beforeDot: string, afterDot: string } }) { if (!data) return; const { minValue, maxValue, enforceMax, enforceMin, maxAfterDot } = this.props; const { position } = data; // enforce props.maxBeforeDot and props.maxAfterDot const valueWithDecimalRestrictions = this._enforceDecimalRestrictions(data); // creates floating point number equal to valueWithDecimalRestrictions (string) // will be used for value comparisons against props.maxValue and props.minValue if applicable const valueWithoutSeparators = parseFloat(valueWithDecimalRestrictions.replace(/,/g, '')); // if input value is greater than props.maxValue, throw error if (maxValue && valueWithoutSeparators > maxValue) { const formattedMaxVal = maxValue.toFixed(maxAfterDot || 6).toString(); this._setError(`Maximum amount is ${formattedMaxVal}`); // if user passes enforceMax=true, restrict input value to props.maxValue if (enforceMax) { this.setState({ caretPosition: position }); return formattedMaxVal; } // if input value is below props.minValue, throw error } else if (minValue && valueWithoutSeparators < minValue) { const formattedMinVal = minValue.toFixed(maxAfterDot || 6).toString(); this._setError(`Minimum amount is ${formattedMinVal}`); // if props.enforceMin=true, restrict input value to props.minValue if (enforceMin) { this.setState({ caretPosition: position }); return formattedMinVal; } // if input value has no errors, clear state.error } else if (this.state.error !== '') { this._setError(''); } // update caret in state this.setState({ caretPosition: position }); // input value w/ decimal restrictions is passed along // to this._separate without value restrictions return valueWithDecimalRestrictions; } // enforces props.maxBeforeDot and props.maxAfterDot _enforceDecimalRestrictions(data: { value: string, position: number, parts: { beforeDot: string, afterDot: string } }) { const { maxBeforeDot, maxAfterDot } = this.props; let { beforeDot } = data.parts; let { afterDot } = data.parts; // preventing numbers with more than maxBeforeDot units // - return first maxBeforeDot numbers (with comma separators) if (maxBeforeDot && beforeDot) { // max number of commas depending on max number of characters before dot const numberOfCommas = maxBeforeDot % 3 > 0 ? parseInt(maxBeforeDot / 3, 10) : parseInt(maxBeforeDot / 3, 10) - 1; const maxBeforeDotWithSeparator = maxBeforeDot + numberOfCommas; if (beforeDot.length > maxBeforeDotWithSeparator) { beforeDot = beforeDot.substring(0, maxBeforeDotWithSeparator); } } // remove commas from decimal part // (e.g. 123,23,2.002000 -> dot after 2.character reproduce 12.3,23,2) afterDot = afterDot.replace(/,/g, ''); // preventing numbers with more than maxAfterDot units - return first maxAfterDot numbers if (maxAfterDot && afterDot && afterDot.length > maxAfterDot) { afterDot = afterDot.substring(0, maxAfterDot); } // if decimal number has less than maxAfterDot numbers add trailing zeros let afterDotLength = afterDot ? afterDot.length : 0; if (maxAfterDot && afterDotLength < maxAfterDot) { for (afterDotLength; afterDotLength < maxAfterDot; afterDotLength++) { afterDot += '0'; } } // if maxAfterDot is 0, drop decimal & numbers after decimal, return int if (maxAfterDot === 0) { return beforeDot; } // return input value w/decimal restrictions as a string return beforeDot + '.' + afterDot; } _separate(value: string) { this.setState({ oldValue: value }); // value will not contain '.' if maxAfterDot is 0, return early if (value && !value.includes('.')) { return value; } if (!value) { this.setState({ separatorsCount: 0 }); } if (value) { const splitedValue = value.split('.'); const separatedValue = splitedValue[0] .replace(/,/g, '') .split('') .reverse() .join('') .replace(/(\d{3}\B)/g, '$1,') .split('') .reverse() .join(''); const newSeparatorsCount = (separatedValue.match(/,/g) || []).length; this.setState({ separatorsCount: newSeparatorsCount }); return separatedValue + '.' + splitedValue[1]; } } _isNumeric(value: string) { const replacedValue = value.replace(/,/g, ''); // eslint-disable-next-line no-restricted-globals return !isNaN(parseFloat(replacedValue)) && isFinite(replacedValue); } render() { // destructuring props ensures only the "...rest" get passed down const { skin, theme, themeOverrides, onChange, error, context, maxValue, minValue, maxBeforeDot, maxAfterDot, ...rest } = this.props; const InputSkin = skin || context.skins[IDENTIFIERS.INPUT]; return ( <InputSkin error={error || this.state.error} inputRef={this.inputElement} onChange={this.onChange} theme={this.state.composedTheme} {...rest} /> ); } } export const NumericInput = withTheme(NumericInputBase);
Martin-BG/spring-nov-2019
heroes/src/main/java/com/minkov/heroes/web/api/models/ItemResponseModel.java
package com.minkov.heroes.web.api.models; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import com.minkov.heroes.data.models.Slot; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class ItemResponseModel { private long id; private String name; private int stamina; private int strength; private int attack; private int defence; private Slot slot; private boolean isOwned; }
sid-360/gearshaft
message-store/test/message-data.test.js
const { exampleWriteMessageData } = require('../examples') const uuidValidate = require('uuid-validate') describe('write-message-data', () => { describe('examples', () => { describe('no inputs', () => { const message = exampleWriteMessageData() it('generates id', () => { expect(uuidValidate(message.id)).toBe(true) }) it('generates type', () => { expect(message).toEqual({ id: expect.anything(), // covered aboe type: 'SomeType', data: { someAttribute: expect.stringMatching(/^[0-9a-f]{32}$/) }, metadata: { // streamName: expect.stringMatching(/^[0-9a-f]{32}$/), // position: expect.any(Number), // globalPosition: expect.any(Number), // causationMessageGlobalPosition: expect.any(Number), // causationMessageStreamName: expect.stringMatching(/^[0-9a-f]{32}$/), // causationMessagePosition: expect.any(Number), // correlationStreamName: expect.stringMatching(/^[0-9a-f]{32}$/), // replyStreamName: expect.stringMatching(/^[0-9a-f]{32}$/), someMetaAttribute: expect.stringMatching(/^[0-9a-f]{32}$/) } }) }) }) describe('specified inputs', () => { it('generates a message with the specified values', () => { const values = { id: '57b730bf-0a30-4ec0-89aa-888b5f22ce6d', type: 'OtherType', data: { otherAttribute: 'other-value' }, metadata: { otherMetaAttribute: 'meta-attribute' } } const message = exampleWriteMessageData(values) expect(message).toEqual(values) }) }) }) })
oirad21/react_oirad
node_modules/@fortawesome/pro-light-svg-icons/faShareSquare.js
<filename>node_modules/@fortawesome/pro-light-svg-icons/faShareSquare.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fal'; var iconName = 'share-square'; var width = 576; var height = 512; var ligatures = []; var unicode = 'f14d'; var svgPathData = 'M566.633 169.37L406.63 9.392C386.626-10.612 352 3.395 352 32.022v72.538C210.132 108.474 88 143.455 88 286.3c0 84.74 49.78 133.742 79.45 155.462 24.196 17.695 58.033-4.917 49.7-34.51C188.286 304.843 225.497 284.074 352 280.54V352c0 28.655 34.654 42.606 54.63 22.63l160.003-160c12.489-12.5 12.489-32.76 0-45.26zM384 352V248.04c-141.718.777-240.762 15.03-197.65 167.96C154.91 393 120 351.28 120 286.3c0-134.037 131.645-149.387 264-150.26V32l160 160-160 160zm37.095 52.186c2.216-1.582 4.298-3.323 6.735-5.584 7.68-7.128 20.17-1.692 20.17 8.787V464c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h172.146c6.612 0 11.954 5.412 11.852 12.04-.084 5.446-4.045 10.087-9.331 11.396-9.462 2.343-18.465 4.974-27.074 7.914-1.25.427-2.555.65-3.876.65H48c-8.837 0-16 7.163-16 16v352c0 8.837 7.163 16 16 16h352c8.837 0 16-7.163 16-16v-50.002c0-3.905 1.916-7.543 5.095-9.812z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faShareSquare = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
nunnatsa/logging
logging-log4j/src/test/java/com/cisco/oss/foundation/logging/LoggingDemo.java
<reponame>nunnatsa/logging /* * Copyright 2015 Cisco Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cisco.oss.foundation.logging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggingDemo { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { while(true){ LoggingDemo1.log(); LoggingDemo2.log(); Thread.sleep(1000); } } private static final class LoggingDemo1{ private static final Logger LOGGER = LoggerFactory.getLogger(LoggingDemo1.class); private static void log(){ LOGGER.info("demo 1 info log"); LOGGER.warn("demo 1 warn log"); } } private static final class LoggingDemo2{ private static final Logger LOGGER = LoggerFactory.getLogger(LoggingDemo2.class); private static void log(){ LOGGER.info("demo 2 info log"); LOGGER.warn("demo 2 warn log"); } } }
LMSC-NTappy/PyMoDAQ
tests/daq_utils_test/plotting_test/data_viewers_test/viewerND_test.py
import pytest from qtpy import QtWidgets from pymodaq.daq_utils.plotting.data_viewers.viewerND import ViewerND from pymodaq.daq_utils.conftests import qtbotskip pytestmark = pytest.mark.skipif(qtbotskip, reason='qtbot issues but tested locally') @pytest.fixture def init_prog(qtbot): form = QtWidgets.QWidget() prog = ViewerND() qtbot.addWidget(form) yield prog form.close() class TestViewer2D: def test_init(self, init_prog): prog = init_prog assert isinstance(prog, ViewerND)
Grimgrents2/WarsmashModEngine
jassparser/src/com/etheller/interpreter/ast/visitors/ArgumentExpressionHandler.java
package com.etheller.interpreter.ast.visitors; public class ArgumentExpressionHandler { protected JassArgumentsVisitor argumentsVisitor; protected JassExpressionVisitor expressionVisitor; public void setJassArgumentsVisitor(final JassArgumentsVisitor jassArgumentsVisitor) { this.argumentsVisitor = jassArgumentsVisitor; } public void setJassExpressionVisitor(final JassExpressionVisitor jassExpressionVisitor) { this.expressionVisitor = jassExpressionVisitor; } }
IdanBanani/Pwnable.kr-CTF-Writeups
pwnable/crypto1/solution.py
<gh_stars>0 import re import socket from typing import List from hashlib import sha256 BLOCK_SIZE = 16 ALLOWED_CHARACTERS = '1234567890abcdefghijklmnopqrstuvwxyz-_' COOKIE_LENGTH = 49 def get_encrypted(identity: str, password: str) -> List[str]: conn = socket.socket() conn.connect(('pwnable.kr', 9006)) conn.send(f'{identity}\n'.encode()) conn.send(f'{password}\n'.encode()) conn.recv(1024) raw_response = conn.recv(1024).decode() encrypted_data = re.search(r'\((?P<encrypted>.*)\)', raw_response).group('encrypted') result = [encrypted_data[i:i + BLOCK_SIZE * 2] for i in range(0, len(encrypted_data), BLOCK_SIZE * 2)] return result def find_cookie() -> str: """ In order to find the cookie we rely on a few exploits on the given cryptosystem: - The IV is a constant value - We are in position of Chosen-Plaintext-Attackers. We can send any plaintext we get and view the ciphertext. This attack follows the same principles of well known attacks such as BEAST attack on TLS. This is exactly how we do it: - First, we create a block by filling it with 15 bytes, and then we're left with one byte from the cookie. So what we do is calculating the value of the real block, and then repeatedly guessing the first byte of the cookie until the real ciphertext matches our guessed ciphertext - Then we do the same thing for the rest of the blocks, until we found all the characters of the cookie. This methods lets us find the cookie in complexity in n * 256 iterations instead of just 256 ** n. :return: The Cookie we calculated """ cookie = '' junk_block = 'a' * (BLOCK_SIZE - 1) # Start from block index 1 block_index = 1 # Iterate through all the blocks and stop until the whole cookie # is found while True: # Find the next 15 bytes for byte_index in range(1, BLOCK_SIZE): prefix = 'a' * (BLOCK_SIZE - 1 - byte_index + (block_index - 1)) cookie_block = get_encrypted(junk_block, prefix)[block_index] for character in ALLOWED_CHARACTERS: guessed_data = f'{prefix}-{cookie + character}' guessed_block = get_encrypted(junk_block, guessed_data)[block_index] if guessed_block == cookie_block: cookie += character # TODO: Remove this print print(character, end='') break if len(cookie) == COOKIE_LENGTH: return cookie # Progress the block index block_index += 1 def main(): """ Prints the admin password for pwnable.kr crypto1 challange. """ cookie = find_cookie() admin_password = sha256(b'admin' + cookie.encode()).hexdigest() print(f'The admin password is: \n{admin_password}') if __name__ == '__main__': main()
DwArFeng/familyhelper-finance
familyhelper-finance-impl/src/main/java/com/dwarfeng/familyhelper/finance/impl/service/FundChangeMaintainServiceImpl.java
<gh_stars>0 package com.dwarfeng.familyhelper.finance.impl.service; import com.dwarfeng.familyhelper.finance.stack.bean.entity.FundChange; import com.dwarfeng.familyhelper.finance.stack.service.FundChangeMaintainService; import com.dwarfeng.subgrade.impl.service.DaoOnlyEntireLookupService; import com.dwarfeng.subgrade.impl.service.DaoOnlyPresetLookupService; import com.dwarfeng.subgrade.impl.service.GeneralBatchCrudService; import com.dwarfeng.subgrade.sdk.interceptor.analyse.BehaviorAnalyse; import com.dwarfeng.subgrade.sdk.interceptor.analyse.SkipRecord; import com.dwarfeng.subgrade.stack.bean.dto.PagedData; import com.dwarfeng.subgrade.stack.bean.dto.PagingInfo; import com.dwarfeng.subgrade.stack.bean.key.LongIdKey; import com.dwarfeng.subgrade.stack.exception.ServiceException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class FundChangeMaintainServiceImpl implements FundChangeMaintainService { private final GeneralBatchCrudService<LongIdKey, FundChange> crudService; private final DaoOnlyEntireLookupService<FundChange> entireLookupService; private final DaoOnlyPresetLookupService<FundChange> presetLookupService; public FundChangeMaintainServiceImpl( GeneralBatchCrudService<LongIdKey, FundChange> crudService, DaoOnlyEntireLookupService<FundChange> entireLookupService, DaoOnlyPresetLookupService<FundChange> presetLookupService ) { this.crudService = crudService; this.entireLookupService = entireLookupService; this.presetLookupService = presetLookupService; } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean exists(LongIdKey key) throws ServiceException { return crudService.exists(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public FundChange get(LongIdKey key) throws ServiceException { return crudService.get(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public LongIdKey insert(FundChange element) throws ServiceException { return crudService.insert(element); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void update(FundChange element) throws ServiceException { crudService.update(element); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void delete(LongIdKey key) throws ServiceException { crudService.delete(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public FundChange getIfExists(LongIdKey key) throws ServiceException { return crudService.getIfExists(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public LongIdKey insertIfNotExists(FundChange element) throws ServiceException { return crudService.insertIfNotExists(element); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void updateIfExists(FundChange element) throws ServiceException { crudService.updateIfExists(element); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void deleteIfExists(LongIdKey key) throws ServiceException { crudService.deleteIfExists(key); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public LongIdKey insertOrUpdate(FundChange element) throws ServiceException { return crudService.insertOrUpdate(element); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean allExists(@SkipRecord List<LongIdKey> keys) throws ServiceException { return crudService.allExists(keys); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public boolean nonExists(@SkipRecord List<LongIdKey> keys) throws ServiceException { return crudService.nonExists(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public List<FundChange> batchGet(@SkipRecord List<LongIdKey> keys) throws ServiceException { return crudService.batchGet(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public List<LongIdKey> batchInsert(@SkipRecord List<FundChange> elements) throws ServiceException { return crudService.batchInsert(elements); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchUpdate(@SkipRecord List<FundChange> elements) throws ServiceException { crudService.batchUpdate(elements); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchDelete(@SkipRecord List<LongIdKey> keys) throws ServiceException { crudService.batchDelete(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public List<FundChange> batchGetIfExists(@SkipRecord List<LongIdKey> keys) throws ServiceException { return crudService.batchGetIfExists(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public List<LongIdKey> batchInsertIfExists(@SkipRecord List<FundChange> elements) throws ServiceException { return crudService.batchInsertIfExists(elements); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchUpdateIfExists(@SkipRecord List<FundChange> elements) throws ServiceException { crudService.batchUpdateIfExists(elements); } @Override @BehaviorAnalyse @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public void batchDeleteIfExists(@SkipRecord List<LongIdKey> keys) throws ServiceException { crudService.batchDeleteIfExists(keys); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", rollbackFor = Exception.class) public List<LongIdKey> batchInsertOrUpdate(@SkipRecord List<FundChange> elements) throws ServiceException { return crudService.batchInsertOrUpdate(elements); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public PagedData<FundChange> lookup() throws ServiceException { return entireLookupService.lookup(); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public PagedData<FundChange> lookup(PagingInfo pagingInfo) throws ServiceException { return entireLookupService.lookup(pagingInfo); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public PagedData<FundChange> lookup(String preset, Object[] objs) throws ServiceException { return presetLookupService.lookup(preset, objs); } @Override @BehaviorAnalyse @SkipRecord @Transactional(transactionManager = "hibernateTransactionManager", readOnly = true, rollbackFor = Exception.class) public PagedData<FundChange> lookup(String preset, Object[] objs, PagingInfo pagingInfo) throws ServiceException { return presetLookupService.lookup(preset, objs, pagingInfo); } }
dingqunfei/LeetCode
Problem401-450/p435_1.cpp
/** * @file p435_1.cpp * @brief * @author dingqunfei (<EMAIL>) * @version 1.0 * @date 2021-07-11 * * @copyright Copyright (c) 2021 DQFLYING * * @par : * * * Date : 2021-07-11 * Version : 1.0 * Author : dqflying * Lisence : * Description : * * * * */ class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { int size = intervals.size(); if(size < 2) { return 0; } sort(intervals.begin(), intervals.end(), [](vector<int> &a, vector<int> &b){return a[1] < b[1];}); int count = 1; vector<int> &start = intervals[0]; for(int i = 1; i < size; ++i) { if(intervals[i][0] >= start[1]) { ++count; start = intervals[i]; } } return size-count; } };
dmgerman/hadoop
hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpConstants.java
<filename>hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpConstants.java begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.tools package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|tools package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceAudience import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceStability import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_comment comment|/** * Utility class to hold commonly used constants. */ end_comment begin_class annotation|@ name|InterfaceAudience operator|. name|LimitedPrivate argument_list|( literal|"Distcp support tools" argument_list|) annotation|@ name|InterfaceStability operator|. name|Evolving DECL|class|DistCpConstants specifier|public specifier|final class|class name|DistCpConstants block|{ DECL|method|DistCpConstants () specifier|private name|DistCpConstants parameter_list|() block|{ } comment|/* Default number of threads to use for building file listing */ DECL|field|DEFAULT_LISTSTATUS_THREADS specifier|public specifier|static specifier|final name|int name|DEFAULT_LISTSTATUS_THREADS init|= literal|1 decl_stmt|; comment|/* Default number of maps to use for DistCp */ DECL|field|DEFAULT_MAPS specifier|public specifier|static specifier|final name|int name|DEFAULT_MAPS init|= literal|20 decl_stmt|; comment|/* Default bandwidth if none specified */ DECL|field|DEFAULT_BANDWIDTH_MB specifier|public specifier|static specifier|final name|float name|DEFAULT_BANDWIDTH_MB init|= literal|100 decl_stmt|; comment|/* Default strategy for copying. Implementation looked up from distcp-default.xml */ DECL|field|UNIFORMSIZE specifier|public specifier|static specifier|final name|String name|UNIFORMSIZE init|= literal|"uniformsize" decl_stmt|; comment|/** * Constants mapping to command line switches/input options */ DECL|field|CONF_LABEL_ATOMIC_COPY specifier|public specifier|static specifier|final name|String name|CONF_LABEL_ATOMIC_COPY init|= literal|"distcp.atomic.copy" decl_stmt|; DECL|field|CONF_LABEL_WORK_PATH specifier|public specifier|static specifier|final name|String name|CONF_LABEL_WORK_PATH init|= literal|"distcp.work.path" decl_stmt|; DECL|field|CONF_LABEL_LOG_PATH specifier|public specifier|static specifier|final name|String name|CONF_LABEL_LOG_PATH init|= literal|"distcp.log.path" decl_stmt|; DECL|field|CONF_LABEL_VERBOSE_LOG specifier|public specifier|static specifier|final name|String name|CONF_LABEL_VERBOSE_LOG init|= literal|"distcp.verbose.log" decl_stmt|; DECL|field|CONF_LABEL_IGNORE_FAILURES specifier|public specifier|static specifier|final name|String name|CONF_LABEL_IGNORE_FAILURES init|= literal|"distcp.ignore.failures" decl_stmt|; DECL|field|CONF_LABEL_PRESERVE_STATUS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_PRESERVE_STATUS init|= literal|"distcp.preserve.status" decl_stmt|; DECL|field|CONF_LABEL_PRESERVE_RAWXATTRS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_PRESERVE_RAWXATTRS init|= literal|"distcp.preserve.rawxattrs" decl_stmt|; DECL|field|CONF_LABEL_SYNC_FOLDERS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SYNC_FOLDERS init|= literal|"distcp.sync.folders" decl_stmt|; DECL|field|CONF_LABEL_DELETE_MISSING specifier|public specifier|static specifier|final name|String name|CONF_LABEL_DELETE_MISSING init|= literal|"distcp.delete.missing.source" decl_stmt|; DECL|field|CONF_LABEL_TRACK_MISSING specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TRACK_MISSING init|= literal|"distcp.track.missing.source" decl_stmt|; DECL|field|CONF_LABEL_LISTSTATUS_THREADS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_LISTSTATUS_THREADS init|= literal|"distcp.liststatus.threads" decl_stmt|; DECL|field|CONF_LABEL_MAX_MAPS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_MAX_MAPS init|= literal|"distcp.max.maps" decl_stmt|; DECL|field|CONF_LABEL_SOURCE_LISTING specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SOURCE_LISTING init|= literal|"distcp.source.listing" decl_stmt|; DECL|field|CONF_LABEL_COPY_STRATEGY specifier|public specifier|static specifier|final name|String name|CONF_LABEL_COPY_STRATEGY init|= literal|"distcp.copy.strategy" decl_stmt|; DECL|field|CONF_LABEL_SKIP_CRC specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SKIP_CRC init|= literal|"distcp.skip.crc" decl_stmt|; DECL|field|CONF_LABEL_OVERWRITE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_OVERWRITE init|= literal|"distcp.copy.overwrite" decl_stmt|; DECL|field|CONF_LABEL_APPEND specifier|public specifier|static specifier|final name|String name|CONF_LABEL_APPEND init|= literal|"distcp.copy.append" decl_stmt|; DECL|field|CONF_LABEL_DIFF specifier|public specifier|static specifier|final name|String name|CONF_LABEL_DIFF init|= literal|"distcp.copy.diff" decl_stmt|; DECL|field|CONF_LABEL_RDIFF specifier|public specifier|static specifier|final name|String name|CONF_LABEL_RDIFF init|= literal|"distcp.copy.rdiff" decl_stmt|; DECL|field|CONF_LABEL_BANDWIDTH_MB specifier|public specifier|static specifier|final name|String name|CONF_LABEL_BANDWIDTH_MB init|= literal|"distcp.map.bandwidth.mb" decl_stmt|; DECL|field|CONF_LABEL_SIMPLE_LISTING_FILESTATUS_SIZE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SIMPLE_LISTING_FILESTATUS_SIZE init|= literal|"distcp.simplelisting.file.status.size" decl_stmt|; DECL|field|CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES init|= literal|"distcp.simplelisting.randomize.files" decl_stmt|; DECL|field|CONF_LABEL_FILTERS_FILE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_FILTERS_FILE init|= literal|"distcp.filters.file" decl_stmt|; DECL|field|CONF_LABEL_MAX_CHUNKS_TOLERABLE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_MAX_CHUNKS_TOLERABLE init|= literal|"distcp.dynamic.max.chunks.tolerable" decl_stmt|; DECL|field|CONF_LABEL_MAX_CHUNKS_IDEAL specifier|public specifier|static specifier|final name|String name|CONF_LABEL_MAX_CHUNKS_IDEAL init|= literal|"distcp.dynamic.max.chunks.ideal" decl_stmt|; DECL|field|CONF_LABEL_MIN_RECORDS_PER_CHUNK specifier|public specifier|static specifier|final name|String name|CONF_LABEL_MIN_RECORDS_PER_CHUNK init|= literal|"distcp.dynamic.min.records_per_chunk" decl_stmt|; DECL|field|CONF_LABEL_SPLIT_RATIO specifier|public specifier|static specifier|final name|String name|CONF_LABEL_SPLIT_RATIO init|= literal|"distcp.dynamic.split.ratio" decl_stmt|; DECL|field|CONF_LABEL_DIRECT_WRITE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_DIRECT_WRITE init|= literal|"distcp.direct.write" decl_stmt|; comment|/* Total bytes to be copied. Updated by copylisting. Unfiltered count */ DECL|field|CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED init|= literal|"mapred.total.bytes.expected" decl_stmt|; comment|/* Total number of paths to copy, includes directories. Unfiltered count */ DECL|field|CONF_LABEL_TOTAL_NUMBER_OF_RECORDS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TOTAL_NUMBER_OF_RECORDS init|= literal|"mapred.number.of.records" decl_stmt|; comment|/* If input is based -f<<source listing>>, file containing the src paths */ DECL|field|CONF_LABEL_LISTING_FILE_PATH specifier|public specifier|static specifier|final name|String name|CONF_LABEL_LISTING_FILE_PATH init|= literal|"distcp.listing.file.path" decl_stmt|; comment|/* Directory where the mapreduce job will write to. If not atomic commit, then same as CONF_LABEL_TARGET_FINAL_PATH */ DECL|field|CONF_LABEL_TARGET_WORK_PATH specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TARGET_WORK_PATH init|= literal|"distcp.target.work.path" decl_stmt|; comment|/* Directory where the final data will be committed to. If not atomic commit, then same as CONF_LABEL_TARGET_WORK_PATH */ DECL|field|CONF_LABEL_TARGET_FINAL_PATH specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TARGET_FINAL_PATH init|= literal|"distcp.target.final.path" decl_stmt|; comment|/* Boolean to indicate whether the target of distcp exists. */ DECL|field|CONF_LABEL_TARGET_PATH_EXISTS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_TARGET_PATH_EXISTS init|= literal|"distcp.target.path.exists" decl_stmt|; comment|/** * DistCp job id for consumers of the Disctp */ DECL|field|CONF_LABEL_DISTCP_JOB_ID specifier|public specifier|static specifier|final name|String name|CONF_LABEL_DISTCP_JOB_ID init|= literal|"distcp.job.id" decl_stmt|; comment|/* Meta folder where the job's intermediate data is kept */ DECL|field|CONF_LABEL_META_FOLDER specifier|public specifier|static specifier|final name|String name|CONF_LABEL_META_FOLDER init|= literal|"distcp.meta.folder" decl_stmt|; comment|/* DistCp CopyListing class override param */ DECL|field|CONF_LABEL_COPY_LISTING_CLASS specifier|public specifier|static specifier|final name|String name|CONF_LABEL_COPY_LISTING_CLASS init|= literal|"distcp.copy.listing.class" decl_stmt|; comment|/* DistCp Copy Buffer Size */ DECL|field|CONF_LABEL_COPY_BUFFER_SIZE specifier|public specifier|static specifier|final name|String name|CONF_LABEL_COPY_BUFFER_SIZE init|= literal|"distcp.copy.buffer.size" decl_stmt|; comment|/** DistCp Blocks Per Chunk: {@value}. */ DECL|field|CONF_LABEL_BLOCKS_PER_CHUNK specifier|public specifier|static specifier|final name|String name|CONF_LABEL_BLOCKS_PER_CHUNK init|= literal|"distcp.blocks.per.chunk" decl_stmt|; comment|/** * Constants for DistCp return code to shell / consumer of ToolRunner's run */ DECL|field|SUCCESS specifier|public specifier|static specifier|final name|int name|SUCCESS init|= literal|0 decl_stmt|; DECL|field|INVALID_ARGUMENT specifier|public specifier|static specifier|final name|int name|INVALID_ARGUMENT init|= operator|- literal|1 decl_stmt|; DECL|field|DUPLICATE_INPUT specifier|public specifier|static specifier|final name|int name|DUPLICATE_INPUT init|= operator|- literal|2 decl_stmt|; DECL|field|ACLS_NOT_SUPPORTED specifier|public specifier|static specifier|final name|int name|ACLS_NOT_SUPPORTED init|= operator|- literal|3 decl_stmt|; DECL|field|XATTRS_NOT_SUPPORTED specifier|public specifier|static specifier|final name|int name|XATTRS_NOT_SUPPORTED init|= operator|- literal|4 decl_stmt|; DECL|field|UNKNOWN_ERROR specifier|public specifier|static specifier|final name|int name|UNKNOWN_ERROR init|= operator|- literal|999 decl_stmt|; comment|/** * Constants for DistCp default values of configurable values */ DECL|field|MAX_CHUNKS_TOLERABLE_DEFAULT specifier|public specifier|static specifier|final name|int name|MAX_CHUNKS_TOLERABLE_DEFAULT init|= literal|400 decl_stmt|; DECL|field|MAX_CHUNKS_IDEAL_DEFAULT specifier|public specifier|static specifier|final name|int name|MAX_CHUNKS_IDEAL_DEFAULT init|= literal|100 decl_stmt|; DECL|field|MIN_RECORDS_PER_CHUNK_DEFAULT specifier|public specifier|static specifier|final name|int name|MIN_RECORDS_PER_CHUNK_DEFAULT init|= literal|5 decl_stmt|; DECL|field|SPLIT_RATIO_DEFAULT specifier|public specifier|static specifier|final name|int name|SPLIT_RATIO_DEFAULT init|= literal|2 decl_stmt|; comment|/** * Constants for NONE file deletion */ DECL|field|NONE_PATH_NAME specifier|public specifier|static specifier|final name|String name|NONE_PATH_NAME init|= literal|"/NONE" decl_stmt|; DECL|field|NONE_PATH specifier|public specifier|static specifier|final name|Path name|NONE_PATH init|= operator|new name|Path argument_list|( name|NONE_PATH_NAME argument_list|) decl_stmt|; DECL|field|RAW_NONE_PATH specifier|public specifier|static specifier|final name|Path name|RAW_NONE_PATH init|= operator|new name|Path argument_list|( name|DistCpConstants operator|. name|HDFS_RESERVED_RAW_DIRECTORY_NAME operator|+ name|NONE_PATH_NAME argument_list|) decl_stmt|; comment|/** * Value of reserved raw HDFS directory when copying raw.* xattrs. */ DECL|field|HDFS_RESERVED_RAW_DIRECTORY_NAME specifier|public specifier|static specifier|final name|String name|HDFS_RESERVED_RAW_DIRECTORY_NAME init|= literal|"/.reserved/raw" decl_stmt|; DECL|field|HDFS_DISTCP_DIFF_DIRECTORY_NAME specifier|static specifier|final name|String name|HDFS_DISTCP_DIFF_DIRECTORY_NAME init|= literal|".distcp.diff.tmp" decl_stmt|; DECL|field|COPY_BUFFER_SIZE_DEFAULT specifier|public specifier|static specifier|final name|int name|COPY_BUFFER_SIZE_DEFAULT init|= literal|8 operator|* literal|1024 decl_stmt|; comment|/** Filename of sorted files in when tracking saves them. */ DECL|field|SOURCE_SORTED_FILE specifier|public specifier|static specifier|final name|String name|SOURCE_SORTED_FILE init|= literal|"source_sorted.seq" decl_stmt|; comment|/** Filename of unsorted target listing. */ DECL|field|TARGET_LISTING_FILE specifier|public specifier|static specifier|final name|String name|TARGET_LISTING_FILE init|= literal|"target_listing.seq" decl_stmt|; comment|/** Filename of sorted target listing. */ DECL|field|TARGET_SORTED_FILE specifier|public specifier|static specifier|final name|String name|TARGET_SORTED_FILE init|= literal|"target_sorted.seq" decl_stmt|; DECL|field|LENGTH_MISMATCH_ERROR_MSG specifier|public specifier|static specifier|final name|String name|LENGTH_MISMATCH_ERROR_MSG init|= literal|"Mismatch in length of source:" decl_stmt|; DECL|field|CHECKSUM_MISMATCH_ERROR_MSG specifier|public specifier|static specifier|final name|String name|CHECKSUM_MISMATCH_ERROR_MSG init|= literal|"Checksum mismatch between " decl_stmt|; block|} end_class end_unit
steva44/OpenSees
SRC/element/gradientInelasticBeamColumn/TclGradientInelasticBeamColumnCommand.cpp
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** ** ** ****************************************************************** */ /* Written by: <NAME> (<EMAIL>) ** Created: 07/19 ** Description: The source code for the Tcl commands of gradient inelastic (GI) force-based beam-column element formulation */ #include <stdlib.h> #include <string.h> #include <Domain.h> #include <TclModelBuilder.h> #include "GradientInelasticBeamColumn2d.h" #include "GradientInelasticBeamColumn3d.h" #include <NewtonCotesBeamIntegration.h> #include <TrapezoidalBeamIntegration.h> #include <SimpsonBeamIntegration.h> #include <LobattoBeamIntegration.h> #include <LegendreBeamIntegration.h> extern void printCommand(int argc, TCL_Char** argv); int TclModelBuilder_addGradientInelasticBeamColumn(ClientData clientData, Tcl_Interp* interp, int argc, TCL_Char** argv, Domain* theTclDomain, TclModelBuilder* theTclBuilder) { // ensure the destructor has not been called if (theTclBuilder == 0) { opserr << "WARNING builder has been destroyed - gradientInelasticBeamColumn\n"; return TCL_ERROR; } Element* theElement = 0; int ndm = theTclBuilder->getNDM(); int ndf = theTclBuilder->getNDF(); int tag; int eleArgStart = 1; if (ndm == 2) { // check plane frame problem has 3 dof per node if (ndf != 3) { opserr << "WARNING invalid ndf: " << ndf; opserr << ", for plane problem need 3 - gradientInelasticBeamColumn\n"; return TCL_ERROR; } // check the number of arguments is correct if ((argc - eleArgStart) < 10) { opserr << "WARNING insufficient arguments\n"; printCommand(argc, argv); opserr << "Want: gradientInelasticBeamColumn eleTag? iNode? jNode? numIntgrPts? endSecTag1? intSecTag? endSecTag2? secLR1? secLR2? lc? transfTag? <-constH> <-integration integrType?> <-iter maxIter? minTol? maxTol?> <-corControl auto/maxEpsInc? maxPhiInc?>\n"; return TCL_ERROR; } // get the id and end nodes int iNode, jNode, endSecTag1, intSecTag, endSecTag2, numIntegrPts, transfTag; double lc, secLR1, secLR2; int maxIter = 50; double minTol = 1E-10, maxTol = 1E-8; bool correctionControl = false; bool constH = false; double maxEpsInc = 0.0, maxPhiInc = 0.0; if (Tcl_GetInt(interp, argv[1 + eleArgStart], &tag) != TCL_OK) { opserr << "WARNING invalid gradientInelasticBeamColumn eleTag\n"; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[2 + eleArgStart], &iNode) != TCL_OK) { opserr << "WARNING invalid iNode"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[3 + eleArgStart], &jNode) != TCL_OK) { opserr << "WARNING invalid jNode"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[4 + eleArgStart], &numIntegrPts) != TCL_OK) { opserr << "WARNING invalid numIntegrPts"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[5 + eleArgStart], &endSecTag1) != TCL_OK) { opserr << "WARNING invalid firstSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[6 + eleArgStart], &intSecTag) != TCL_OK) { opserr << "WARNING invalid intSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[7 + eleArgStart], &endSecTag2) != TCL_OK) { opserr << "WARNING invalid lastSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* endSection1 = theTclBuilder->getSection(endSecTag1); if (!endSection1) { opserr << "WARNING end section not found"; opserr << " - section: " << endSecTag1; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* intSection = theTclBuilder->getSection(intSecTag); if (!intSection) { opserr << "WARNING intermediate section not found"; opserr << " - section: " << intSecTag; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* endSection2 = theTclBuilder->getSection(endSecTag2); if (!endSection2) { opserr << "WARNING end section not found"; opserr << " - section: " << endSecTag2; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[8 + eleArgStart], &secLR1) != TCL_OK) { opserr << "WARNING invalid secLR1"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[9 + eleArgStart], &secLR2) != TCL_OK) { opserr << "WARNING invalid secLR2"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[10 + eleArgStart], &lc) != TCL_OK) { opserr << "WARNING invalid lc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[11 + eleArgStart], &transfTag) != TCL_OK) { opserr << "WARNING invalid transfTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } CrdTransf* theTransf2d = OPS_getCrdTransf(transfTag); // was: theTclBuilder->getCrdTransf(transfTag); if (!theTransf2d) { opserr << "WARNING transformation not found"; opserr << " - transformation: " << transfTag; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } // check for optional arguments BeamIntegration* beamIntegr = 0; for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 1 < argc && strcmp(argv[i], "-integration") == 0) { if (strcmp(argv[i + 1], "NewtonCotes") == 0) { if (numIntegrPts > 20) { opserr << "WARNING number of integration points must be less than 20 for Newton-Cotes integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new NewtonCotesBeamIntegration(); } else if (strcmp(argv[i + 1], "Simpson") == 0) { if (((numIntegrPts - 1) % 2) != 0) { opserr << "WARNING number of integration points must be odd for Simpson's integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new SimpsonBeamIntegration(); } else if (strcmp(argv[i + 1], "Trapezoidal") == 0) beamIntegr = new TrapezoidalBeamIntegration(); else if (strcmp(argv[i + 1], "Lobatto") == 0) beamIntegr = new LobattoBeamIntegration(); else if (strcmp(argv[i + 1], "Legendre") == 0) beamIntegr = new LegendreBeamIntegration(); if (beamIntegr == 0) { opserr << "WARNING invalid integration type"; opserr << " - gradientInelasticBeamColumn element: " << tag; opserr << " - Simpson's integration method is used\n"; } } } if (!beamIntegr) { if (((numIntegrPts - 1) % 2) != 0) { opserr << "WARNING number of integration points must be odd for Simpson's integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new SimpsonBeamIntegration(); } for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 3 < argc && strcmp(argv[i], "-iter") == 0) { if (Tcl_GetInt(interp, argv[i + 1], &maxIter) != TCL_OK) { opserr << "WARNING invalid maxIter"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 2], &minTol) != TCL_OK) { opserr << "WARNING invalid minTol"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 3], &maxTol) != TCL_OK) { opserr << "WARNING invalid maxTol"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } } } for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 1 < argc && strcmp(argv[i], "-corControl") == 0) { correctionControl = true; if (i + 2 < argc && strcmp(argv[i + 1], "auto") != 0) { if (Tcl_GetDouble(interp, argv[i + 1], &maxEpsInc) != TCL_OK) { opserr << "WARNING invalid maxEpsInc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 2], &maxPhiInc) != TCL_OK) { opserr << "WARNING invalid maxPhiInc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } } } } for (int i = 12 + eleArgStart; i < argc; i++) if (strcmp(argv[i], "-constH") == 0) constH = true; // now create the NonlocalBeamColumn theElement = new GradientInelasticBeamColumn2d(tag, iNode, jNode, numIntegrPts, &endSection1, &intSection, &endSection2, secLR1, secLR2, *beamIntegr, *theTransf2d, lc, minTol, maxTol, maxIter, constH, correctionControl, maxEpsInc, maxPhiInc); if (!theElement) { opserr << "WARNING ran out of memory creating element"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } // then add the NonlocalBeamColumn to the domain if (theTclDomain->addElement(theElement) == false) { opserr << "WARNING could not add element to the domain"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; delete theElement; return TCL_ERROR; } } else if (ndm == 3) { // check plane frame problem has 6 dof per node if (ndf != 6) { opserr << "WARNING invalid ndf: " << ndf; opserr << ", for plane problem need 6 - gradientInelasticBeamColumn\n"; return TCL_ERROR; } // check the number of arguments is correct if ((argc - eleArgStart) < 10) { opserr << "WARNING insufficient arguments\n"; printCommand(argc, argv); opserr << "Want: gradientInelasticBeamColumn eleTag? iNode? jNode? numIntgrPts? endSecTag1? intSecTag? endSecTag2? secLR1? secLR2? lc? transfTag? <-constH> <-integration integrType?> <-iter maxIter? minTol? maxTol?> <-corControl auto/maxEpsInc? maxPhiInc?>\n"; return TCL_ERROR; } // get the id and end nodes int iNode, jNode, endSecTag1, intSecTag, endSecTag2, secOrder, numIntegrPts, transfTag; double lc, secLR1, secLR2; int maxIter = 50; double minTol = 1E-10, maxTol = 1E-8; bool correctionControl = false; bool constH = false; double maxEpsInc = 0.0, maxPhiInc = 0.0; if (Tcl_GetInt(interp, argv[1 + eleArgStart], &tag) != TCL_OK) { opserr << "WARNING invalid gradientInelasticBeamColumn eleTag\n"; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[2 + eleArgStart], &iNode) != TCL_OK) { opserr << "WARNING invalid iNode"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[3 + eleArgStart], &jNode) != TCL_OK) { opserr << "WARNING invalid jNode"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[4 + eleArgStart], &numIntegrPts) != TCL_OK) { opserr << "WARNING invalid numIntegrPts"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[5 + eleArgStart], &endSecTag1) != TCL_OK) { opserr << "WARNING invalid firstSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[6 + eleArgStart], &intSecTag) != TCL_OK) { opserr << "WARNING invalid intSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[7 + eleArgStart], &endSecTag2) != TCL_OK) { opserr << "WARNING invalid lastSecTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* endSection1 = theTclBuilder->getSection(endSecTag1); if (!endSection1) { opserr << "WARNING end section not found"; opserr << " - section: " << endSecTag1; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* intSection = theTclBuilder->getSection(intSecTag); if (!intSection) { opserr << "WARNING intermediate section not found"; opserr << " - section: " << intSecTag; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } SectionForceDeformation* endSection2 = theTclBuilder->getSection(endSecTag2); if (!endSection2) { opserr << "WARNING end section not found"; opserr << " - section: " << endSecTag2; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[8 + eleArgStart], &secLR1) != TCL_OK) { opserr << "WARNING invalid secLR1"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[9 + eleArgStart], &secLR2) != TCL_OK) { opserr << "WARNING invalid secLR2"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[10 + eleArgStart], &lc) != TCL_OK) { opserr << "WARNING invalid lc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[11 + eleArgStart], &transfTag) != TCL_OK) { opserr << "WARNING invalid transfTag"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } CrdTransf* theTransf3d = OPS_getCrdTransf(transfTag); // was: theTclBuilder->getCrdTransf3d(transfTag); if (!theTransf3d) { opserr << "WARNING transformation not found"; opserr << " - transformation: " << transfTag; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } // check for optional arguments BeamIntegration* beamIntegr = 0; for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 1 < argc && strcmp(argv[i], "-integration") == 0) { if (strcmp(argv[i + 1], "NewtonCotes") == 0) { if (numIntegrPts > 20) { opserr << "WARNING number of integration points must be less than 20 for Newton-Cotes integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new NewtonCotesBeamIntegration(); } else if (strcmp(argv[i + 1], "Simpson") == 0) { if (((numIntegrPts - 1) % 2) != 0) { opserr << "WARNING number of integration points must be odd for Simpson's integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new SimpsonBeamIntegration(); } else if (strcmp(argv[i + 1], "Trapezoidal") == 0) beamIntegr = new TrapezoidalBeamIntegration(); else if (strcmp(argv[i + 1], "Lobatto") == 0) beamIntegr = new LobattoBeamIntegration(); else if (strcmp(argv[i + 1], "Legendre") == 0) beamIntegr = new LegendreBeamIntegration(); if (beamIntegr == 0) { opserr << "WARNING invalid integration type"; opserr << " - gradientInelasticBeamColumn element: " << tag; opserr << " - Simpson's integration method is used\n"; } } } if (!beamIntegr) { if (((numIntegrPts - 1) % 2) != 0) { opserr << "WARNING number of integration points must be odd for Simpson's integration method"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } beamIntegr = new SimpsonBeamIntegration(); } for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 3 < argc && strcmp(argv[i], "-iter") == 0) { if (Tcl_GetInt(interp, argv[i + 1], &maxIter) != TCL_OK) { opserr << "WARNING invalid maxIter"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 2], &minTol) != TCL_OK) { opserr << "WARNING invalid minTol"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 3], &maxTol) != TCL_OK) { opserr << "WARNING invalid maxTol"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } } } for (int i = 12 + eleArgStart; i < argc; i++) { if (i + 1 < argc && strcmp(argv[i], "-corControl") == 0) { correctionControl = true; if (i + 2 < argc && strcmp(argv[i + 1], "auto") != 0) { if (Tcl_GetDouble(interp, argv[i + 1], &maxEpsInc) != TCL_OK) { opserr << "WARNING invalid maxEpsInc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i + 2], &maxPhiInc) != TCL_OK) { opserr << "WARNING invalid maxPhiInc"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } } } } for (int i = 12 + eleArgStart; i < argc; i++) if (strcmp(argv[i], "-constH") == 0) constH = true; // now create the NonlocalBeamColumn theElement = new GradientInelasticBeamColumn3d(tag, iNode, jNode, numIntegrPts, &endSection1, &intSection, &endSection2, secLR1, secLR2, *beamIntegr, *theTransf3d, lc, minTol, maxTol, maxIter, constH, correctionControl, maxEpsInc, maxPhiInc); if (!theElement) { opserr << "WARNING ran out of memory creating element"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; return TCL_ERROR; } // then add the NonlocalBeamColumn to the domain if (theTclDomain->addElement(theElement) == false) { opserr << "WARNING could not add element to the domain"; opserr << " - gradientInelasticBeamColumn element: " << tag << endln; delete theElement; return TCL_ERROR; } } else { opserr << "WARNING gradientInelasticBeamColumn command only works when ndm is 2 or 3, ndm: "; opserr << ndm << endln; return TCL_ERROR; } // if get here we have sucessfully created the NonlocalBeamColumn and added it to the domain return TCL_OK; }
LIN3S/CSSFoundation
src/js/ui/vanilla/atoms/FormSelect/FormSelect.js
<gh_stars>0 /* * This file is part of the Front Foundation package. * * Copyright (c) 2017-present LIN3S <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author <NAME> <<EMAIL>> */ import debounce from 'lodash.debounce'; import {onWindowResized, OneTimeEventPublisher, LifeTimeEventPublisher} from 'lin3s-event-bus'; import {getHtmlLang} from './../../../../dom'; import FormSelectInitializedEvent from './../../../../event-bus/FormSelect/FormSelectInitializedEvent'; import FormSelectOptionSelectedEvent from './../../../../event-bus/FormSelect/FormSelectOptionSelectedEvent'; import FormSelectStateChangedEvent from './../../../../event-bus/FormSelect/FormSelectStateChangedEvent'; import addSelectorFilteredEventListener from '../../../../dom/addSelectorFilteredEventListener'; import getDomNodeIndex from '../../../../dom/getDomNodeIndex'; import removeDomNodes from '../../../../dom/removeDomNodes'; import dispatchNativeEvent from '../../../../dom/dispatchNativeEvent'; const renderSelectOption = (optionValue, optionLabel) => { const option = document.createElement('option'); option.value = optionValue; option.textContent = optionLabel; return option; }, renderSelectOptionView = (optionValue, optionLabel) => { const optionView = document.createElement('div'); optionView.classList.add('form-select__option'); optionView.dataset.label = optionLabel; optionView.dataset.value = optionValue; optionView.textContent = optionLabel; return optionView; }; const isMobile = (viewportWidth, mobileBreakpoint = 1024) => viewportWidth < mobileBreakpoint; class FormSelect { static STATE = { OPENED: 'OPENED', CLOSED: 'CLOSED' }; constructor(domNode) { this.domNode = domNode; this.opened = this.domNode.classList.contains('form-select--opened'); this.focused = false; this.enabled = true; this.maxHeightDesktop = parseInt(this.domNode.dataset.maxHeightDesktop, 10); this.maxHeightMobile = parseInt(this.domNode.dataset.maxHeightMobile, 10); this.isFilterable = parseInt(this.domNode.dataset.filterable, 10) === 1; this.filterBy = this.domNode.dataset.filterOrderBy; this.mobileBreakpoint = parseInt(this.domNode.dataset.mobileBreakpoint, 10); this.outsideClickToCloseEnabled = parseInt(this.domNode.dataset.outsideClickToCloseEnabled, 10) === 1; this.mouseOverListenerEnabled = true; this.keyboardControlledSelectedOptionIndex = 0; this.lastFilterValue = ''; this.openedByFocus = false; if (this.isFilterable) { this.filterInput = this.domNode.querySelector('.form-select__input'); } this.select = this.domNode.querySelector('.form-select__select'); this.selectOptionsContainer = this.domNode.querySelector('.form-select__options-container'); this.selectOptions = this.domNode.querySelector('.form-select__options'); this.selectLabel = this.domNode.querySelector('.form-select__label'); this.debouncedFilter = debounce(() => this.filter(), 500); this.parseSelectOptions(); this.bindListeners(); this.setSelectOpened(this.opened); this.setInitiallySelectedOption(); this.publishFormSelectInitializedEvent(); } parseSelectOptions() { const selectOptions = this.select.querySelectorAll('option'); this.options = Array.from(selectOptions).map(selectOption => { return { value: selectOption.value.trim(), label: selectOption.textContent.trim() }; }); } getOptionsContainerNeedsOverflow(optionsContainerHeight) { return isMobile(this.windowWidth, this.mobileBreakpoint) && optionsContainerHeight >= this.maxHeightMobile || !isMobile(this.windowWidth, this.mobileBreakpoint) && optionsContainerHeight >= this.maxHeightDesktop; } setOptionsContainerHeight(height) { // Prevent overflow/scroll animation this.selectOptionsContainer.classList.toggle('form-select__options-container--no-overflow', !this.getOptionsContainerNeedsOverflow(height)); this.selectOptionsContainer.style.height = `${height}px`; } getOptionsContainerHeight() { const totalHeight = Array.from(this.domNode.querySelectorAll('.form-select__option')) .reduce((accumulatedHeight, option) => accumulatedHeight + option.offsetHeight, 0); if (isMobile(this.windowWidth, this.mobileBreakpoint) && totalHeight >= this.maxHeightMobile) { return this.maxHeightMobile; } else if (!isMobile(this.windowWidth, this.mobileBreakpoint) && totalHeight >= this.maxHeightDesktop) { return this.maxHeightDesktop; } return totalHeight; } bindListeners() { if (this.isFilterable) { this.filterInput.addEventListener('input', () => this.debouncedFilter()); this.filterInput.addEventListener('click', event => { if (this.opened) { event.stopPropagation(); } }); } if (this.outsideClickToCloseEnabled) { window.addEventListener('click', this.close.bind(this)); } this.domNode.addEventListener('focus', () => { this.setSelectFocused(true); if (this.tabHit) { return; } if (!this.isFilterable && !this.opened) { this.openedByFocus = true; } this.open(); }); addSelectorFilteredEventListener(this.domNode, 'click', '.form-select__option', this.onClick.bind(this)); this.domNode.addEventListener('click', event => { if (this.outsideClickToCloseEnabled) { event.stopPropagation(); } if (event.target === this.domNode || this.openedByFocus) { return; } this.setSelectOpened(!this.opened); }); addSelectorFilteredEventListener(this.domNode, 'mouseover', '.form-select__option', this.onMouseOver.bind(this)); addSelectorFilteredEventListener(this.domNode, 'mousemove', '.form-select__option', this.onMouseMove.bind(this)); this.domNode.addEventListener('keydown', this.onKeyDown.bind(this)); onWindowResized(this.onResize.bind(this)); } onClick(event) { this.setSelectedOption(event.target); } onMouseOver(event) { if (!this.mouseOverListenerEnabled) { return; } this.setKeyboardControlledSelectedOptionView( this.domNode.querySelectorAll('.form-select__option'), event.target ); this.keyboardControlledSelectedOptionIndex = getDomNodeIndex(event.target); } onMouseMove(event) { this.mouseOverListenerEnabled = true; } onKeyDown(event) { if (!(event.which === 40 || event.which === 38 || event.which === 13 || event.which === 9)) { return; } if (event.which === 9) { // tab if (this.opened) { this.tabHit = true; } this.close(); return; } event.preventDefault(); this.mouseOverListenerEnabled = false; const selectOptionViews = Array.from(this.domNode.querySelectorAll('.form-select__option')); if (event.which === 13) { // enter if (!this.opened && this.focused) { this.open(); } else { this.setSelectedOption(selectOptionViews[this.keyboardControlledSelectedOptionIndex]); this.close(); } } else if (event.which === 40) { // down this.keyboardControlledSelectedOptionIndex = this.keyboardControlledSelectedOptionIndex < selectOptionViews.length - 1 ? this.keyboardControlledSelectedOptionIndex + 1 : selectOptionViews.length - 1; this.setKeyboardControlledSelectedOptionView(selectOptionViews, selectOptionViews[this.keyboardControlledSelectedOptionIndex], true); } else if (event.which === 38) { // up this.keyboardControlledSelectedOptionIndex = this.keyboardControlledSelectedOptionIndex > 0 ? this.keyboardControlledSelectedOptionIndex - 1 : 0; this.setKeyboardControlledSelectedOptionView(selectOptionViews, selectOptionViews[this.keyboardControlledSelectedOptionIndex], true); } } onResize(windowResizedEvent) { this.windowWidth = windowResizedEvent.windowWidth || window.innerWidth; if (this.opened) { this.open(); } } setInitiallySelectedOption() { const selectedOption = this.select.querySelector('option[selected="selected"]'); if (selectedOption === null) { return; } this.onOptionSelected(selectedOption.textContent, selectedOption.value); } setSelectOpened(opened) { if (opened) { this.open(); } else { this.close(); } this.publishFormSelectStateChangedEvent(opened ? FormSelect.STATE.OPENED : FormSelect.STATE.CLOSED); } setSelectFocused(focused) { this.focused = focused; this.domNode.classList.toggle('form-select--focused', focused); } setSelectFocusable(focusable) { setTimeout(() => { this.domNode.tabIndex = focusable ? 0 : -1; }, 100); } open() { if (!this.enabled) { return; } this.domNode.classList.add('form-select--opened'); this.domNode.classList.toggle('form-select--editing-input', this.isFilterable); this.setOptionsContainerHeight(this.getOptionsContainerHeight()); this.opened = true; this.setSelectFocused(false); if (this.isFilterable) { setTimeout(() => { if (this.opened) { this.filterInput.focus(); } }, 100); } this.setSelectFocusable(false); } close() { if (!this.enabled) { return; } this.domNode.classList.remove('form-select--opened'); this.domNode.classList.remove('form-select--editing-input'); this.setOptionsContainerHeight(0); this.opened = false; this.setSelectFocused(false); this.tabHit = false; if (this.isFilterable) { this.filterInput.blur(); } this.setSelectFocusable(true); this.openedByFocus = false; } onOptionSelected(optionLabel, optionValue, publishEvent = true) { if (!this.enabled) { return; } // Explicitly cast to String const label = String(optionLabel), value = String(optionValue); if (this.selectedOptionLabel === optionLabel || this.selectedOptionValue === optionValue) { return; } this.setSelectValue(value); this.setSelectLabelValue(label); this.setSelectActiveOption(value); this.selectedOptionLabel = optionLabel; this.selectedOptionValue = optionValue; if ((this.selectedOptionLabel !== undefined || this.selectedOptionValue !== undefined) && publishEvent) { this.publishFormSelectOptionSelectedEvent(value); } this.openedByFocus = false; } setSelectValue(value) { this.select.value = value; dispatchNativeEvent(this.select, 'input'); } setSelectLabelValue(value) { this.selectLabel.textContent = value; } setSelectActiveOption(optionValue) { Array.from(this.domNode.querySelectorAll('.form-select__option')).forEach(selectOption => selectOption.classList.toggle('form-select__option--active', String(selectOption.dataset.value) === String(optionValue) )); } setSelectedOptionByOptionValue(optionValue) { const option = this.domNode.querySelector(`.form-select__option[data-value="${optionValue}"]`), label = option.getAttribute('data-label'); this.onOptionSelected(label, optionValue, false); } update({options, publishEvent = true} = {}) { this.close(); this.destroy(); if (options.length === 0) { return; } this.build(options); this.setSelectedOptionDefault(publishEvent); } destroy() { removeDomNodes( this.domNode.querySelectorAll('.form-select__option:not(.form-select__option--select-no-selection), option:not(.form-select__select-no-selection)') // eslint-disable-line max-len ); this.filterInput.value = ''; } build(options) { this.options = options; this.options.forEach(option => { this.select.appendChild(renderSelectOption(option.value, option.label)); this.selectOptions.appendChild(renderSelectOptionView(option.value, option.label)); }); this.setOptionsContainerHeight(this.getOptionsContainerHeight()); } filter() { const noSelectionValue = this.domNode.querySelector('.form-select__select-no-selection').value, filterValue = this.filterInput.value, filteredOptions = this.options.filter(option => option.label.toLowerCase().includes(filterValue.toLowerCase()) || filterValue === '' || option.value === noSelectionValue ); if (filterValue === this.lastFilterValue) { return; } this.lastFilterValue = filterValue; // Remove unnecessary ones this.options.forEach(option => { if (filteredOptions.indexOf(option) === -1) { const optionView = this.selectOptions.querySelectorAll(`[data-value="${option.value}"]`); removeDomNodes(optionView); } }); // Add necessary ones filteredOptions.forEach(filteredOption => { const selectOption = this.domNode.querySelector(`.form-select__option[data-value="${filteredOption.value}"]`); if (selectOption === null) { // Find place to inject const currentSelectOptionViews = Array.from(this.domNode.querySelectorAll('.form-select__option + .form-select__option')), // eslint-disable-line max-len newSelectOption = renderSelectOption(filteredOption.value, filteredOption.label), newSelectOptionView = renderSelectOptionView(filteredOption.value, filteredOption.label); let found = false, index = 0; while (index < currentSelectOptionViews.length && !found) { const currentSelectOption = currentSelectOptionViews[index]; const isInteger = (!isNaN(parseInt(currentSelectOption.getAttribute(`data-${this.filterBy}`), 10)) && !isNaN(parseInt(filteredOption[`${this.filterBy}`], 10))); const currentOptionIsBiggerThanFilteredOne = isInteger ? parseInt(currentSelectOption.getAttribute(`data-${this.filterBy}`), 10) > parseInt(filteredOption[`${this.filterBy}`], 10) // eslint-disable-line max-len : String(currentSelectOption.getAttribute(`data-${this.filterBy}`)).trim().localeCompare(filteredOption[`${this.filterBy}`], getHtmlLang(), {sensitivity: 'base'}) > 0; // eslint-disable-line max-len if (currentOptionIsBiggerThanFilteredOne) { found = true; } index++; } if (found) { const currentOption = Array.from(this.select.querySelectorAll('option'))[index], currentOptionView = Array.from(this.domNode.querySelectorAll('.form-select__option'))[index]; this.select.insertBefore(newSelectOption, currentOption); this.selectOptions.insertBefore(newSelectOptionView, currentOptionView); } else { this.select.appendChild(newSelectOption); this.selectOptions.appendChild(newSelectOptionView); } } }); this.setOptionsContainerHeight(this.getOptionsContainerHeight()); // select none this.setSelectedOptionDefault(false); } setSelectedOptionDefault(publishEvent = true) { const noSelection = this.domNode.querySelector('.form-select__select-no-selection'); this.onOptionSelected(noSelection.textContent.trim(), noSelection.value.trim(), publishEvent); } setSelectedOption(option) { this.onOptionSelected(option.dataset.label, option.dataset.value); } setKeyboardControlledSelectedOptionView(selectOptionViews, optionView, animateScroll = false) { Array.from(selectOptionViews).forEach(selectOptionView => selectOptionView.classList.remove('form-select__option--hover')); if (optionView === undefined) { return; } optionView.classList.add('form-select__option--hover'); // Scroll to option if (!animateScroll) { return; } optionView.scrollIntoView({behaviour: 'smooth'}); } enable() { this.enabled = true; } disable() { this.enabled = false; } publishFormSelectInitializedEvent() { OneTimeEventPublisher.publish(new FormSelectInitializedEvent(this)); } publishFormSelectOptionSelectedEvent(value) { LifeTimeEventPublisher.publish(new FormSelectOptionSelectedEvent(this, value)); } publishFormSelectStateChangedEvent(state) { LifeTimeEventPublisher.publish(new FormSelectStateChangedEvent(this, state)); } } export default FormSelect;
black-vision-engine/bv-engine
BlackVision/LibCore/Source/System/InitSubsystem.h
#pragma once namespace bv { class InitSubsystem { public: typedef void (*Initializer)( int argc, char * argv[] ); static void AddInitializer ( Initializer fun ); static void CallInitializers ( int argc, char * argv[] ); private: enum { MAX_ELEMENTS = 512 }; static int m_sNumInitializers; static Initializer m_sInitializers[ MAX_ELEMENTS ]; }; } //bv
sidgairo18/Programming-Practice
codeforces/665_2/c.cpp
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vector<int> v(n); vector<int> small; vector<int> out(n,-1); int mn = 1e9+1; for(int i = 0; i<n; i++){ cin>>v[i]; mn = min(v[i], mn); } for(int i = 0; i<n; i++){ if(v[i] % mn == 0) small.push_back(v[i]); else out[i] = v[i]; } sort(small.begin(), small.end()); int j = 0; for(int i = 0; i<n; i++){ if(out[i] > -1) continue; else out[i] = small[j++]; } int check = 1; for(int i = 1; i<n; i++){ if(out[i] >= out[i-1]) continue; else{ check =0; break; } } if(check) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
wallberg-umd/fcrepo-api-x
fcrepo-api-x-integration/src/test/java/org/fcrepo/apix/integration/StreamingIT.java
/* * Licensed to DuraSpace under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * DuraSpace licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fcrepo.apix.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import org.fcrepo.client.FcrepoOperationFailedException; import org.fcrepo.client.FcrepoResponse; import org.apache.camel.CamelContext; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.model.ModelCamelContext; import org.apache.commons.io.input.NullInputStream; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.ResourceFactory; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.util.Filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Integration tests relating to streaming content proxied by API-X * * @author esm */ @RunWith(PaxExam.class) public class StreamingIT implements KarafIT { private static final Logger LOG = LoggerFactory.getLogger(StreamingIT.class); private static final URI APIX_BASE_URI = URI.create(apixBaseURI); private static final String INTERCEPT_ROUTE_ID = "execute-intercept"; private static final String CONTEXT_NAME = "apix-core"; private static final String CONTEXT_ROLE = "routing-context"; private URI binaryContainer; private URI binaryResource; private String binaryResourceSha; private static MessageDigest sha1; @Rule public TestName name = new TestName(); @Inject @Filter("(role=" + CONTEXT_ROLE + ")") private CamelContext ctx; @Override public String testClassName() { return this.getClass().getSimpleName(); } @Override public String testMethodName() { return name.getMethodName(); } @BeforeClass public static void initMessageDigest() throws NoSuchAlgorithmException { sha1 = MessageDigest.getInstance("SHA-1"); } /** * Creates a container and a binary resource of 2MiB + 1 bytes long. Retrieves checksum of the resource. * * @throws FcrepoOperationFailedException if unexpected things go wrong * @throws IOException if unexpected things go wrong * @throws URISyntaxException if unexpected things go wrong */ @Before public void initBinaryResources() throws FcrepoOperationFailedException, IOException, URISyntaxException { binaryContainer = URI.create(String.format("%s%s", fcrepoBaseURI, testClassName() + "/binaries/")); // Create container if it doesn't already exist if (!resourceExists(binaryContainer)) { try (FileInputStream body = new FileInputStream( new File(testResources, "objects/binary_container.ttl")); FcrepoResponse r = client.put(binaryContainer) .body(body, "text/turtle") .perform()) { assertEquals("Failed to create binary container '" + binaryContainer + "'", 201, r.getStatusCode()); } } // Create the binary resource if it doesn't already exist final URI expectedBinaryResource = appendToPath(binaryContainer, "large-binary"); if (!resourceExists(expectedBinaryResource)) { LOG.warn("Expected resource did not exist {}", expectedBinaryResource); try (InputStream body = new NullInputStream((2 * 1024 * 1024) + 1)) { binaryResource = postFromStream( body, binaryContainer, "application/octet-stream", "large-binary"); } catch (final Exception e) { fail(String.format("Failed to create binary LDPR: %s", e.getMessage())); } } else { binaryResource = expectedBinaryResource; } // Retrieve the checksum calculated by Fedora binaryResourceSha = ModelFactory.createDefaultModel() .read(client .get(appendToPath(binaryResource, "/fcr:metadata")) .accept("application/rdf+xml") .perform().getBody(), null) .listObjectsOfProperty( ResourceFactory .createProperty("http://www.loc.gov/premis/rdf/v1#", "hasMessageDigest")) .mapWith((digestValue) -> digestValue.toString().substring("urn:sha1:".length())) .next(); assertNotNull("Missing http://www.loc.gov/premis/rdf/v1#hasMessageDigest on " + appendToPath(binaryResource, "/fcr:metadata").toString(), binaryResourceSha); } /** * Smoke test insuring Karaf is doing what we think it is doing */ @Before public void verifyContextAndRoute() { assertNotNull("No context", ctx); assertEquals("Unexpected context " + ctx.getName(), CONTEXT_NAME, ctx.getName()); assertNotNull("No route (ctx name: " + ctx.getName() + ")", ctx.getRouteDefinition(INTERCEPT_ROUTE_ID)); } /** * Verify the binary can be retrieved from Fedora. The request should <em>not</em> be intercepted. * * @throws Exception if unexpected things go wrong */ @Test public void testRetrieveLargeBinaryFromFedora() throws Exception { // Record 'true' if the intercepting route is triggered final AtomicBoolean intercepted = new AtomicBoolean(false); ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveAddFirst().process((ex) -> intercepted.set(true)); } }); final long expectedSize = (2 * 1024 * 1024) + 1; final long actualSize; final String actualDigest; try (FcrepoResponse r = client.get(binaryResource).perform(); DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) { actualSize = drain(body); actualDigest = asHex(body.getMessageDigest().digest()); } // The resource can be retrieved intact assertEquals(expectedSize, actualSize); assertEquals(binaryResourceSha, actualDigest); // And the request was not proxied by API-X assertFalse(String.format("Unexpected interception of a Fedora resource URI %s by route %s", binaryResource.toString(), INTERCEPT_ROUTE_ID), intercepted.get()); } /** * Verify the binary can be retrieved through the API-X proxy. The request should be intercepted and proxied by * API-X. * * @throws Exception if unexpected things go wrong */ @Test public void testRetrieveLargeBinaryFromApix() throws Exception { // Record 'true' if the intercepting route is triggered final AtomicBoolean intercepted = new AtomicBoolean(false); ctx.getRouteDefinition(INTERCEPT_ROUTE_ID).adviceWith((ModelCamelContext) ctx, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { weaveAddFirst().process((ex) -> intercepted.set(true)); } }); final long expectedSize = (2 * 1024 * 1024) + 1; final long actualSize; final String actualDigest; final URI proxiedResource = proxied(binaryResource); try (FcrepoResponse r = KarafIT.attempt(30, () -> client.get(proxiedResource).perform()); DigestInputStream body = new DigestInputStream(r.getBody(), sha1)) { actualSize = drain(body); actualDigest = asHex(body.getMessageDigest().digest()); } // The request _was_ proxied by API-X assertTrue(String.format("Expected the retrieval of %s to be proxied by API-X, route id %s", proxiedResource, INTERCEPT_ROUTE_ID), intercepted.get()); // And resource can be retrieved intact assertEquals(expectedSize, actualSize); assertEquals(binaryResourceSha, actualDigest); } /** * Returns true if the URI exists (i.e. responds with a 200 to a HEAD request). * * @param resource some HTTP resource * @return true if the resource exists, false otherwise * @throws IOException if there is an error determining whether the resource exists */ private boolean resourceExists(final URI resource) throws IOException { try (FcrepoResponse r = client.head(resource).perform()) { if (r.getStatusCode() == 200) { return true; } } catch (final FcrepoOperationFailedException e) { // Probably the resource doesn't exist. LOG.debug("Error retrieving resource '" + resource + "': " + e.getMessage(), e); } return false; } /** * Reads the input stream to exhaustion and returns the number of bytes read. * * @param in the stream to exhaust * @return the number of bytes read * @throws IOException */ private static long drain(final InputStream in) throws IOException { final byte[] buf = new byte[1024 * 128]; long size = 0; for (int i = in.read(buf, 0, buf.length); i > -1; i = in.read(buf, 0, i)) { size += i; } return size; } /** * Coverts the supplied byte array to a String hexadecimal representation, starting with the most significant bit. * * @param digest a byte array containing a message digest * @return a hexadecimal string representation of the message digest */ private static String asHex(final byte[] digest) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < digest.length; i++) { buf.append( String.format("%02x", Byte.toUnsignedInt(digest[i]))); } return buf.toString(); } /** * Assuming the supplied URI targets the <em>Fedora repository</em> (i.e. <em>a URI that is not proxied by * API-X</em>), returns an equivalent URI that targets the same resource through the API-X proxy. * * @param toProxy a URI that targets an un-proxied Fedora resource * @return an equivalent URI targeting the proxied Fedora resource * @throws URISyntaxException */ private static URI proxied(final URI toProxy) throws URISyntaxException { if (isProxied(toProxy)) { return toProxy; } return appendToPath(APIX_BASE_URI, toProxy.getPath()); } /** * Appends the path to the URI. All other components of the URI are preserved. * * @param uri the URI with the path being appended to * @param toAppend the path to be appended to the URI * @return a new URI with a path component ending with {@code toAppend} * @throws URISyntaxException */ private static URI appendToPath(final URI uri, final String toAppend) throws URISyntaxException { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + toAppend, uri.getRawQuery(), uri.getRawFragment()); } /** * Returns true if the supplied URI will be proxied by API-X * * @param uri a candidate uri that might be proxied API-X * @return true if the supplied URI will be proxied by API-X, false otherwise */ private static boolean isProxied(final URI uri) { return uri.getScheme().equals(APIX_BASE_URI.getScheme()) && uri.getHost().equals(APIX_BASE_URI.getHost()) && uri.getPort() == APIX_BASE_URI.getPort(); } }
softberries/sfs-mysql
src/main/java/com/softwarepassion/sfs/SfsApplication.java
package com.softwarepassion.sfs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableCaching @EnableAsync public class SfsApplication { public static void main(String[] args) { SpringApplication.run(SfsApplication.class, args); } }
ZeroZill/MulDiJson
src/main/java/org/zerozill/muldijson/parser/AbstractJsonParser.java
<gh_stars>0 package org.zerozill.muldijson.parser; import org.zerozill.muldijson.behavior.Deserializable; import org.zerozill.muldijson.behavior.Parsable; import org.zerozill.muldijson.behavior.Serializable; import org.zerozill.muldijson.behavior.Writable; public abstract class AbstractJsonParser implements Serializable, Deserializable, Parsable, Writable { public Parsers parserType; public boolean isBeanTypeParser() { return ParserClassification.isType(parserType, ParserClassification.BEAN_TYPE); } public boolean isNonBeanTypeParser() { return ParserClassification.isType(parserType, ParserClassification.NON_BEAN_TYPE); } }
AllaMaevskaya/AliRoot
T0/T0base/AliT0LookUpKey.cxx
<gh_stars>10-100 /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /************************************************************************* * class for logical adress of chanells: * can be call by nubmer or by name * * Alla.<EMAIL>v<EMAIL> ************************************************************************/ #include "AliT0LookUpKey.h" ClassImp(AliT0LookUpKey) AliT0LookUpKey::AliT0LookUpKey(): TObject(), fKey(0), fName("") { } //-------------------------------------------------------------------------------------- AliT0LookUpKey::AliT0LookUpKey(Int_t key): TObject(), fKey(key), fName("") { } //-------------------------------------------------------------------------------------- AliT0LookUpKey::AliT0LookUpKey(TString name): TObject(), fKey(), fName(name) { } //________________________________________________________________ AliT0LookUpKey::AliT0LookUpKey(const AliT0LookUpKey& o) : TObject(), fKey(), fName("") { // copy constructor ((AliT0LookUpKey&) o).Copy(*this); } //-------------------------------------------------------------------------------------- Bool_t AliT0LookUpKey:: IsEqual(const TObject* obj) const { Int_t k; // printf("IsEqual\n"); k=((AliT0LookUpKey*)obj)->GetKey(); if (k==fKey) return kTRUE; else return kFALSE; } //-------------------------------------------------------------------------------------- void AliT0LookUpKey::Print(Option_t *) const { printf(" AliT0LookUpKey key %i name %s\n",fKey,fName.Data()); }
eriknyquist/wip
text_game_maker/tile/tile.py
<gh_stars>1-10 import copy from text_game_maker.utils import utils from text_game_maker.materials.materials import get_properties from text_game_maker.game_objects.base import GameEntity, serialize, deserialize from text_game_maker.game_objects.items import Lockpick from text_game_maker.event.event import Event ITEMS_KEY = "items" PEOPLE_KEY = "people" TILE_ID_KEY = "tile_id" ENTER_EVENT_KEY = "enter_event" EXIT_EVENT_KEY = "exit_event" _tiles = {} def _register_tile(tile, tile_id=None): if tile_id is None: ret = Tile.tile_id Tile.tile_id += 1 else: ret = tile_id _tiles[ret] = tile return ret def unregister_tile_id(tile_id): """ Unregister a tile ID so it can be used again. Should only be used if you are deleting all instances of a tile object. :param tile_id: tile ID to unregister """ if tile_id not in _tiles: return del _tiles[tile_id] def get_tile_by_id(tile_id): """ Get Tile instance by tile ID :param tile_id: ID of tile to fetch :return: tile instance :rtype: text_game_maker.tile.tile.Tile """ if tile_id not in _tiles: return None return _tiles[tile_id] def reverse_direction(direction): """ Returns the opposite direction for a given direction, e.g. "north" becomes "south" :param str direction: direction to reverse :return: opposite direction. None if invalid direction is provided :rtype: str """ if not direction: return None if direction == 'north': return 'south' elif direction == 'south': return 'north' elif direction == 'east': return 'west' elif direction == 'west': return 'east' return None def crawler(start): """ Crawl over a map and serialize all tiles and contained items :param text_game_maker.tile.tile.Tile start: map starting tile :return: serializable dict representing all tiles and contained items :rtype: dict """ ret = [] tilestack = [start] seen = [] if not isinstance(start, Tile): raise ValueError("%s should be called with a Tile object" % __func__) while tilestack: tile = tilestack.pop() if tile.tile_id in seen: continue ret.append(tile.get_attrs()) seen.append(tile.tile_id) if isinstance(tile, LockedDoor) and tile.replacement_tile: tilestack.append(tile.replacement_tile) else: for t in tile.iterate_directions(): tilestack.append(t) return ret def builder(tiledata, start_tile_id, version, clear_old_tiles=True): """ Deserialize a list of serialized tiles, then re-link all the tiles to re-create the map described by the tile links :param list tiledata: list of serialized tiles :param start_tile_id: tile ID of tile that should be used as the start tile :param str version: object model version of the tile data to be deserialized :return: starting tile of built map :rtype: text_game_maker.tile.tile.Tile """ tiles = {} visited = [] if clear_old_tiles: _tiles.clear() for d in tiledata: tile = deserialize(d, version) tiles[tile.tile_id] = tile if start_tile_id not in tiles: raise RuntimeError("No tile found with ID '%s'" % start_tile_id) tilestack = [tiles[start_tile_id]] while tilestack: t = tilestack.pop(0) if t.tile_id in visited: continue visited.append(t.tile_id) if isinstance(t, LockedDoor) and t.replacement_tile: if t.replacement_tile: t.replacement_tile = tiles[t.replacement_tile] tilestack.append(t.replacement_tile) if t.source_tile: t.source_tile = tiles[t.source_tile] tilestack.append(t.source_tile) else: for direction in ['north', 'south', 'east', 'west']: tile_id = getattr(t, direction) if not tile_id: continue setattr(t, direction, tiles[tile_id]) tilestack.append(tiles[tile_id]) return tiles[start_tile_id] class Tile(GameEntity): """ Represents a single 'tile' or 'room' in the game """ tile_id = 0 default_locations = [ "on the ground" ] def __init__(self, name=None, description=None): """ Initialise a Tile instance :param str name: short description, e.g. "a dark cellar" :param str description: long description, printed when player enters\ the room e.g. "a dark, scary cellar with blah blah blah... " """ super(Tile, self).__init__() self.description = "" self.name = name self.original_name = self.name self.enter_event = Event() self.exit_event = Event() self.name_from_dir = { "north": None, "south": None, "east": None, "west": None } if description: self.description = utils._remove_leading_whitespace(description) # Adjacent tiles to the north, south, east and west of this tile self.north = None self.south = None self.east = None self.west = None # First time visiting this tile? self.first_visit = True self.first_visit_message = None # Show first visit message even if player can't see anything? self.first_visit_message_in_dark = False # Does this tile require a light source? self.dark = False # Items on this tile self.items = {loc: [] for loc in self.default_locations} # People on this tile self.people = {} self.smell_description = None self.ground_smell_description = None self.ground_taste_description = None self.material = None self.tile_id = _register_tile(self) def copy(self): new = copy.deepcopy(self) for t in new.iterate_directions(): t = None new.items = {} for loc in self.items: for item in self.items[loc]: new.add_item(item.copy()) return new def set_name_from_north(self, name): """ Set the name that will be shown when player looks at this tile from an adjacent tile north from this tile :param str desc: description text """ self.name_from_dir["north"] = name def set_name_from_south(self, name): """ Set the name that will be shown when player looks at this tile from an adjacent tile south from this tile :param str desc: description text """ self.name_from_dir["south"] = name def set_name_from_east(self, name): """ Set the name that will be shown when player looks at this tile from an adjacent tile east from this tile :param str desc: description text """ self.name_from_dir["east"] = name def set_name_from_west(self, name): """ Set the name that will be shown when player looks at this tile from an adjacent tile west from this tile :param str desc: description text """ self.name_from_dir["west"] = name def matches_name(self, name): """ Check if a string fuzzily matches the name of this tile :param str name: string to check :return: True if string fuzzily matches this tiles name :rtype: bool """ if name.startswith("the"): name = name[4:] return name in self.name @property def map_identifier(self): if self.name in ["", None]: return str(self.tile_id) return self.name def on_smell(self): """ Called when player types 'smell' or equivalent on this tile """ if self.smell_description: utils.game_print(self.smell_description) return utils.game_print("It doesn't smell like anything in particular here.") def on_smell_ground(self): """ Called when player types 'smell ground' or equivalent on this tile """ if self.ground_smell_description: utils.game_print(self.ground_smell_description) return if self.material: utils.game_print("The ground smells %s." % get_properties(self.material).smell) return utils.game_print("The ground doesn't smell like anything in " "particular.") def on_taste_ground(self): """ Called when player types 'taste ground' or equivalent on this tile """ if self.ground_taste_description: utils.game_print(self.ground_taste_description) return if self.material: utils.game_print("The ground tastes %s." % get_properties(self.material).taste) return utils.game_print("The ground doesn't taste like anything in " "particular.") def set_tile_id(self, tile_id): """ Sets the ID for this tile. This ID will be used to represent the tile in save files. Setting explicit tile names is recommended, as it ensures that the tile IDs will not change. If the ID of a tile changes, save files created with previous tile IDs will no longer work as expected. :param tile_id: tile ID """ if tile_id in _tiles: raise RuntimeError("tile ID '%s' is already in use" % tile_id) if self.tile_id in _tiles: del _tiles[self.tile_id] _tiles[tile_id] = self self.tile_id = tile_id def get_special_attrs(self): ret = {} for tile in self.iterate_directions(): d = self.direction_to(tile) ret[d] = tile.tile_id ret['items'] = {x:serialize(self.items[x]) for x in self.items} ret['people'] = {x:serialize(self.people[x]) for x in self.people} ret['enter_event'] = self.enter_event.serialize() ret['exit_event'] = self.exit_event.serialize() return ret def set_special_attrs(self, data, version): self.items = {} if ITEMS_KEY in data: for loc in data[ITEMS_KEY]: for d in data[ITEMS_KEY][loc]: item = deserialize(d, version) self.add_item(item) del data[ITEMS_KEY] self.people = {} if PEOPLE_KEY in data: for name in data[PEOPLE_KEY]: self.people[name] = deserialize(data[PEOPLE_KEY][name], version) del data[PEOPLE_KEY] self.set_tile_id(data[TILE_ID_KEY]) del data[TILE_ID_KEY] if ENTER_EVENT_KEY in data: self.enter_event.deserialize(data[ENTER_EVENT_KEY]) del data[ENTER_EVENT_KEY] if EXIT_EVENT_KEY in data: self.exit_event.deserialize(data[EXIT_EVENT_KEY]) del data[EXIT_EVENT_KEY] return data def iterate_directions(self): """ Iterator for all tiles connected to this tile :return: tile iterator :rtype: Iterator[:class:`text_game_maker.tile.tile.Tile`] """ for tile in [self.north, self.south, self.east, self.west]: if tile is None: continue yield tile def is_connected_to(self, tile): """ Checks if this tile is connected to the given tile :param Tile tile: tile to check against this tile :return: True if tile is connected to this tile, False otherwise :rtype: bool """ for connected in self.iterate_directions(): if tile is connected: return True return False def is_door(self): return False def direction_to(self, tile): """ Get the direction from this tile to the given tile :param Tile tile: tile to check the direction to :return: direction to the given tile :rtype: str """ if not tile: return None if tile == self.north: return 'north' elif tile == self.south: return 'south' elif tile == self.east: return 'east' elif tile == self.west: return 'west' return None def direction_from(self, tile): """ Get the direction from the given tile to this tile :param Tile tile: tile to check the direction from :return: direction from the given tile to this tile :rtype: str """ return reverse_direction(self.direction_to(tile)) # Enter/exit methods def on_enter(self, player, src): """ Called when player tries to move into this tile. If on_enter returns True, the player will be moved to this tile. If False, the move will not be allowed. :param text_game_maker.player.player.Player player: player object :param text_game_maker.tile.tile.Tile src: tile that player is\ currently on :return: True if player move should be allowed :rtype: bool """ return True def on_exit(self, player, dest): """ Called when player tries to move out of this tile. If on_exit returns True, the player will be moved to ``dest``. If False, the move will not be allowed. :param text_game_maker.player.player.Player player: player object :param text_game_maker.tile.tile.Tile dest: tile that player is\ trying to move to :return: True if player move should be allowed :rtype: bool """ return True def _get_name(self, tile, name): if tile: return "to the %s is %s" % (name, tile.name) else: return None def _item_descriptions(self, items, testfunc=None): if not items: return None ret = "" for loc in items: itemlist = [] for item in items[loc]: if (not testfunc) or testfunc(item): itemlist.append(str(item)) if not itemlist: continue elif len(itemlist) > 1: english = utils.list_to_english(itemlist) sentence = '%s are %s. ' % (english, loc) else: sentence = '%s %s %s. ' % (itemlist[0], items[loc][0].verb, loc) ret += sentence return ret def describe_scene(self): """ Return sentences describing all scenery items on this tile :return: description of scenery on this tile :rtype: str """ return self._item_descriptions(self.items, lambda x: x.scenery) def describe_items(self): """ Return sentences describing all non-scenery items on this tile :return: description of non-scenery on this tile :rtype: str """ return self._item_descriptions(self.items, lambda x: not x.scenery) def describe_people(self): """ Return sentences describing all people on this tile :return: description of all people (NPCs) on this tile :rtype: str """ return self._item_descriptions(self.people) def add_item(self, item): """ Add item to this tile :param GameEntity item: item to add :return: the added item """ if item.location not in self.items: self.items[item.location] = [] return item.move(self.items[item.location]) def add_person(self, person): """ Add person to this tile :param text_game_maker.game_objects.person.Person: person to add """ if person.location not in self.people: self.people[person.location] = [] if person in self.people[person.location]: return person.tile_id = self.tile_id person.move(self.people[person.location]) def summary(self): """ Return a description of all available directions from this tile that the player can see :return: description of all available directions from this tile :rtype: str """ ret = [] north = self._get_name(self.north, 'north') south = self._get_name(self.south, 'south') east = self._get_name(self.east, 'east') west = self._get_name(self.west, 'west') if north: ret.append(north) if south: ret.append(south) if east: ret.append(east) if west: ret.append(west) return '%s. ' % ('. '.join(ret)) if ret else '' class LockedDoor(Tile): """ Locked door with a mechanical lock, requires a key or lockpick to unlock """ def __init__(self, prefix="", name="", src_tile="", replacement_tile=""): if prefix in ["", None]: prefix = "a" if name in ["", None]: name = "door" super(LockedDoor, self).__init__(name, "") self.name = '%s %s' % (prefix, name) self.short_name = name self.prefix = prefix self.locked = True self.source_tile = src_tile self.replacement_tile = replacement_tile @property def prep(self): if self._prep in ["", None]: return "the " + str(self.short_name) return self._prep @prep.setter def prep(self, val): self._prep = val def get_special_attrs(self): ret = super(LockedDoor, self).get_special_attrs() for name in ['source_tile', 'replacement_tile']: tile = getattr(self, name) if isinstance(tile, GameEntity): ret[name] = tile.tile_id else: ret[name] = tile return ret def is_door(self): return True def on_open(self, player): """ Called when player attempts to open this door :param text_game_maker.player.player.Player player: player object """ pick = utils.find_inventory_item_class(player, Lockpick) if not pick: utils._wrap_print("You need a key or a lockpick to unlock %s" % self.prep) return # TODO: add logic for unlocking with keys self.unlock() if pick.uses <= 1: utils.game_print("%s has seen its last use, and breaks into pieces " "in your hand" % pick.prep) pick.delete() else: pick.uses -= 1 def matches_name(self, name): """ Check if a string fuzzily matches the name of this door :param str name: string to check :return: True if string fuzzily matches this doors name :rtype: bool """ if name.startswith("the"): name = name[4:] return name in self.short_name def unlock(self): """ Unlocks the door, revealing whichever tile is connected behind it """ if not self.locked: return direction = self.source_tile.direction_to(self) if not direction: return setattr(self.source_tile, direction, self.replacement_tile) msg = "You unlock the %s, revealing %s to the %s." % (self.short_name, self.replacement_tile.name, direction) utils.game_print(msg) self.locked = False def on_enter(self, player, src): if self.locked: utils._wrap_print("%s is locked." % self.short_name) return False class LockedDoorWithKeypad(LockedDoor): """ Locked door with an electronic lock, can be opened with a numeric code """ def __init__(self, unlock_code=None, **kwargs): super(LockedDoorWithKeypad, self).__init__(**kwargs) self.unlock_code = unlock_code self.prompt = "Enter keypad code to unlock the door" def set_prompt(self, prompt): """ Set text to be display when prompting player to input keypad code :param str prompt: text to prompt with """ self.prompt = prompt def on_open(self, player): """ Called when playyer attempts to open this door. :param text_game_maker.player.player.Player player: player object """ while True: code = utils.read_line_raw(self.prompt, cancel_word="cancel") if (code == None) or (code.strip() == ""): utils.game_print("Cancelled.") return try: intcode = int(code) except: utils.game_print("Keypad code not acccepted.") continue if intcode != self.unlock_code: utils.game_print("Keypad code not acccepted.") continue break utils.game_print("Keypad code accepted!") self.unlock() def on_enter(self, player, src): self.on_open(player)
shurcooL/eX0
eX0-go/particles.go
<gh_stars>10-100 package main import ( "fmt" "sync" "github.com/go-gl/mathgl/mgl32" ) type particleSystem struct { sync.Mutex particles []particle } func (ps *particleSystem) Add(position, velocity mgl32.Vec2, bornAt, maxAge float64) { ps.Lock() defer ps.Unlock() ps.particles = append(ps.particles, particle{ Position: position, Velocity: velocity, BornAt: bornAt, Time: bornAt, DieAt: bornAt + maxAge, }) } func (ps *particleSystem) Tick(now float64) { ps.Lock() defer ps.Unlock() // Movement. for i := range ps.particles { p := &ps.particles[i] for p.Time <= now { p.Time += 1.0 / commandRate if p.Time >= p.DieAt { fmt.Printf("BOOM at x=%f, y=%f and LogicTime=%.20f\n", p.Position.X(), p.Position.Y(), p.DieAt) break } p.Position = p.Position.Add(p.Velocity) //fmt.Printf("%f: bouncy bullet vel: %f (%t)\n", p.Time, p.Velocity.Len(), p.Age(p.Time) < 1.75) if p.Age(p.Time) < 1.75 { // Slow down minimally during its first 1.75 seconds of life. p.Velocity = p.Velocity.Mul(0.990) } else { // Slow down significantly during its last 1.25 seconds of life. x := p.Velocity.Len() - 0.2 if x < 0.01 { x = 0.01 } p.Velocity = p.Velocity.Normalize().Mul(x) } } } // Remove dead particles. var alive []particle for _, p := range ps.particles { if p.Time >= p.DieAt { // Dead particle, skip it. continue } alive = append(alive, p) } ps.particles = alive } type particle struct { Position mgl32.Vec2 Velocity mgl32.Vec2 BornAt float64 Time float64 DieAt float64 } func (p particle) Age(now float64) float64 { return now - p.BornAt }
ckamtsikis/cmssw
RecoParticleFlow/PFClusterProducer/plugins/PFMultiDepthClusterizer.cc
<reponame>ckamtsikis/cmssw<gh_stars>1-10 #include "PFMultiDepthClusterizer.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/Math/interface/deltaR.h" #include "DataFormats/Math/interface/deltaPhi.h" #include "Math/GenVector/VectorUtil.h" #include "vdt/vdtMath.h" #include <iterator> PFMultiDepthClusterizer::PFMultiDepthClusterizer(const edm::ParameterSet& conf) : PFClusterBuilderBase(conf) { if (conf.exists("allCellsPositionCalc")) { const edm::ParameterSet& acConf = conf.getParameterSet("allCellsPositionCalc"); const std::string& algoac = acConf.getParameter<std::string>("algoName"); _allCellsPosCalc = PFCPositionCalculatorFactory::get()->create(algoac, acConf); } nSigmaEta_ = pow(conf.getParameter<double>("nSigmaEta"), 2); nSigmaPhi_ = pow(conf.getParameter<double>("nSigmaPhi"), 2); } void PFMultiDepthClusterizer::buildClusters(const reco::PFClusterCollection& input, const std::vector<bool>& seedable, reco::PFClusterCollection& output) { std::vector<double> etaRMS2(input.size(), 0.0); std::vector<double> phiRMS2(input.size(), 0.0); //We need to sort the clusters for smaller to larger depth // for (unsigned int i=0;i<input.size();++i) // printf(" cluster%f %f \n",input[i].depth(),input[i].energy()); //calculate cluster shapes calculateShowerShapes(input, etaRMS2, phiRMS2); //link auto&& links = link(input, etaRMS2, phiRMS2); // for (const auto& link: links) // printf("link %d %d %f %f\n",link.from(),link.to(),link.dR(),link.dZ()); std::vector<bool> mask(input.size(), false); std::vector<bool> linked(input.size(), false); //prune auto&& prunedLinks = prune(links, linked); //printf("Pruned links\n") // for (const auto& link: prunedLinks) // printf("link %d %d %f %f\n",link.from(),link.to(),link.dR(),link.dZ()); //now we need to build clusters for (unsigned int i = 0; i < input.size(); ++i) { //if not masked if (mask[i]) continue; //if not linked just spit it out if (!linked[i]) { output.push_back(input[i]); // printf("Added single cluster with energy =%f \n",input[i].energy()); mask[i] = true; continue; } //now business: if linked and not masked gather clusters reco::PFCluster cluster = input[i]; mask[i] = true; expandCluster(cluster, i, mask, input, prunedLinks); _allCellsPosCalc->calculateAndSetPosition(cluster); output.push_back(cluster); // printf("Added linked cluster with energy =%f\n",cluster.energy()); } } void PFMultiDepthClusterizer::calculateShowerShapes(const reco::PFClusterCollection& clusters, std::vector<double>& etaRMS2, std::vector<double>& phiRMS2) { //shower shapes. here do not use the fractions for (unsigned int i = 0; i < clusters.size(); ++i) { const reco::PFCluster& cluster = clusters[i]; double etaSum = 0.0; double phiSum = 0.0; auto const& crep = cluster.positionREP(); for (const auto& frac : cluster.recHitFractions()) { auto const& h = *frac.recHitRef(); auto const& rep = h.positionREP(); etaSum += (frac.fraction() * h.energy()) * std::abs(rep.eta() - crep.eta()); phiSum += (frac.fraction() * h.energy()) * std::abs(deltaPhi(rep.phi(), crep.phi())); } //protection for single line : assign ~ tower etaRMS2[i] = std::max(etaSum / cluster.energy(), 0.1); etaRMS2[i] *= etaRMS2[i]; phiRMS2[i] = std::max(phiSum / cluster.energy(), 0.1); phiRMS2[i] *= phiRMS2[i]; } } std::vector<PFMultiDepthClusterizer::ClusterLink> PFMultiDepthClusterizer::link( const reco::PFClusterCollection& clusters, const std::vector<double>& etaRMS2, const std::vector<double>& phiRMS2) { std::vector<ClusterLink> links; //loop on all pairs for (unsigned int i = 0; i < clusters.size(); ++i) for (unsigned int j = 0; j < clusters.size(); ++j) { if (i == j) continue; const reco::PFCluster& cluster1 = clusters[i]; const reco::PFCluster& cluster2 = clusters[j]; auto dz = (cluster2.depth() - cluster1.depth()); //Do not link at the same layer and only link inside out! if (dz < 0.0f || std::abs(dz) < 0.2f) continue; auto const& crep1 = cluster1.positionREP(); auto const& crep2 = cluster2.positionREP(); auto deta = crep1.eta() - crep2.eta(); deta = deta * deta / (etaRMS2[i] + etaRMS2[j]); auto dphi = deltaPhi(crep1.phi(), crep2.phi()); dphi = dphi * dphi / (phiRMS2[i] + phiRMS2[j]); // printf("Testing Link %d -> %d (%f %f %f %f ) \n",i,j,deta,dphi,cluster1.position().Eta()-cluster2.position().Eta(),deltaPhi(cluster1.position().Phi(),cluster2.position().Phi())); if ((deta < nSigmaEta_) & (dphi < nSigmaPhi_)) links.push_back(ClusterLink(i, j, deta + dphi, std::abs(dz), cluster1.energy() + cluster2.energy())); } return links; } std::vector<PFMultiDepthClusterizer::ClusterLink> PFMultiDepthClusterizer::prune(std::vector<ClusterLink>& links, std::vector<bool>& linkedClusters) { std::vector<ClusterLink> goodLinks; std::vector<bool> mask(links.size(), false); if (links.empty()) return goodLinks; for (unsigned int i = 0; i < links.size() - 1; ++i) { if (mask[i]) continue; for (unsigned int j = i + 1; j < links.size(); ++j) { if (mask[j]) continue; const ClusterLink& link1 = links[i]; const ClusterLink& link2 = links[j]; if (link1.to() == link2.to()) { //found two links going to the same spot,kill one //first prefer nearby layers if (link1.dZ() < link2.dZ()) { mask[j] = true; } else if (link1.dZ() > link2.dZ()) { mask[i] = true; } else if (fabs(link1.dZ() - link2.dZ()) < 0.2) { //if same layer-pick based on transverse compatibility if (link1.dR() < link2.dR()) { mask[j] = true; } else if (link1.dR() > link2.dR()) { mask[i] = true; } else { //same distance as well -> can happen !!!!! Pick the highest SUME if (link1.energy() < link2.energy()) mask[i] = true; else mask[j] = true; } } } } } for (unsigned int i = 0; i < links.size(); ++i) { if (mask[i]) continue; goodLinks.push_back(links[i]); linkedClusters[links[i].from()] = true; linkedClusters[links[i].to()] = true; } return goodLinks; } void PFMultiDepthClusterizer::absorbCluster(reco::PFCluster& main, const reco::PFCluster& added) { double e1 = 0.0; double e2 = 0.0; //find seeds for (const auto& fraction : main.recHitFractions()) if (fraction.recHitRef()->detId() == main.seed()) { e1 = fraction.recHitRef()->energy(); } for (const auto& fraction : added.recHitFractions()) { main.addRecHitFraction(fraction); if (fraction.recHitRef()->detId() == added.seed()) { e2 = fraction.recHitRef()->energy(); } } if (e2 > e1) main.setSeed(added.seed()); } void PFMultiDepthClusterizer::expandCluster(reco::PFCluster& cluster, unsigned int point, std::vector<bool>& mask, const reco::PFClusterCollection& clusters, const std::vector<ClusterLink>& links) { for (const auto& link : links) { if (link.from() == point) { //found link that starts from this guy if not masked absorb if (!mask[link.from()]) { absorbCluster(cluster, clusters[link.from()]); mask[link.from()] = true; } if (!mask[link.to()]) { absorbCluster(cluster, clusters[link.to()]); mask[link.to()] = true; expandCluster(cluster, link.to(), mask, clusters, links); } } if (link.to() == point) { //found link that starts from this guy if not masked absorb if (!mask[link.to()]) { absorbCluster(cluster, clusters[link.to()]); mask[link.to()] = true; } if (!mask[link.from()]) { absorbCluster(cluster, clusters[link.from()]); mask[link.from()] = true; expandCluster(cluster, link.from(), mask, clusters, links); } } } }
renzenicolai/micropython-with-badge-graphics
ports/unix/display/fonts/font_Exo2-ExtraLight_13pt7b.c
<filename>ports/unix/display/fonts/font_Exo2-ExtraLight_13pt7b.c #include "../include/driver_framebuffer.h" const uint8_t Exo2_ExtraLight_13pt7bBitmaps[] = { 0x00, 0xFE, 0x40, 0xB6, 0x80, 0x22, 0x22, 0x24, 0xFF, 0x24, 0x44, 0xFE, 0x44, 0x48, 0x48, 0x10, 0x47, 0xE4, 0x92, 0x45, 0x0A, 0x24, 0x92, 0x7E, 0x20, 0xF0, 0x92, 0x22, 0x48, 0x49, 0x09, 0x5C, 0xD4, 0x42, 0x88, 0x91, 0x22, 0x24, 0x38, 0x7C, 0x40, 0x20, 0x90, 0x47, 0xFC, 0x12, 0x09, 0x04, 0x82, 0x3E, 0xC0, 0xE0, 0x2A, 0x49, 0x24, 0x92, 0x22, 0x88, 0x92, 0x49, 0x24, 0xA8, 0x2B, 0x65, 0x20, 0x8F, 0xC8, 0x20, 0xE0, 0xF0, 0x80, 0x06, 0x08, 0x20, 0x41, 0x02, 0x08, 0x10, 0x41, 0x80, 0x7A, 0x18, 0x61, 0x86, 0x18, 0x61, 0x85, 0xE0, 0x79, 0x11, 0x11, 0x11, 0x11, 0xF8, 0x10, 0x42, 0x08, 0x42, 0x10, 0x43, 0xF0, 0xF8, 0x10, 0x42, 0x78, 0x10, 0x41, 0x07, 0xE0, 0x20, 0x41, 0x12, 0x28, 0x50, 0xA1, 0x7F, 0x04, 0x08, 0xFA, 0x08, 0x20, 0xF0, 0x20, 0x41, 0x0B, 0xE0, 0x7A, 0x08, 0x2E, 0xC6, 0x18, 0x61, 0x85, 0xE0, 0xFC, 0x20, 0x82, 0x10, 0x41, 0x08, 0x20, 0x80, 0x7E, 0x18, 0x61, 0x7A, 0x18, 0x61, 0x85, 0xF0, 0x7A, 0x18, 0x61, 0x86, 0x37, 0x41, 0x07, 0xE0, 0x84, 0x87, 0x09, 0xB0, 0x83, 0x04, 0xFC, 0x00, 0x3F, 0xC0, 0xC0, 0xC6, 0x62, 0x00, 0xF8, 0x42, 0x11, 0x10, 0x80, 0x01, 0x00, 0x7E, 0x81, 0x9F, 0xA1, 0xA1, 0xA3, 0x9D, 0x80, 0x7F, 0x08, 0x14, 0x14, 0x24, 0x22, 0x22, 0x7E, 0x41, 0x41, 0x81, 0xFD, 0x0A, 0x0C, 0x2F, 0x90, 0xA0, 0xC1, 0x83, 0xF8, 0x7E, 0x08, 0x20, 0x82, 0x08, 0x20, 0x81, 0xF0, 0xFD, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC1, 0x83, 0xF8, 0x7E, 0x08, 0x20, 0xFA, 0x08, 0x20, 0x81, 0xF0, 0x7E, 0x08, 0x20, 0xFA, 0x08, 0x20, 0x82, 0x00, 0x7D, 0x02, 0x04, 0x08, 0x30, 0x60, 0xC1, 0x86, 0xF4, 0x83, 0x06, 0x0C, 0x1F, 0xF0, 0x60, 0xC1, 0x83, 0x04, 0xFF, 0xC0, 0x24, 0x92, 0x49, 0x3C, 0x85, 0x12, 0x24, 0x8E, 0x12, 0x24, 0x44, 0x85, 0x0C, 0x82, 0x08, 0x20, 0x82, 0x08, 0x20, 0x81, 0xF0, 0x40, 0xA8, 0x5A, 0x16, 0x85, 0x92, 0x64, 0x99, 0x26, 0x31, 0x8C, 0x60, 0x10, 0xC3, 0x46, 0x8C, 0x99, 0x31, 0x62, 0xC3, 0x87, 0x04, 0x7D, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC1, 0x82, 0xF8, 0xFE, 0x18, 0x61, 0x87, 0xE8, 0x20, 0x82, 0x00, 0x7D, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC1, 0x82, 0xF8, 0x40, 0x60, 0xFD, 0x0A, 0x0C, 0x18, 0x5F, 0x21, 0x42, 0x85, 0x04, 0xFE, 0x08, 0x20, 0x60, 0x60, 0x41, 0x07, 0xE0, 0xFF, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x83, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC1, 0x42, 0x78, 0x81, 0x41, 0x42, 0x42, 0x22, 0x24, 0x24, 0x14, 0x18, 0x18, 0x82, 0x0A, 0x28, 0x91, 0x44, 0x8A, 0x24, 0x51, 0x14, 0x50, 0xA2, 0x85, 0x14, 0x28, 0xA0, 0x82, 0x00, 0x41, 0x42, 0x24, 0x14, 0x18, 0x14, 0x24, 0x22, 0x42, 0xC1, 0x82, 0x85, 0x11, 0x22, 0x83, 0x04, 0x08, 0x10, 0x20, 0xFC, 0x10, 0x84, 0x10, 0x84, 0x10, 0x83, 0xF0, 0x72, 0x49, 0x24, 0x92, 0x48, 0xC0, 0xC0, 0x80, 0x81, 0x01, 0x02, 0x02, 0x04, 0x04, 0x0C, 0xD5, 0x55, 0x55, 0x70, 0x22, 0xA2, 0xFC, 0x90, 0xF8, 0x43, 0xF8, 0xC7, 0xE0, 0x82, 0x08, 0x2E, 0xC6, 0x18, 0x61, 0x87, 0xE0, 0x7C, 0x21, 0x08, 0x41, 0xE0, 0x04, 0x10, 0x5F, 0x86, 0x18, 0x61, 0x8D, 0xD0, 0x7A, 0x18, 0x7E, 0x82, 0x07, 0x80, 0x3A, 0x11, 0xF4, 0x21, 0x08, 0x42, 0x00, 0x7E, 0x18, 0x62, 0x72, 0x07, 0xA1, 0x87, 0xE0, 0x82, 0x08, 0x2E, 0xC6, 0x18, 0x61, 0x86, 0x10, 0x9F, 0xC0, 0x9F, 0xF8, 0x84, 0x21, 0x19, 0x53, 0x14, 0x94, 0x40, 0x92, 0x49, 0x24, 0x8C, 0xBB, 0xF1, 0x18, 0x46, 0x11, 0x84, 0x61, 0x18, 0x44, 0xBB, 0x18, 0x61, 0x86, 0x18, 0x40, 0x7A, 0x18, 0x61, 0x86, 0x17, 0x80, 0xBB, 0x18, 0x61, 0x86, 0x1F, 0xA0, 0x82, 0x00, 0x7E, 0x18, 0x61, 0x86, 0x37, 0x41, 0x04, 0x10, 0xBC, 0x88, 0x88, 0x80, 0xFC, 0x20, 0xE0, 0x87, 0xE0, 0x42, 0x3E, 0x84, 0x21, 0x08, 0x38, 0x86, 0x18, 0x61, 0x86, 0x37, 0x40, 0x82, 0x89, 0x11, 0x22, 0x85, 0x04, 0x00, 0x84, 0x28, 0xC5, 0x29, 0x25, 0x22, 0x94, 0x63, 0x04, 0x20, 0x46, 0x88, 0xA0, 0x82, 0x88, 0xB0, 0x80, 0x82, 0x89, 0x11, 0x22, 0x85, 0x04, 0x08, 0x10, 0xC0, 0xF8, 0x44, 0x44, 0x43, 0xE0, 0x72, 0x49, 0x24, 0x92, 0x44, 0x40, 0xFF, 0xFC, 0x89, 0x24, 0x8A, 0x49, 0x25, 0x00, 0x6C, 0xC0 }; const GFXglyph Exo2_ExtraLight_13pt7bGlyphs[] = { { 0, 1, 1, 3, 0, 0 }, // 0x20 ' ' { 1, 1, 10, 4, 1, -9 }, // 0x21 '!' { 3, 3, 3, 5, 1, -9 }, // 0x22 '"' { 5, 8, 10, 9, 1, -9 }, // 0x23 '#' { 15, 6, 13, 8, 1, -11 }, // 0x24 '$' { 25, 11, 10, 12, 1, -9 }, // 0x25 '%' { 39, 9, 10, 11, 1, -9 }, // 0x26 '&' { 51, 1, 3, 3, 1, -9 }, // 0x27 ''' { 52, 3, 13, 5, 1, -10 }, // 0x28 '(' { 57, 3, 13, 5, 1, -10 }, // 0x29 ')' { 62, 4, 4, 6, 1, -9 }, // 0x2A '*' { 64, 6, 5, 8, 1, -6 }, // 0x2B '+' { 68, 1, 3, 3, 1, 0 }, // 0x2C ',' { 69, 4, 1, 7, 1, -3 }, // 0x2D '-' { 70, 1, 1, 3, 1, 0 }, // 0x2E '.' { 71, 7, 10, 7, 0, -9 }, // 0x2F '/' { 80, 6, 10, 8, 1, -9 }, // 0x30 '0' { 88, 4, 10, 5, 0, -9 }, // 0x31 '1' { 93, 6, 10, 8, 1, -9 }, // 0x32 '2' { 101, 6, 10, 8, 1, -9 }, // 0x33 '3' { 109, 7, 10, 8, 1, -9 }, // 0x34 '4' { 118, 6, 10, 7, 1, -9 }, // 0x35 '5' { 126, 6, 10, 8, 1, -9 }, // 0x36 '6' { 134, 6, 10, 7, 1, -9 }, // 0x37 '7' { 142, 6, 10, 9, 1, -9 }, // 0x38 '8' { 150, 6, 10, 8, 1, -9 }, // 0x39 '9' { 158, 1, 6, 3, 1, -5 }, // 0x3A ':' { 159, 1, 8, 3, 1, -5 }, // 0x3B ';' { 160, 5, 6, 8, 1, -6 }, // 0x3C '<' { 164, 6, 4, 8, 1, -5 }, // 0x3D '=' { 167, 6, 6, 8, 1, -6 }, // 0x3E '>' { 172, 5, 10, 7, 1, -9 }, // 0x3F '?' { 179, 8, 9, 10, 1, -7 }, // 0x40 '@' { 188, 8, 10, 9, 0, -9 }, // 0x41 'A' { 198, 7, 10, 9, 1, -9 }, // 0x42 'B' { 207, 6, 10, 8, 1, -9 }, // 0x43 'C' { 215, 7, 10, 9, 1, -9 }, // 0x44 'D' { 224, 6, 10, 8, 1, -9 }, // 0x45 'E' { 232, 6, 10, 7, 1, -9 }, // 0x46 'F' { 240, 7, 10, 9, 1, -9 }, // 0x47 'G' { 249, 7, 10, 9, 1, -9 }, // 0x48 'H' { 258, 1, 10, 3, 1, -9 }, // 0x49 'I' { 260, 3, 10, 5, 0, -9 }, // 0x4A 'J' { 264, 7, 10, 8, 1, -9 }, // 0x4B 'K' { 273, 6, 10, 7, 1, -9 }, // 0x4C 'L' { 281, 10, 10, 12, 1, -9 }, // 0x4D 'M' { 294, 7, 10, 10, 1, -9 }, // 0x4E 'N' { 303, 7, 10, 9, 1, -9 }, // 0x4F 'O' { 312, 6, 10, 8, 1, -9 }, // 0x50 'P' { 320, 7, 12, 9, 1, -9 }, // 0x51 'Q' { 331, 7, 10, 9, 1, -9 }, // 0x52 'R' { 340, 6, 10, 8, 1, -9 }, // 0x53 'S' { 348, 8, 10, 8, 0, -9 }, // 0x54 'T' { 358, 7, 10, 9, 1, -9 }, // 0x55 'U' { 367, 8, 10, 8, 0, -9 }, // 0x56 'V' { 377, 13, 10, 13, 0, -9 }, // 0x57 'W' { 394, 8, 10, 8, 0, -9 }, // 0x58 'X' { 404, 7, 10, 8, 0, -9 }, // 0x59 'Y' { 413, 6, 10, 8, 1, -9 }, // 0x5A 'Z' { 421, 3, 14, 4, 1, -10 }, // 0x5B '[' { 427, 7, 10, 7, 0, -9 }, // 0x5C '\' { 436, 2, 14, 4, 1, -10 }, // 0x5D ']' { 440, 5, 3, 6, 0, -7 }, // 0x5E '^' { 442, 6, 1, 6, 0, 1 }, // 0x5F '_' { 443, 2, 2, 4, 1, -9 }, // 0x60 '`' { 444, 5, 7, 8, 1, -6 }, // 0x61 'a' { 449, 6, 10, 8, 1, -9 }, // 0x62 'b' { 457, 5, 7, 7, 1, -6 }, // 0x63 'c' { 462, 6, 10, 8, 1, -9 }, // 0x64 'd' { 470, 6, 7, 7, 1, -6 }, // 0x65 'e' { 476, 5, 10, 5, 0, -9 }, // 0x66 'f' { 483, 6, 10, 8, 1, -6 }, // 0x67 'g' { 491, 6, 10, 8, 1, -9 }, // 0x68 'h' { 499, 1, 10, 3, 1, -9 }, // 0x69 'i' { 501, 1, 13, 3, 1, -9 }, // 0x6A 'j' { 503, 5, 10, 7, 1, -9 }, // 0x6B 'k' { 510, 3, 10, 4, 1, -9 }, // 0x6C 'l' { 514, 10, 7, 12, 1, -6 }, // 0x6D 'm' { 523, 6, 7, 8, 1, -6 }, // 0x6E 'n' { 529, 6, 7, 8, 1, -6 }, // 0x6F 'o' { 535, 6, 10, 8, 1, -6 }, // 0x70 'p' { 543, 6, 10, 8, 1, -6 }, // 0x71 'q' { 551, 4, 7, 5, 1, -6 }, // 0x72 'r' { 555, 5, 7, 7, 1, -6 }, // 0x73 's' { 560, 5, 9, 5, 0, -8 }, // 0x74 't' { 566, 6, 7, 8, 1, -6 }, // 0x75 'u' { 572, 7, 7, 7, 0, -6 }, // 0x76 'v' { 579, 11, 7, 11, 0, -6 }, // 0x77 'w' { 589, 7, 7, 7, 0, -6 }, // 0x78 'x' { 596, 7, 10, 7, 0, -6 }, // 0x79 'y' { 605, 5, 7, 7, 1, -6 }, // 0x7A 'z' { 610, 3, 14, 4, 1, -10 }, // 0x7B '{' { 616, 1, 14, 3, 1, -11 }, // 0x7C '|' { 618, 3, 14, 4, 1, -10 }, // 0x7D '}' { 624, 5, 2, 7, 1, -4 } }; // 0x7E '~' const GFXfont Exo2_ExtraLight_13pt7b = { (uint8_t *)Exo2_ExtraLight_13pt7bBitmaps, (GFXglyph *)Exo2_ExtraLight_13pt7bGlyphs, 0x20, 0x7E, 13 };//B // Approx. 1298 bytes
arnaud-morvan/geoportailv3
geoportal/geoportailv3_geoportal/static-ngeo/js/index.js
/* eslint-disable */ goog.require('app.query.casiporeportDirective'); goog.require('app.draw.FeatureHash'); goog.require('app.layerinfo.layerinfoDirective'); /** * @typedef {{themes: Array.<Object>, background_layers: Array.<Object>}} */ app.ThemesResponse; /** * @typedef {function(ol.Coordinate, string, string, boolean, boolean):string} */ app.CoordinateString; /** * @typedef {{point: Array.<ol.style.Style>, default: Array.<ol.style.Style>}} */ app.query.QueryStyles; /** * @typedef {function(string, app.NotifyNotificationType)} */ app.Notify; /** * @typedef {Array.<Object>} */ app.MapsResponse; /** * @typedef {{className: (string|undefined), * label: (string|undefined), * tipLabel: (string|undefined), * target: (Element|undefined), * drawLineInteraction: app.interaction.DrawRoute * }} */ app.draw.RouteControlOptions; /** * @typedef {ol.Collection<ol.Feature>} */ app.draw.SelectedFeatures; /** * @typedef {function(Object):ol.layer.Layer} */ app.GetLayerForCatalogNode; /** * @typedef {function(ol.Coordinate):!angular.$q.Promise} */ app.GetElevation; /** * @typedef {function( * (ol.geom.MultiLineString|ol.geom.LineString), * string=):!angular.$q.Promise * } */ app.GetProfile; /** * @typedef {function(ol.Coordinate=):!angular.$q.Promise} */ app.GetShorturl; /** * @typedef {function(string, string, boolean):ol.layer.Tile} */ app.GetWmtsLayer; /** * @typedef {function(ol.layer.Layer)} */ app.layerinfo.ShowLayerinfo; /** * @typedef {function(string, string, string, string=):ol.layer.Image} */ app.GetWmsLayer; /** * @typedef {{className: (string|undefined), * label: (string|undefined), * tipLabel: (string|undefined), * target: (Element|undefined), * featureOverlayMgr: ngeo.map.FeatureOverlayMgr, * notify: app.Notify, * gettextCatalog: angularGettext.Catalog, * scope: angular.Scope, * window: angular.$window * }} */ app.LocationControlOptions;
Berstanio/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/authenticationservices/ASAuthorizationSingleSignOnCredential.java
package apple.authenticationservices; import apple.NSObject; import apple.authenticationservices.protocol.ASAuthorizationCredential; import apple.foundation.NSArray; import apple.foundation.NSCoder; import apple.foundation.NSData; import apple.foundation.NSHTTPURLResponse; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.ProtocolClassMethod; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; @Generated @Library("AuthenticationServices") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class ASAuthorizationSingleSignOnCredential extends NSObject implements ASAuthorizationCredential { static { NatJ.register(); } @Generated protected ASAuthorizationSingleSignOnCredential(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); /** * An access token used to access other systems with the authorized scopes. */ @Generated @Selector("accessToken") public native NSData accessToken(); @Generated @Owned @Selector("alloc") public static native ASAuthorizationSingleSignOnCredential alloc(); @Generated @Selector("allocWithZone:") @MappedReturn(ObjCObjectMapper.class) public static native Object allocWithZone(VoidPtr zone); /** * The complete AuthenticationServices extension response with the additional outputs used by the specific technology used by the Authorization Server instance and AuthenticationServices Extension. * [@note] for some operations all properties can be null and the response will indicate just successful result of the operation. */ @Generated @Selector("authenticatedResponse") public native NSHTTPURLResponse authenticatedResponse(); /** * This value will contain a list of scopes for which the user provided authorization. These may contain a subset of the requested scopes on @see ASAuthorizationOpenIDRequest. The application should query this value to identify which scopes were returned as it maybe different from ones requested. */ @Generated @Selector("authorizedScopes") public native NSArray<String> authorizedScopes(); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Owned @Selector("copyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object copyWithZone(VoidPtr zone); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("encodeWithCoder:") public native void encodeWithCoder(NSCoder coder); @Generated @Selector("hash") @NUInt public static native long hash_static(); /** * A JSON Web Token (JWT) used to communicate information about the identity of the user in a secure way to the app. */ @Generated @Selector("identityToken") public native NSData identityToken(); @Generated @Selector("init") public native ASAuthorizationSingleSignOnCredential init(); @Generated @Selector("initWithCoder:") public native ASAuthorizationSingleSignOnCredential initWithCoder(NSCoder coder); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") @MappedReturn(ObjCObjectMapper.class) public static native Object new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); /** * A state returned from the AuthenticationServices extension. */ @Generated @Selector("state") public native String state(); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("supportsSecureCoding") public static native boolean supportsSecureCoding(); @Generated @ProtocolClassMethod("supportsSecureCoding") public boolean _supportsSecureCoding() { return supportsSecureCoding(); } @Generated @Selector("version") @NInt public static native long version_static(); }
dimitardanailov/ddanailov
website/pages-nextjs/About/Components/Testimonials/Ashton/Letter.js
function AshtonLetter() { return ( <p> "Even though my time with Dimitar was limited, I found him consistently pleasant, professional, and tackled all programming assignments with dedication and a view of total success. Besides being a joy to work with, Dimitar is a take - charge person who is able to present creative ideas and communicate the benefits. I highly recommend Dimitar for employment. He is a team player and would make a great asset of any organization." </p> ) } export default AshtonLetter
plenarius/iota.lib.py
iota/commands/core/find_transactions.py
# coding=utf-8 from __future__ import absolute_import, division, print_function, \ unicode_literals import filters as f from six import iteritems from iota import Address, Tag, TransactionHash from iota.commands import FilterCommand, RequestFilter, ResponseFilter from iota.filters import Trytes __all__ = [ 'FindTransactionsCommand', ] class FindTransactionsCommand(FilterCommand): """ Executes `findTransactions` command. See :py:meth:`iota.api.StrictIota.find_transactions`. """ command = 'findTransactions' def get_request_filter(self): return FindTransactionsRequestFilter() def get_response_filter(self): return FindTransactionsResponseFilter() class FindTransactionsRequestFilter(RequestFilter): CODE_NO_SEARCH_VALUES = 'no_search_values' templates = { CODE_NO_SEARCH_VALUES: 'No search values specified.', } def __init__(self): super(FindTransactionsRequestFilter, self).__init__( { 'addresses': ( f.Array | f.FilterRepeater( f.Required | Trytes(result_type=Address) | f.Unicode(encoding='ascii', normalize=False) ) ), 'approvees': ( f.Array | f.FilterRepeater( f.Required | Trytes(result_type=TransactionHash) | f.Unicode(encoding='ascii', normalize=False) ) ), 'bundles': ( f.Array | f.FilterRepeater( f.Required | Trytes(result_type=TransactionHash) | f.Unicode(encoding='ascii', normalize=False) ) ), 'tags': ( f.Array | f.FilterRepeater( f.Required | Trytes(result_type=Tag) | f.Unicode(encoding='ascii', normalize=False) ) ), }, # Technically, all of the parameters for this command are # optional, so long as at least one of them is present and not # empty. allow_missing_keys = True, ) def _apply(self, value): value = super(FindTransactionsRequestFilter, self)._apply(value) # type: dict if self._has_errors: return value # Remove null search terms. # Note: We will assume that empty lists are intentional. # https://github.com/iotaledger/iota.lib.py/issues/96 search_terms = { term: query for term, query in iteritems(value) if query is not None } # At least one search term is required. if not search_terms: # Include unfiltered ``value`` in filter error context. return self._invalid_value(value, self.CODE_NO_SEARCH_VALUES) return search_terms class FindTransactionsResponseFilter(ResponseFilter): def __init__(self): super(FindTransactionsResponseFilter, self).__init__({ 'hashes': f.FilterRepeater( f.ByteString(encoding='ascii') | Trytes(result_type=TransactionHash) ) | f.Optional(default=[]), })
phatblat/macOSPrivateFrameworks
PrivateFrameworks/AVConference/VCMoments.h
<reponame>phatblat/macOSPrivateFrameworks // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" #import "VCMomentsMessenger.h" @class NSMutableSet, NSObject<OS_dispatch_queue>, NSString, VCMomentsHistory, VideoAttributes; __attribute__((visibility("hidden"))) @interface VCMoments : NSObject <VCMomentsMessenger> { id _delegate; id _transportDelegate; unsigned int _streamToken; VCMomentsHistory *_momentsHistory; unsigned int _capabilities; unsigned char _mode; NSObject<OS_dispatch_queue> *delegateNotificationQueue; int _currentActiveRequestsCount; BOOL _isActive; BOOL _isClientRegistered; VideoAttributes *_remoteScreenAttributes; NSMutableSet *_requests; BOOL _lastRequest; } + (unsigned long long)countForRequestType:(int)arg1; + (int)typeForRequest:(id)arg1; + (unsigned long long)deviceFreeDiskSpace; + (BOOL)deviceHasSufficientFreeSpace; + (unsigned long long)fileSize:(id)arg1; @property(retain, nonatomic) VideoAttributes *remoteScreenAttributes; // @synthesize remoteScreenAttributes=_remoteScreenAttributes; @property(readonly, nonatomic) BOOL isActive; // @synthesize isActive=_isActive; @property(nonatomic) unsigned int capabilities; // @synthesize capabilities=_capabilities; - (void)handleInsufficientFreeSpaceWithRequest:(id)arg1 delegate:(id)arg2; - (unsigned long long)directorySize:(id)arg1; - (BOOL)isHistorySupported; - (BOOL)validateNumberOfRequestsWithError:(id *)arg1; - (void)updateVCMomentsMode; - (void)notifyLocalFinishWithRequest:(id)arg1 didSucceed:(BOOL)arg2; - (void)notifyRemoteFinishWithRequest:(id)arg1 didSucceed:(BOOL)arg2 fileSize:(long long)arg3; - (void)notifyFinishWithRequest:(id)arg1 didSucceed:(BOOL)arg2 fileSize:(long long)arg3; - (void)processRemotePhotoRequest:(id)arg1; - (void)processRemoteLivePhotoRequest:(id)arg1; - (void)processRemoteRequest:(id)arg1 withMediaType:(unsigned char)arg2; - (void)_generateRequest:(unsigned char)arg1 requestState:(unsigned char)arg2 transactionID:(id)arg3 timestamp:(unsigned int)arg4; - (void)updateActiveStatus; - (void)deregisterClient; - (void)registerClient; - (void)cleanupActiveRequests; - (BOOL)processClientRequest:(id)arg1 error:(id *)arg2; - (void)setMomentsDelegate:(id)arg1; - (id)momentsDelegate; - (void)setTransportDelegate:(id)arg1; - (id)transportDelegate; - (void)setFrameRate:(float)arg1; - (void)processRequest:(id)arg1; - (BOOL)validateIncomingRequest:(id)arg1; - (void)updateRemoteScreenAttributes:(id)arg1; - (void)getInitialRemoteScreenAttributes:(id)arg1; - (void)addLocalVideoSampleBuffer:(struct opaqueCMSampleBuffer *)arg1 cameraStatusBits:(unsigned char)arg2 timestamp:(unsigned int)arg3; - (void)addRemoteAudioSample:(struct opaqueVCAudioBufferList *)arg1 timestamp:(unsigned int)arg2; - (void)addLocalAudioSample:(struct opaqueVCAudioBufferList *)arg1 timestamp:(unsigned int)arg2; @property(nonatomic) int imageType; @property(nonatomic) int videoCodec; - (void)dealloc; - (id)initWithStreamToken:(unsigned int)arg1 delegate:(id)arg2; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
yurili8/apexcharts-flow
src/main/java/com/github/appreciated/apexcharts/config/builder/StrokeBuilder.java
package com.github.appreciated.apexcharts.config.builder; import com.github.appreciated.apexcharts.config.Stroke; import com.github.appreciated.apexcharts.config.stroke.Curve; import com.github.appreciated.apexcharts.config.stroke.LineCap; import java.util.Arrays; import java.util.List; public class StrokeBuilder { private Boolean show; private Curve curve; private LineCap lineCap; private List<String> colors; private Double width; private List<Double> dashArray; private StrokeBuilder() { } public static StrokeBuilder get() { return new StrokeBuilder(); } public StrokeBuilder withShow(Boolean show) { this.show = show; return this; } public StrokeBuilder withCurve(Curve curve) { this.curve = curve; return this; } public StrokeBuilder withLineCap(LineCap lineCap) { this.lineCap = lineCap; return this; } public StrokeBuilder withColors(String... colors) { this.colors = Arrays.asList(colors); return this; } public StrokeBuilder withWidth(Double width) { this.width = width; return this; } public StrokeBuilder withDashArray(List<Double> dashArray) { this.dashArray = dashArray; return this; } public Stroke build() { Stroke stroke = new Stroke(); stroke.setShow(show); stroke.setCurve(curve); stroke.setLineCap(lineCap); stroke.setColors(colors); stroke.setWidth(width); stroke.setDashArray(dashArray); return stroke; } }
Nexuscompute/aws-sdk-cpp
aws-cpp-sdk-workspaces/include/aws/workspaces/model/IosImportClientBrandingAttributes.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/workspaces/WorkSpaces_EXPORTS.h> #include <aws/core/utils/Array.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace WorkSpaces { namespace Model { /** * <p>The client branding attributes to import for iOS device types. These * attributes are displayed on the iOS client login screen.</p> * <p>Client branding attributes are public facing. Ensure you do not include * sensitive information.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/IosImportClientBrandingAttributes">AWS * API Reference</a></p> */ class AWS_WORKSPACES_API IosImportClientBrandingAttributes { public: IosImportClientBrandingAttributes(); IosImportClientBrandingAttributes(Aws::Utils::Json::JsonView jsonValue); IosImportClientBrandingAttributes& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline const Aws::Utils::ByteBuffer& GetLogo() const{ return m_logo; } /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline bool LogoHasBeenSet() const { return m_logoHasBeenSet; } /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline void SetLogo(const Aws::Utils::ByteBuffer& value) { m_logoHasBeenSet = true; m_logo = value; } /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline void SetLogo(Aws::Utils::ByteBuffer&& value) { m_logoHasBeenSet = true; m_logo = std::move(value); } /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline IosImportClientBrandingAttributes& WithLogo(const Aws::Utils::ByteBuffer& value) { SetLogo(value); return *this;} /** * <p>The logo. This is the link where users can download the logo image. This is * the standard-resolution display that has a 1:1 pixel density (or @1x), where one * pixel is equal to one point.</p> */ inline IosImportClientBrandingAttributes& WithLogo(Aws::Utils::ByteBuffer&& value) { SetLogo(std::move(value)); return *this;} /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline const Aws::Utils::ByteBuffer& GetLogo2x() const{ return m_logo2x; } /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline bool Logo2xHasBeenSet() const { return m_logo2xHasBeenSet; } /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline void SetLogo2x(const Aws::Utils::ByteBuffer& value) { m_logo2xHasBeenSet = true; m_logo2x = value; } /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline void SetLogo2x(Aws::Utils::ByteBuffer&& value) { m_logo2xHasBeenSet = true; m_logo2x = std::move(value); } /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline IosImportClientBrandingAttributes& WithLogo2x(const Aws::Utils::ByteBuffer& value) { SetLogo2x(value); return *this;} /** * <p>The @2x version of the logo. This is the higher resolution display that * offers a scale factor of 2.0 (or @2x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline IosImportClientBrandingAttributes& WithLogo2x(Aws::Utils::ByteBuffer&& value) { SetLogo2x(std::move(value)); return *this;} /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline const Aws::Utils::ByteBuffer& GetLogo3x() const{ return m_logo3x; } /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline bool Logo3xHasBeenSet() const { return m_logo3xHasBeenSet; } /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline void SetLogo3x(const Aws::Utils::ByteBuffer& value) { m_logo3xHasBeenSet = true; m_logo3x = value; } /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline void SetLogo3x(Aws::Utils::ByteBuffer&& value) { m_logo3xHasBeenSet = true; m_logo3x = std::move(value); } /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline IosImportClientBrandingAttributes& WithLogo3x(const Aws::Utils::ByteBuffer& value) { SetLogo3x(value); return *this;} /** * <p>The @3x version of the logo. This is the higher resolution display that * offers a scale factor of 3.0 (or @3x).</p> <p> For more information about * iOS image size and resolution, see <a * href="https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/image-size-and-resolution/">Image * Size and Resolution </a> in the <i>Apple Human Interface Guidelines</i>.</p> * */ inline IosImportClientBrandingAttributes& WithLogo3x(Aws::Utils::ByteBuffer&& value) { SetLogo3x(std::move(value)); return *this;} /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline const Aws::String& GetSupportEmail() const{ return m_supportEmail; } /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline bool SupportEmailHasBeenSet() const { return m_supportEmailHasBeenSet; } /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportEmail(const Aws::String& value) { m_supportEmailHasBeenSet = true; m_supportEmail = value; } /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportEmail(Aws::String&& value) { m_supportEmailHasBeenSet = true; m_supportEmail = std::move(value); } /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportEmail(const char* value) { m_supportEmailHasBeenSet = true; m_supportEmail.assign(value); } /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportEmail(const Aws::String& value) { SetSupportEmail(value); return *this;} /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportEmail(Aws::String&& value) { SetSupportEmail(std::move(value)); return *this;} /** * <p>The support email. The company's customer support email address.</p> * <ul> <li> <p>In each platform type, the <code>SupportEmail</code> and * <code>SupportLink</code> parameters are mutually exclusive. You can specify one * parameter for each platform type, but not both.</p> </li> <li> <p>The default * email is <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportEmail(const char* value) { SetSupportEmail(value); return *this;} /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline const Aws::String& GetSupportLink() const{ return m_supportLink; } /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline bool SupportLinkHasBeenSet() const { return m_supportLinkHasBeenSet; } /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportLink(const Aws::String& value) { m_supportLinkHasBeenSet = true; m_supportLink = value; } /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportLink(Aws::String&& value) { m_supportLinkHasBeenSet = true; m_supportLink = std::move(value); } /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline void SetSupportLink(const char* value) { m_supportLinkHasBeenSet = true; m_supportLink.assign(value); } /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportLink(const Aws::String& value) { SetSupportLink(value); return *this;} /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportLink(Aws::String&& value) { SetSupportLink(std::move(value)); return *this;} /** * <p>The support link. The link for the company's customer support page for their * WorkSpace.</p> <ul> <li> <p>In each platform type, the * <code>SupportEmail</code> and <code>SupportLink</code> parameters are mutually * exclusive. You can specify one parameter for each platform type, but not * both.</p> </li> <li> <p>The default support link is * <code><EMAIL></code>.</p> </li> </ul> */ inline IosImportClientBrandingAttributes& WithSupportLink(const char* value) { SetSupportLink(value); return *this;} /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline const Aws::String& GetForgotPasswordLink() const{ return m_forgotPasswordLink; } /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline bool ForgotPasswordLinkHasBeenSet() const { return m_forgotPasswordLinkHasBeenSet; } /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline void SetForgotPasswordLink(const Aws::String& value) { m_forgotPasswordLinkHasBeenSet = true; m_forgotPasswordLink = value; } /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline void SetForgotPasswordLink(Aws::String&& value) { m_forgotPasswordLinkHasBeenSet = true; m_forgotPasswordLink = std::move(value); } /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline void SetForgotPasswordLink(const char* value) { m_forgotPasswordLinkHasBeenSet = true; m_forgotPasswordLink.assign(value); } /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline IosImportClientBrandingAttributes& WithForgotPasswordLink(const Aws::String& value) { SetForgotPasswordLink(value); return *this;} /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline IosImportClientBrandingAttributes& WithForgotPasswordLink(Aws::String&& value) { SetForgotPasswordLink(std::move(value)); return *this;} /** * <p>The forgotten password link. This is the web address that users can go to if * they forget the password for their WorkSpace.</p> */ inline IosImportClientBrandingAttributes& WithForgotPasswordLink(const char* value) { SetForgotPasswordLink(value); return *this;} /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline const Aws::Map<Aws::String, Aws::String>& GetLoginMessage() const{ return m_loginMessage; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline bool LoginMessageHasBeenSet() const { return m_loginMessageHasBeenSet; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline void SetLoginMessage(const Aws::Map<Aws::String, Aws::String>& value) { m_loginMessageHasBeenSet = true; m_loginMessage = value; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline void SetLoginMessage(Aws::Map<Aws::String, Aws::String>&& value) { m_loginMessageHasBeenSet = true; m_loginMessage = std::move(value); } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& WithLoginMessage(const Aws::Map<Aws::String, Aws::String>& value) { SetLoginMessage(value); return *this;} /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& WithLoginMessage(Aws::Map<Aws::String, Aws::String>&& value) { SetLoginMessage(std::move(value)); return *this;} /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(const Aws::String& key, const Aws::String& value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(key, value); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(Aws::String&& key, const Aws::String& value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(std::move(key), value); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(const Aws::String& key, Aws::String&& value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(key, std::move(value)); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(Aws::String&& key, Aws::String&& value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(const char* key, Aws::String&& value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(key, std::move(value)); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(Aws::String&& key, const char* value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(std::move(key), value); return *this; } /** * <p>The login message. Specified as a key value pair, in which the key is a * locale and the value is the localized message for that locale. The only key * supported is <code>en_US</code>. </p> */ inline IosImportClientBrandingAttributes& AddLoginMessage(const char* key, const char* value) { m_loginMessageHasBeenSet = true; m_loginMessage.emplace(key, value); return *this; } private: Aws::Utils::ByteBuffer m_logo; bool m_logoHasBeenSet; Aws::Utils::ByteBuffer m_logo2x; bool m_logo2xHasBeenSet; Aws::Utils::ByteBuffer m_logo3x; bool m_logo3xHasBeenSet; Aws::String m_supportEmail; bool m_supportEmailHasBeenSet; Aws::String m_supportLink; bool m_supportLinkHasBeenSet; Aws::String m_forgotPasswordLink; bool m_forgotPasswordLinkHasBeenSet; Aws::Map<Aws::String, Aws::String> m_loginMessage; bool m_loginMessageHasBeenSet; }; } // namespace Model } // namespace WorkSpaces } // namespace Aws
charithccmc/incubator-metron
metron-streaming/Metron-DataServices/src/main/java/org/apache/metron/dataservices/modules/guice/ServiceModule.java
<filename>metron-streaming/Metron-DataServices/src/main/java/org/apache/metron/dataservices/modules/guice/ServiceModule.java package org.apache.metron.dataservices.modules.guice; import javax.inject.Singleton; import org.jboss.resteasy.plugins.guice.ext.RequestScopeModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Provides; import org.apache.metron.dataservices.common.MetronService; import org.apache.metron.services.alerts.ElasticSearch_KafkaAlertsService; import org.apache.metron.services.alerts.Solr_KafkaAlertsService; public class ServiceModule extends RequestScopeModule { private static final Logger logger = LoggerFactory.getLogger( ServiceModule.class ); private String[] args; public ServiceModule(String[] args) { this.args = args; } @Provides @Singleton public MetronService socservice() { if (args.length > 0 && args[0].equals("ElasticSearch_KafkaAlertsService")) { return new ElasticSearch_KafkaAlertsService(); } else { return new Solr_KafkaAlertsService(); } } }
codehaus/coconut
cake/trunk/cake-core/cake-management/src/main/java/org/codehaus/cake/management/OperationKey.java
<gh_stars>0 /* Copyright 2004 - 2008 <NAME> <<EMAIL>> * Licensed under the Apache 2.0 License. */ package org.codehaus.cake.management; import java.util.Arrays; /** * An OperationKey is used to represent an operation as a key in a map. * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Id: Cache.java,v 1.2 2005/04/27 15:49:16 kasper Exp $ */ class OperationKey { /** The hashcode of this object. */ private int hashCode; /** The name of the operation. */ private final String methodName; /** The signature of the operation. */ private final String[] signature; /** * Creates a new OperationKey. * * @param methodName * the name of the method * @param signature * the signature of the method */ public OperationKey(String methodName, String... signature) { this.methodName = methodName; if (signature == null) { signature = new String[0]; } this.signature = signature.clone(); hashCode = methodName.hashCode() ^ Arrays.hashCode(signature); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { return obj instanceof OperationKey && equals((OperationKey) obj); } /** * As {@link #equals(Object)} except taking an OperationKey. * * @param obj * the reference object with which to compare. * @return <code>true</code> if this object is the same as the obj argument; * <code>false</code> otherwise. */ public boolean equals(OperationKey obj) { return methodName.equals(obj.methodName) && Arrays.equals(signature, obj.signature); } /** {@inheritDoc} */ @Override public int hashCode() { return hashCode; } }
Gadmind/spring_cloud_learn
msc-alibaba-seata-order-service-2001/src/main/java/com/daop/msc/seata/order/service/OrderService.java
package com.daop.msc.seata.order.service; import com.daop.msc.entities.Order; /** * @BelongsProject: spring_cloud_learn * @BelongsPackage: com.daop.msc.seata.order.service.impl * @Description: * @DATE: 2020-10-27 * @AUTHOR: Administrator **/ public interface OrderService { void creatOrder(Order order); }
vboar/PocketOA
app/src/main/java/top/kass/pocketoa/view/ContractView.java
package top.kass.pocketoa.view; import java.util.List; import top.kass.pocketoa.bean.ContractBean; public interface ContractView { void showProgress(); void addContracts(List<ContractBean> contractList); void hideProgress(); void showLoadFailMsg(); }
wsw2008new/iBase4J
iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/LocaleInterceptor.java
package org.ibase4j.core.interceptor; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.ibase4j.core.util.WebUtil; import org.springframework.context.i18n.LocaleContextHolder; /** * 国际化信息设置(基于SESSION) * * @author ShenHuaJie * @version 2016年5月20日 下午3:16:45 */ public class LocaleInterceptor extends BaseInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); // 设置客户端语言 Locale locale = (Locale) session.getAttribute("LOCALE"); if (locale == null) { String language = request.getParameter("locale"); if (StringUtils.isNotBlank(language)) { locale = new Locale(language); session.setAttribute("LOCALE", locale); } else { locale = request.getLocale(); } } session.setAttribute("HOST", WebUtil.getHost(request)); LocaleContextHolder.setLocale(locale); return super.preHandle(request, response, handler); } }
blockchain-jd-com/jdchain-indexer
chain/init.go
package chain import "github.com/ssor/zlog" var ( logger = zlog.New("chain") )
weijia/djangoautoconf
djangoautoconf/auto_conf_admin_tools/model_with_full_permission_feature.py
<gh_stars>0 from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase __author__ = 'weijia' def get_model_perms(self, request): return {'add': True, 'change': True, 'delete': False} def has_change_permission(self, request, obj=None): return True class ModelWithFullPermissionFeature(AdminFeatureBase): def process_parent_class_list(self, parent_list, class_inst): pass # noinspection PyMethodMayBeStatic def process_admin_class_attr(self, admin_attr, class_inst): admin_attr["get_model_perms"] = get_model_perms admin_attr["has_change_permission"] = has_change_permission admin_attr["has_add_permission"] = has_change_permission
tech-inducers/kuhakT
kuhak-controller/src/main/java/com/kuhak/controller/service/impl/GatewayServiceImpl.java
<gh_stars>1-10 package com.kuhak.controller.service.impl; import com.kuhak.controller.dto.GatewayDto; import com.kuhak.controller.entity.Gateway; import com.kuhak.controller.entity.GatewayStatus; import com.kuhak.controller.repository.GatewayRepository; import com.kuhak.controller.repository.ProtocolRepository; import com.kuhak.controller.service.GatewayService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class GatewayServiceImpl implements GatewayService { @Autowired ProtocolRepository protocolRepository; @Autowired GatewayRepository gatewayRepository; @Override public GatewayDto createOrUpdateGateway(GatewayDto gatewayDto) { Gateway gwR =protocolRepository.findById(gatewayDto.getProtocolId()).map(protocol -> { Gateway gw = new Gateway(); gw.setProtocol(protocol); gw.setActivated_on(gatewayDto.getActivated_on()); gw.setDeviceCount(0); gw.setGatewayIp(gatewayDto.getGatewayIp()); gw.setDeviceLimit(gatewayDto.getDeviceLimit()); gw.setGatewayPort(gatewayDto.getGatewayPort()); gw.setGatewaySuffix(gatewayDto.getGatewaySuffix()); gw.setGatwwayPrefix(gatewayDto.getGatwwayPrefix()); gw.setStatus(GatewayStatus.NEW); return gatewayRepository.save(gw); }).get(); GatewayDto gwdR = new GatewayDto(); gwdR.setProtocolId(gwR.getProtocol().getProtocolId()); gwdR.setGatewayId(gwR.getGatewayId()); gwdR.setGatewayIp(gwR.getGatewayIp()); gwdR.setGatewayPort(gwR.getGatewayPort()); gwdR.setGatewaySuffix(gwR.getGatewaySuffix()); gwdR.setGatwwayPrefix(gwR.getGatwwayPrefix()); gwdR.setDeviceLimit(gwR.getDeviceLimit()); gwdR.setDeviceCount(gwR.getDeviceCount()); gwdR.setStatus(gwR.getStatus().toString()); return gwdR; } @Override public List<GatewayDto> getAllGateways() { return gatewayRepository.findAll().stream().map(gwR -> { GatewayDto gwdR = new GatewayDto(); gwdR.setProtocolId(gwR.getProtocol().getProtocolId()); gwdR.setGatewayId(gwR.getGatewayId()); gwdR.setGatewayIp(gwR.getGatewayIp()); gwdR.setGatewayPort(gwR.getGatewayPort()); gwdR.setGatewaySuffix(gwR.getGatewaySuffix()); gwdR.setGatwwayPrefix(gwR.getGatwwayPrefix()); gwdR.setDeviceLimit(gwR.getDeviceLimit()); gwdR.setDeviceCount(gwR.getDeviceCount()); gwdR.setStatus(gwR.getStatus().toString()); return gwdR; }).collect(Collectors.toList()); } @Override public GatewayDto getGatewayByGatewayId(Long gatewayId) { return gatewayRepository.findById(gatewayId).map(gwR ->{ GatewayDto gwdR = new GatewayDto(); gwdR.setProtocolId(gwR.getProtocol().getProtocolId()); gwdR.setGatewayId(gwR.getGatewayId()); gwdR.setGatewayIp(gwR.getGatewayIp()); gwdR.setGatewayPort(gwR.getGatewayPort()); gwdR.setGatewaySuffix(gwR.getGatewaySuffix()); gwdR.setGatwwayPrefix(gwR.getGatwwayPrefix()); gwdR.setDeviceLimit(gwR.getDeviceLimit()); gwdR.setDeviceCount(gwR.getDeviceCount()); gwdR.setStatus(gwR.getStatus().toString()); return gwdR; }).get(); } @Override public List<GatewayDto> gatAllGatewayByProtocolId(Long protocolId) { return gatewayRepository.findByProtocolProtocolId(protocolId).stream().map(gwR ->{ GatewayDto gwdR = new GatewayDto(); gwdR.setProtocolId(gwR.getProtocol().getProtocolId()); gwdR.setGatewayId(gwR.getGatewayId()); gwdR.setGatewayIp(gwR.getGatewayIp()); gwdR.setGatewayPort(gwR.getGatewayPort()); gwdR.setGatewaySuffix(gwR.getGatewaySuffix()); gwdR.setGatwwayPrefix(gwR.getGatwwayPrefix()); gwdR.setDeviceLimit(gwR.getDeviceLimit()); gwdR.setDeviceCount(gwR.getDeviceCount()); gwdR.setStatus(gwR.getStatus().toString()); return gwdR; }).collect(Collectors.toList()); } }
francisvm/swift
lib/AST/SubstitutionList.cpp
//===--- SubstitutionList.cpp - Compact SubstitutionMap -------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the SubstitutionList class, which is a memory-efficient // representation of a SubstitutionMap, intended to be stored in AST nodes and // SIL instructions. // //===----------------------------------------------------------------------===// #include "swift/AST/SubstitutionList.h" #include "swift/AST/ProtocolConformanceRef.h" #include "llvm/ADT/FoldingSet.h" using namespace swift; void swift::profileSubstitutionList(llvm::FoldingSetNodeID &id, SubstitutionList subs) { id.AddInteger(subs.size()); for (auto &sub : subs) { id.AddPointer(sub.getReplacement().getPointer()); for (auto conformance : sub.getConformances()) id.AddPointer(conformance.getOpaqueValue()); } }
softwarelma/epe
src/main/java/com/softwarelma/epe/p3/print/EpePrintFinalPrint_separator.java
<reponame>softwarelma/epe package com.softwarelma.epe.p3.print; import java.util.List; import com.softwarelma.epe.p1.app.EpeAppException; import com.softwarelma.epe.p1.app.EpeAppUtils; import com.softwarelma.epe.p2.exec.EpeExecContent; import com.softwarelma.epe.p2.exec.EpeExecParams; import com.softwarelma.epe.p2.exec.EpeExecResult; public final class EpePrintFinalPrint_separator extends EpePrintAbstract { @Override public EpeExecResult doFunc(EpeExecParams execParams, List<EpeExecResult> listExecResult) throws EpeAppException { String postMessage = "print_separator, expected a list with the param, external and internal separators " + "and the contents to print."; List<String> listStr = getListStringAt(listExecResult, 0, postMessage); String sepParam = listStr.size() > 0 ? listStr.get(0) : ""; String sepExternal = listStr.size() > 1 ? listStr.get(1) : ""; String sepInternal = listStr.size() > 2 ? listStr.get(2) : ""; String str = retrievePrintableStrWithSeparators(sepParam, sepExternal, sepInternal, listExecResult, 1); log(execParams, str); return createResult(str); } public static String retrievePrintableStrWithSeparators(String sepParam, String sepExternal, String sepInternal, List<EpeExecResult> listExecResult, int startingIndex) throws EpeAppException { EpeAppUtils.checkNull("listExecResult", listExecResult); StringBuilder sb = new StringBuilder(); String sepParam2 = ""; for (int i = startingIndex; i < listExecResult.size(); i++) { EpeExecResult result = listExecResult.get(i); EpeAppUtils.checkNull("result", result); EpeExecContent content = result.getExecContent(); EpeAppUtils.checkNull("content", content); sb.append(sepParam2); sepParam2 = sepParam; sb.append(content.toString(sepExternal, sepInternal)); } return sb.toString(); } }
lzmchinafirst/dogmail
dogmall-back/src/main/java/org/singledog/dogmall/back/adapter/web/TestService.java
<reponame>lzmchinafirst/dogmail<gh_stars>1-10 package org.singledog.dogmall.back.adapter.web; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class TestService { @Async public String test() { return "succes" + "s"; } }
montoyo/mgpcl
src/FFT.cpp
<filename>src/FFT.cpp<gh_stars>0 /* Copyright (C) 2017 <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. */ #define M_FFT_DECLARE #include "mgpcl/FFT.h" #include "mgpcl/Math.h" #include "mgpcl/SSE.h" _PS_CONST(4, 4.0f); static const ALIGN16_BEG float _ps_0123[4] ALIGN16_END = { 0.0f, 1.0f, 2.0f, 3.0f }; #ifdef MGPCL_WIN #define M_FORCE_INLINE(rtype) rtype __forceinline #else #define M_FORCE_INLINE(rtype) __attribute__((always_inline)) rtype #endif namespace m { M_FORCE_INLINE(static void) applyFFT_4(const float *aIn, float *aOut, float *bOut, uint32_t stride) { //applyFFT_ps(aIn, aOut, bOut, 2, 2 * stride) float a0 = aIn[0]; float a1 = aIn[stride << 1]; aOut[0] = a0 + a1; aOut[1] = a0 - a1; bOut[0] = 0.0f; bOut[1] = 0.0f; //applyFFT_ps(aIn + stride, aOut + 2, bOut + 2, 2, 2 * stride) a0 = aIn[stride]; a1 = aIn[3 * stride]; aOut[2] = a0 + a1; aOut[3] = a0 - a1; bOut[2] = 0.0f; bOut[3] = 0.0f; //Here, half = 2, so: // * for i = 0, twA = aOut[2], twB = bOut[2] // * for i = 1, twAng = -2 * PI / 4 = -PI / 2 => twA = bOut[3], twB = -aOut[3] //i = 0 float twA = aOut[2]; float twB = bOut[2]; float tmp = aOut[0]; aOut[0] += twA; aOut[2] = tmp - twA; tmp = bOut[0]; bOut[0] += twB; bOut[2] = tmp - twB; //i = 1 twA = bOut[3]; twB = -aOut[3]; tmp = aOut[1]; aOut[1] += twA; aOut[3] = tmp - twA; tmp = bOut[1]; bOut[1] += twB; bOut[3] = tmp - twB; } static void applyFFT_ps(const float *aIn, float *aOut, float *bOut, uint32_t cnt, uint32_t stride) { if(cnt == 4) applyFFT_4(aIn, aOut, bOut, stride); else { uint32_t half = cnt >> 1; uint32_t dbl = stride << 1; applyFFT_ps(aIn, aOut, bOut, half, dbl); //TODO: Recursion = bad applyFFT_ps(aIn + stride, aOut + half, bOut + half, half, dbl); M128 xmm0, xmm7; xmm7 = _mm_set1_ps(-2.0f * static_cast<float>(M_PI) / static_cast<float>(cnt)); xmm0 = _mm_mul_ps(xmm7, _PS_CONST_GET(0123)); //xmm0 = twAng xmm7 = _mm_mul_ps(xmm7, _PS_CONST_GET(4)); //xmm7 = twMul for(uint32_t i = 0; i < half; i += 4) { M128 xmm1, xmm2; uint32_t j = half + i; sse::sincos_ps(xmm0, &xmm2, &xmm1); //xmm1 = twCos, xmm2 = twSin M128 xmm3, xmm4, xmm5, xmm6; xmm3 = _mm_load_ps(aOut + j); //xmm3 = aOut[j] xmm4 = _mm_load_ps(bOut + j); //xmm4 = bOut[j] xmm5 = _mm_mul_ps(xmm1, xmm3); //xmm5 = twCos * aOut[j] xmm6 = _mm_mul_ps(xmm2, xmm4); //xmm6 = twSin * bOut[j] xmm5 = _mm_sub_ps(xmm5, xmm6); //xmm5 = xmm5 - xmm6 (twA) xmm1 = _mm_mul_ps(xmm1, xmm4); //xmm1 = twCos * bOut[j] xmm2 = _mm_mul_ps(xmm2, xmm3); //xmm2 = twSin * aOut[j] xmm6 = _mm_add_ps(xmm1, xmm2); //xmm6 = xmm1 + xmm2 (twB) xmm1 = _mm_load_ps(aOut + i); //xmm1 = aOut[i] (tmp) xmm2 = _mm_add_ps(xmm1, xmm5); //xmm2 = tmp + twA _mm_store_ps(aOut + i, xmm2); //aOut[i] = xmm2 xmm2 = _mm_sub_ps(xmm1, xmm5); //xmm2 = tmp - twA _mm_store_ps(aOut + j, xmm2); //aOut[j] = xmm2 xmm1 = _mm_load_ps(bOut + i); //xmm1 = bOut[i] (tmp) xmm2 = _mm_add_ps(xmm1, xmm6); //xmm2 = tmp + twB _mm_store_ps(bOut + i, xmm2); //bOut[i] = xmm2 xmm2 = _mm_sub_ps(xmm1, xmm6); //xmm2 = tmp - twB _mm_store_ps(bOut + j, xmm2); //bOut[j] = xmm2 xmm0 = _mm_add_ps(xmm0, xmm7); //xmm0 = twAng + twMul } } } static void applyFFT_basic(const float *aIn, float *aOut, float *bOut, uint32_t cnt, uint32_t stride) { if(cnt == 4) applyFFT_4(aIn, aOut, bOut, stride); else { uint32_t half = cnt >> 1; uint32_t dbl = stride << 1; applyFFT_basic(aIn, aOut, bOut, half, dbl); //TODO: Recursion = bad applyFFT_basic(aIn + stride, aOut + half, bOut + half, half, dbl); float twMul = -2.0f * static_cast<float>(M_PI) / static_cast<float>(cnt); float twAng = 0.0f; for(uint32_t i = 0; i < half; i++) { uint32_t j = half + i; float twCos = math::cos<float>(twAng); float twSin = math::sin<float>(twAng); float twA = twCos * aOut[j] - twSin * bOut[j]; float twB = twCos * bOut[j] + twSin * aOut[j]; float tmp = aOut[i]; aOut[i] += twA; aOut[j] = tmp - twA; tmp = bOut[i]; bOut[i] += twB; bOut[j] = tmp - twB; twAng += twMul; } } } } void m::fft::applySSE(const float *aIn, float *aOut, float *bOut, uint32_t cnt) { applyFFT_ps(aIn, aOut, bOut, cnt, 1); } void m::fft::apply(const float *aIn, float *aOut, float *bOut, uint32_t cnt) { applyFFT_basic(aIn, aOut, bOut, cnt, 1); } void m::fft::absSSE(const float *aIn, const float *bIn, float *result, uint32_t cnt) { M128 xmm0, xmm1; for(uint32_t i = 0; i < cnt; i += 4) { xmm0 = _mm_load_ps(aIn + i); xmm0 = _mm_mul_ps(xmm0, xmm0); xmm1 = _mm_load_ps(bIn + i); xmm1 = _mm_mul_ps(xmm1, xmm1); xmm0 = _mm_add_ps(xmm0, xmm1); xmm0 = _mm_sqrt_ps(xmm0); _mm_store_ps(result + i, xmm0); } } void m::fft::abs2SSE(const float *aIn, const float *bIn, float *result, uint32_t cnt, float constant) { M128 xmm0, xmm1, xmm2; xmm2 = _mm_set1_ps(constant); for(uint32_t i = 0; i < cnt; i += 4) { xmm0 = _mm_load_ps(aIn + i); xmm0 = _mm_mul_ps(xmm0, xmm0); xmm1 = _mm_load_ps(bIn + i); xmm1 = _mm_mul_ps(xmm1, xmm1); xmm0 = _mm_add_ps(xmm0, xmm1); xmm0 = _mm_sqrt_ps(xmm0); xmm0 = _mm_mul_ps(xmm0, xmm2); _mm_store_ps(result + i, xmm0); } }
jkimmeyer/alchemy_cms
spec/views/essences/essence_page_view_spec.rb
# frozen_string_literal: true require 'rails_helper' describe 'alchemy/essences/_essence_page_view' do let(:page) { build(:alchemy_page, urlname: 'a-page') } let(:essence) { Alchemy::EssencePage.new(page: page) } let(:content) { Alchemy::Content.new(essence: essence) } context 'without page' do let(:essence) { Alchemy::EssencePage.new } it "renders nothing" do render content, content: content expect(rendered).to eq('') end end context 'with page' do it "renders a link to the page" do render content, content: content expect(rendered).to have_selector("a[href='/#{page.urlname}']") end it "has the page name as link text" do render content, content: content expect(rendered).to have_selector("a:contains('#{page.name}')") end end end
takeej/device-sdk-javame
SimpleSDK/src/org/eclipse/paho/client/mqttv3/MqttClient.java
<filename>SimpleSDK/src/org/eclipse/paho/client/mqttv3/MqttClient.java /******************************************************************************* * Copyright (c) 2009, 2015 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * <NAME> - initial API and implementation and/or initial documentation * <NAME> - MQTT 3.1.1 support * <NAME> - per subscription message handlers (bug 466579) * <NAME> - ack control (bug 472172) */ package org.eclipse.paho.client.mqttv3; import tp.java.util.Properties; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.eclipse.paho.client.mqttv3.util.Debug; /** * Lightweight client for talking to an MQTT server using methods that block * until an operation completes. * * <p>This class implements the blocking {@link IMqttClient} client interface where all * actions block until they have completed (or timed out). * This implementation is compatible with all Java SE runtimes from 1.4.2 and up. * </p> * <p>An application can connect to an MQTT server using: * <ul> * <li>A plain TCP socket * <li>An secure SSL/TLS socket * </ul> * </p> * <p>To enable messages to be delivered even across network and client restarts * messages need to be safely stored until the message has been delivered at the requested * quality of service. A pluggable persistence mechanism is provided to store the messages. * </p> * <p>By default {@link MqttDefaultFilePersistence} is used to store messages to a file. * If persistence is set to null then messages are stored in memory and hence can be lost * if the client, Java runtime or device shuts down. * </p> * <p>If connecting with {@link MqttConnectOptions#setCleanSession(boolean)} set to true it * is safe to use memory persistence as all state it cleared when a client disconnects. If * connecting with cleanSession set to false, to provide reliable message delivery * then a persistent message store should be used such as the default one. </p> * <p>The message store interface is pluggable. Different stores can be used by implementing * the {@link MqttClientPersistence} interface and passing it to the clients constructor. * </p> * * @see IMqttClient */ public class MqttClient implements IMqttClient { //), DestinationProvider { //private static final String CLASS_NAME = MqttClient.class.getName(); //private static final Logger log = LoggerFactory.getLogger(LoggerFactory.MQTT_CLIENT_MSG_CAT,CLASS_NAME); protected MqttAsyncClient aClient = null; // Delegate implementation to MqttAsyncClient protected long timeToWait = -1; // How long each method should wait for action to complete /** * Create an MqttClient that can be used to communicate with an MQTT server. * <p> * The address of a server can be specified on the constructor. Alternatively * a list containing one or more servers can be specified using the * {@link MqttConnectOptions#setServerURIs(String[]) setServerURIs} method * on MqttConnectOptions. * * <p>The <code>serverURI</code> parameter is typically used with the * the <code>clientId</code> parameter to form a key. The key * is used to store and reference messages while they are being delivered. * Hence the serverURI specified on the constructor must still be specified even if a list * of servers is specified on an MqttConnectOptions object. * The serverURI on the constructor must remain the same across * restarts of the client for delivery of messages to be maintained from a given * client to a given server or set of servers. * * <p>The address of the server to connect to is specified as a URI. Two types of * connection are supported <code>tcp://</code> for a TCP connection and * <code>ssl://</code> for a TCP connection secured by SSL/TLS. * For example: * <ul> * <li><code>tcp://localhost:1883</code></li> * <li><code>ssl://localhost:8883</code></li> * </ul> * If the port is not specified, it will * default to 1883 for <code>tcp://</code>" URIs, and 8883 for <code>ssl://</code> URIs. * </p> * * <p> * A client identifier <code>clientId</code> must be specified and be less that 65535 characters. * It must be unique across all clients connecting to the same * server. The clientId is used by the server to store data related to the client, * hence it is important that the clientId remain the same when connecting to a server * if durable subscriptions or reliable messaging are required. * <p>A convenience method is provided to generate a random client id that * should satisfy this criteria - {@link #generateClientId()}. As the client identifier * is used by the server to identify a client when it reconnects, the client must use the * same identifier between connections if durable subscriptions or reliable * delivery of messages is required. * </p> * <p> * In Java SE, SSL can be configured in one of several ways, which the * client will use in the following order: * </p> * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can * use {@link MqttConnectOptions#setSocketFactory(SocketFactory)} to supply * a factory with the appropriate SSL settings.</li> * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a * simple Java Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}.</li> * <li><strong>Use JVM settings</strong> - There are a number of standard * Java system properties that can be used to configure key and trust stores.</li> * </ul> * * <p>In Java ME, the platform settings are used for SSL connections.</p> * * <p>An instance of the default persistence mechanism {@link MqttDefaultFilePersistence} * is used by the client. To specify a different persistence mechanism or to turn * off persistence, use the {@link #MqttClient(String, String, MqttClientPersistence)} * constructor. * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden using * {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @throws IllegalArgumentException if the URI does not start with * "tcp://", "ssl://" or "local://". * @throws IllegalArgumentException if the clientId is null or is greater than 65535 characters in length * @throws MqttException if any other problem was encountered */ public MqttClient(String serverURI, String clientId) throws MqttException { this(serverURI,clientId, new MemoryPersistence()); } /** * Create an MqttClient that can be used to communicate with an MQTT server. * <p> * The address of a server can be specified on the constructor. Alternatively * a list containing one or more servers can be specified using the * {@link MqttConnectOptions#setServerURIs(String[]) setServerURIs} method * on MqttConnectOptions. * * <p>The <code>serverURI</code> parameter is typically used with the * the <code>clientId</code> parameter to form a key. The key * is used to store and reference messages while they are being delivered. * Hence the serverURI specified on the constructor must still be specified even if a list * of servers is specified on an MqttConnectOptions object. * The serverURI on the constructor must remain the same across * restarts of the client for delivery of messages to be maintained from a given * client to a given server or set of servers. * * <p>The address of the server to connect to is specified as a URI. Two types of * connection are supported <code>tcp://</code> for a TCP connection and * <code>ssl://</code> for a TCP connection secured by SSL/TLS. * For example: * <ul> * <li><code>tcp://localhost:1883</code></li> * <li><code>ssl://localhost:8883</code></li> * </ul> * If the port is not specified, it will * default to 1883 for <code>tcp://</code>" URIs, and 8883 for <code>ssl://</code> URIs. * </p> * * <p> * A client identifier <code>clientId</code> must be specified and be less that 65535 characters. * It must be unique across all clients connecting to the same * server. The clientId is used by the server to store data related to the client, * hence it is important that the clientId remain the same when connecting to a server * if durable subscriptions or reliable messaging are required. * <p>A convenience method is provided to generate a random client id that * should satisfy this criteria - {@link #generateClientId()}. As the client identifier * is used by the server to identify a client when it reconnects, the client must use the * same identifier between connections if durable subscriptions or reliable * delivery of messages is required. * </p> * <p> * In Java SE, SSL can be configured in one of several ways, which the * client will use in the following order: * </p> * <ul> * <li><strong>Supplying an <code>SSLSocketFactory</code></strong> - applications can * use {@link MqttConnectOptions#setSocketFactory(SocketFactory)} to supply * a factory with the appropriate SSL settings.</li> * <li><strong>SSL Properties</strong> - applications can supply SSL settings as a * simple Java Properties using {@link MqttConnectOptions#setSSLProperties(Properties)}.</li> * <li><strong>Use JVM settings</strong> - There are a number of standard * Java system properties that can be used to configure key and trust stores.</li> * </ul> * * <p>In Java ME, the platform settings are used for SSL connections.</p> * <p> * A persistence mechanism is used to enable reliable messaging. * For messages sent at qualities of service (QoS) 1 or 2 to be reliably delivered, * messages must be stored (on both the client and server) until the delivery of the message * is complete. If messages are not safely stored when being delivered then * a failure in the client or server can result in lost messages. A pluggable * persistence mechanism is supported via the {@link MqttClientPersistence} * interface. An implementer of this interface that safely stores messages * must be specified in order for delivery of messages to be reliable. In * addition {@link MqttConnectOptions#setCleanSession(boolean)} must be set * to false. In the event that only QoS 0 messages are sent or received or * cleanSession is set to true then a safe store is not needed. * </p> * <p>An implementation of file-based persistence is provided in * class {@link MqttDefaultFilePersistence} which will work in all Java SE based * systems. If no persistence is needed, the persistence parameter * can be explicitly set to <code>null</code>.</p> * * @param serverURI the address of the server to connect to, specified as a URI. Can be overridden using * {@link MqttConnectOptions#setServerURIs(String[])} * @param clientId a client identifier that is unique on the server being connected to * @param persistence the persistence class to use to store in-flight message. If null then the * default persistence mechanism is used * @throws IllegalArgumentException if the URI does not start with * "tcp://", "ssl://" or "local://" * @throws IllegalArgumentException if the clientId is null or is greater than 65535 characters in length * @throws MqttException if any other problem was encountered */ public MqttClient(String serverURI, String clientId, MqttClientPersistence persistence) throws MqttException { aClient = new MqttAsyncClient(serverURI, clientId, persistence); } /* * @see IMqttClient#connect() */ public void connect() throws MqttSecurityException, MqttException { this.connect(new MqttConnectOptions()); } /* * @see IMqttClient#connect(MqttConnectOptions) */ public void connect(MqttConnectOptions options) throws MqttSecurityException, MqttException { aClient.connect(options, null, null).waitForCompletion(getTimeToWait()); } /* * @see IMqttClient#connect(MqttConnectOptions) */ public void connect(MqttConnectOptions options, IMqttActionListener listener) throws MqttSecurityException, MqttException { aClient.connect(options, null, listener).waitForCompletion(getTimeToWait()); } /* * @see IMqttClient#connect(MqttConnectOptions) */ public IMqttToken connectWithResult(MqttConnectOptions options) throws MqttSecurityException, MqttException { IMqttToken tok = aClient.connect(options, null, null); tok.waitForCompletion(getTimeToWait()); return tok; } /* * @see IMqttClient#disconnect() */ public void disconnect() throws MqttException { aClient.disconnect().waitForCompletion(); } /* * @see IMqttClient#disconnect(long) */ public void disconnect(long quiesceTimeout) throws MqttException { aClient.disconnect(quiesceTimeout, null, null).waitForCompletion(); } /* * (non-Javadoc) * * @see org.eclipse.paho.client.mqttv3.IMqttAsyncClient#disconnectForcibly() */ public void disconnectForcibly() throws MqttException { aClient.disconnectForcibly(); } /* * (non-Javadoc) * * @see org.eclipse.paho.client.mqttv3.IMqttAsyncClient#disconnectForcibly(long) */ public void disconnectForcibly(long disconnectTimeout) throws MqttException { aClient.disconnectForcibly(disconnectTimeout); } /* * (non-Javadoc) * * @see org.eclipse.paho.client.mqttv3.IMqttAsyncClient#disconnectForcibly(long, long) */ public void disconnectForcibly(long quiesceTimeout, long disconnectTimeout) throws MqttException { aClient.disconnectForcibly(quiesceTimeout, disconnectTimeout); } /* * @see IMqttClient#subscribe(String) */ public void subscribe(String topicFilter) throws MqttException { this.subscribe(new String[] {topicFilter}, new int[] {1}); } /* * @see IMqttClient#subscribe(String[]) */ public void subscribe(String[] topicFilters) throws MqttException { int[] qos = new int[topicFilters.length]; for (int i=0; i<qos.length; i++) { qos[i] = 1; } this.subscribe(topicFilters, qos); } /* * @see IMqttClient#subscribe(String, int) */ public void subscribe(String topicFilter, int qos) throws MqttException { this.subscribe(new String[] {topicFilter}, new int[] {qos}); } /* * @see IMqttClient#subscribe(String[], int[]) */ public void subscribe(String[] topicFilters, int[] qos) throws MqttException { IMqttToken tok = aClient.subscribe(topicFilters, qos, null, null); tok.waitForCompletion(getTimeToWait()); int[] grantedQos = tok.getGrantedQos(); for (int i = 0; i < grantedQos.length; ++i) { qos[i] = grantedQos[i]; } if (grantedQos.length == 1 && qos[0] == 0x80) { throw new MqttException(MqttException.REASON_CODE_SUBSCRIBE_FAILED); } } /* * @see IMqttClient#subscribe(String[], int[]) */ public void subscribe(String[] topicFilters, int[] qos, IMqttActionListener listener) throws MqttException { IMqttToken tok = aClient.subscribe(topicFilters, qos, null, listener); tok.waitForCompletion(getTimeToWait()); int[] grantedQos = tok.getGrantedQos(); for (int i = 0; i < grantedQos.length; ++i) { qos[i] = grantedQos[i]; } if (grantedQos.length == 1 && qos[0] == 0x80) { throw new MqttException(MqttException.REASON_CODE_SUBSCRIBE_FAILED); } } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#subscribe(java.lang.String, int, java.lang.Object, org.eclipse.paho.client.mqttv3.IMqttActionListener) */ public void subscribe(String topicFilter, IMqttMessageListener messageListener) throws MqttException { this.subscribe(new String[] {topicFilter}, new int[] {1}, new IMqttMessageListener[] {messageListener}); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#subscribe(java.lang.String, int, java.lang.Object, org.eclipse.paho.client.mqttv3.IMqttActionListener) */ public void subscribe(String[] topicFilters, IMqttMessageListener[] messageListeners) throws MqttException { int[] qos = new int[topicFilters.length]; for (int i=0; i<qos.length; i++) { qos[i] = 1; } this.subscribe(topicFilters, qos, messageListeners); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#subscribe(java.lang.String, int) */ public void subscribe(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException { this.subscribe(new String[] {topicFilter}, new int[] {qos}, new IMqttMessageListener[] {messageListener}); } public void subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException { this.subscribe(topicFilters, qos); // add message handlers to the list for this client for (int i = 0; i < topicFilters.length; ++i) { aClient.comms.setMessageListener(topicFilters[i], messageListeners[i]); } } /* * @see IMqttClient#unsubscribe(String) */ public void unsubscribe(String topicFilter) throws MqttException { unsubscribe(new String[] {topicFilter}); } /* * @see IMqttClient#unsubscribe(String[]) */ public void unsubscribe(String[] topicFilters) throws MqttException { // message handlers removed in the async client unsubscribe below aClient.unsubscribe(topicFilters, null,null).waitForCompletion(getTimeToWait()); } /* * @see IMqttClient#publishBlock(String, byte[], int, boolean) */ public void publish(String topic, byte[] payload,int qos, boolean retained) throws MqttException, MqttPersistenceException { MqttMessage message = new MqttMessage(payload); message.setQos(qos); message.setRetained(retained); this.publish(topic, message); } /* * @see IMqttClient#publishBlock(String, MqttMessage) */ public void publish(String topic, MqttMessage message) throws MqttException, MqttPersistenceException { aClient.publish(topic, message, null, null).waitForCompletion(getTimeToWait()); } /* * @see IMqttClient#publishBlock(String, MqttMessage) */ public void publish(String topic, MqttMessage message, IMqttActionListener listener) throws MqttException, MqttPersistenceException { aClient.publish(topic, message, null, listener).waitForCompletion(getTimeToWait()); } /** * Set the maximum time to wait for an action to complete. * <p>Set the maximum time to wait for an action to complete before * returning control to the invoking application. Control is returned * when: * <ul> * <li>the action completes * <li>or when the timeout if exceeded * <li>or when the client is disconnect/shutdown * <ul> * The default value is -1 which means the action will not timeout. * In the event of a timeout the action carries on running in the * background until it completes. The timeout is used on methods that * block while the action is in progress. * </p> * @param timeToWaitInMillis before the action times out. A value or 0 or -1 will wait until * the action finishes and not timeout. */ public void setTimeToWait(long timeToWaitInMillis) throws IllegalArgumentException{ if (timeToWaitInMillis < -1) { throw new IllegalArgumentException(); } this.timeToWait = timeToWaitInMillis; } /** * Return the maximum time to wait for an action to complete. * @see MqttClient#setTimeToWait(long) */ public long getTimeToWait() { return this.timeToWait; } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#close() */ public void close() throws MqttException { aClient.close(); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#getClientId() */ public String getClientId() { return aClient.getClientId(); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#getPendingDeliveryTokens() */ public IMqttDeliveryToken[] getPendingDeliveryTokens() { return aClient.getPendingDeliveryTokens(); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#getServerURI() */ public String getServerURI() { return aClient.getServerURI(); } /** * Returns the currently connected Server URI * Implemented due to: https://bugs.eclipse.org/bugs/show_bug.cgi?id=481097 * * Where getServerURI only returns the URI that was provided in * MqttAsyncClient's constructor, getCurrentServerURI returns the URI of the * Server that the client is currently connected to. This would be different in scenarios * where multiple server URIs have been provided to the MqttConnectOptions. * * @return the currently connected server URI */ public String getCurrentServerURI(){ return aClient.getCurrentServerURI(); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#getTopic(java.lang.String) */ public MqttTopic getTopic(String topic) { return aClient.getTopic(topic); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#isConnected() */ public boolean isConnected() { return aClient.isConnected(); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#setCallback(org.eclipse.paho.client.mqttv3.MqttCallback) */ public void setCallback(MqttCallback callback) { aClient.setCallback(callback); } /* (non-Javadoc) * @see org.eclipse.paho.client.mqttv3.IMqttClient#setCallback(org.eclipse.paho.client.mqttv3.MqttCallback) */ public void setManualAcks(boolean manualAcks) { aClient.setManualAcks(manualAcks); } public void messageArrivedComplete(int messageId, int qos) throws MqttException { aClient.messageArrivedComplete(messageId, qos); } /** * Returns a randomly generated client identifier based on the current user's login * name and the system time. * <p>When cleanSession is set to false, an application must ensure it uses the * same client identifier when it reconnects to the server to resume state and maintain * assured message delivery.</p> * @return a generated client identifier * @see MqttConnectOptions#setCleanSession(boolean) */ public static String generateClientId() { return MqttAsyncClient.generateClientId(); } public void reconnect() throws MqttException { aClient.reconnect(); } /** * Return a debug object that can be used to help solve problems. */ public Debug getDebug() { return (aClient.getDebug()); } }
kkcookies99/UAST
Dataset/Leetcode/train/101/417.java
<gh_stars>0 class Solution { public boolean XXX(TreeNode root) { if (root == null) return true; if (root.left == null && root.right == null) return true; if (root.right == null && root.left != null) return false; if (root.left == null && root.right != null) return false; Queue<TreeNode> queue = new LinkedList<>(); Queue<TreeNode> queue2 = new LinkedList<>(); queue.offer(root.left); queue2.offer(root.right); while (!queue.isEmpty() && !queue2.isEmpty()) { TreeNode p1 = queue.poll(); TreeNode p2 = queue2.poll(); if (p1.val != p2.val) return false; if (p1.left == null && p2.right != null) return false; if (p1.right == null && p2.left != null) return false; if (p1.left != null) queue.offer(p1.left); if (p1.right != null) queue.offer(p1.right); if (p2.right != null) queue2.offer(p2.right); if (p2.left != null) queue2.offer(p2.left); if (queue.size() != queue2.size()) return false; } return true; } }
stereodenis/devise_jwt_auth
app/controllers/devise_jwt_auth/refresh_token_controller.rb
# frozen_string_literal: true module DeviseJwtAuth # Controller that handles sending refresh tokens. class RefreshTokenController < DeviseJwtAuth::ApplicationController before_action :set_user_by_refresh_token def show if @resource yield @resource if block_given? render_refresh_token_success else render_refresh_token_error end end protected def resource_data response_data = @resource.as_json response_data['type'] = @resource.class.name.parameterize if json_api? response_data end def render_refresh_token_success response_data = { status: 'success', data: resource_data } response_data.merge!(@resource.create_named_token_pair) if active_for_authentication? render json: response_data end def render_refresh_token_error render_error(401, I18n.t('devise_jwt_auth.token_validations.invalid')) end def active_for_authentication? !@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication? end end end
ArselonHub/ArtCore-stm32f4
Includes/Art/Private/WaitLink.h
/* * WaitLink.h * * Created on: Oct 27, 2016 * Author: denizcan */ #ifndef SOURCE_ART_PRIVATE_WAITLINK_H_ #define SOURCE_ART_PRIVATE_WAITLINK_H_ #include <Art/BasicList.h> #include <Art/Private/WaitHandler.h> namespace Art { class Thread; class Event; namespace Private { class WaitLink { public: WaitLink(WaitHandler* waitHandler); WaitHandler* waitHandler(); private: WaitLink* m_next; WaitLink* m_previous; WaitLink* m_nextLink; WaitHandler* m_waitHandler; friend class BasicList<WaitLink>; friend class WaitHandler; friend class EventWaitHandler; friend class Art::Event; }; inline WaitLink::WaitLink(WaitHandler* waitHandler) { m_waitHandler = waitHandler; m_nextLink = waitHandler->m_links; waitHandler->m_links = this; } inline WaitHandler* WaitLink::waitHandler() { return m_waitHandler; } } } /* namespace Art */ #endif /* SOURCE_ART_PRIVATE_WAITLINK_H_ */
b20vineeth/mallureport-admin
src/main/java/com/easypick/framework/utility/validation/ValidationBI.java
package com.easypick.framework.utility.validation; import com.easypick.framework.utility.exception.BussinessException; import com.easypick.framework.utility.vo.ResponseVo; import com.easypick.framework.utility.vo.WatchDogVo; public interface ValidationBI { ResponseVo execute(WatchDogVo watchDogVo, String req) throws BussinessException; }