code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package wad.config; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import wad.domain.Account; import wad.domain.Player; import wad.domain.Series; import wad.domain.Team; import wad.domain.Tournament; import wad.repository.AccountRepository; import wad.repository.PlayerRepository; import wad.repository.SeriesRepository; import wad.repository.TeamRepository; import wad.repository.TournamentRepository; import wad.service.TeamService; import wad.service.TournamentService; import wad.util.SeriesGenerator; @Profile("default") @Configuration @EnableWebSecurity public class DefaultSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private TournamentService tournamentService; @Autowired private TeamService teamService; @Autowired private SeriesRepository seriesRepository; @Autowired private PlayerRepository playerRepository; @Autowired private AccountRepository accountRepository; private boolean ekaKerta; @Override protected void configure(HttpSecurity http) throws Exception { // sallitaan h2-konsolin kรคyttรถ http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.authorizeRequests() .anyRequest().permitAll(); http .formLogin() .loginPage("/login.html") .failureUrl("/login-error.html") .and() .logout() .logoutSuccessUrl("/tournaments.html"); testingStuff(); } @Configuration protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter { @Autowired private JpaAuthenticationProvider jpaAuthenticationProvider; @Override public void init(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(jpaAuthenticationProvider); } } // @Autowired // public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication() // .withUser("jack").password("bauer").roles("USER"); // } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } public void testingStuff() { if (ekaKerta == false) { Account account = new Account(); account.setUsername("admin"); account.setPassword("password"); accountRepository.save(account); tournamentService.deleteAll(); Tournament testi = new Tournament(); testi.setName("Turnaus"); testi.setDate(new Date()); Team eka = new Team(); Team toka = new Team(); Team kolmas = new Team(); Team neljas = new Team(); eka.setName("ekatiimi"); toka.setName("tokatiimi"); kolmas.setName("kolmastiimis"); neljas.setName("neljastiimi"); tournamentService.save(testi); List<Team> teams = saveTestPlayers(eka, toka, kolmas, neljas, testi); testi.setTeams(teams); SeriesGenerator seriesGenerator = new SeriesGenerator(); List<Series> series = seriesGenerator.generate(tournamentService.findByName("Turnaus"), teams); Collections.sort(series); for (Series serie : series) { seriesRepository.save(serie); } ekaKerta = true; } } public List<Team> saveTestPlayers(Team eka, Team toka, Team kolmas, Team neljas, Tournament testi) { eka.setTournament(testi); toka.setTournament(testi); kolmas.setTournament(testi); neljas.setTournament(testi); // teamService.save(eka); // teamService.save(toka); // teamService.save(kolmas); // teamService.save(neljas); // Player pekka = new Player(); // pekka.setName("pekka"); //// playerRepository.save(pekka); // Player heikki = new Player("heikki"); //// playerRepository.save(heikki); // Player seppo = new Player("seppo"); //// playerRepository.save(seppo); // eka.setPlayers(Arrays.asList(pekka, heikki, seppo)); // // Player marjatta = new Player("marjatta"); //// playerRepository.save(marjatta); // Player sirkka = new Player("sirkka"); //// playerRepository.save(sirkka); // Player sirpa = new Player("sirpa"); //// playerRepository.save(sirpa); // toka.setPlayers(Arrays.asList(marjatta, sirkka, sirpa)); // // Player rommel = new Player("rommel"); //// playerRepository.save(rommel); // Player patton = new Player("patton"); //// playerRepository.save(patton); // Player mannerheim = new Player("mannerheim"); //// playerRepository.save(mannerheim); // kolmas.setPlayers(Arrays.asList(rommel, patton, mannerheim)); // // Player saara = new Player("saara"); //// playerRepository.save(saara); // Player tom = new Player("tom"); //// playerRepository.save(tom); // Player jerry = new Player("jerry"); //// playerRepository.save(jerry); // neljas.setPlayers(Arrays.asList(saara, tom, jerry)); eka.setPlayersString("pekka"); toka.setPlayersString("sirpa"); kolmas.setPlayersString("rommel"); neljas.setPlayersString("saara"); tournamentService.addTeam(eka, "Turnaus"); tournamentService.addTeam(toka, "Turnaus"); tournamentService.addTeam(kolmas, "Turnaus"); tournamentService.addTeam(neljas, "Turnaus"); List<Team> teams = new ArrayList<>(); teams.addAll(tournamentService.findAllTeams("Turnaus")); return teams; } }
eerolahdenpera/rltournament
src/main/java/wad/config/DefaultSecurityConfiguration.java
Java
gpl-3.0
6,931
package com.idega.block.finance.data; public class AccountEntryHomeImpl extends com.idega.data.IDOFactory implements AccountEntryHome { protected Class getEntityInterfaceClass(){ return AccountEntry.class; } public AccountEntry create() throws javax.ejb.CreateException{ return (AccountEntry) super.createIDO(); } public java.util.Collection findByAccountAndAssessmentRound(java.lang.Integer p0,java.lang.Integer p1)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindByAccountAndAssessmentRound(p0,p1); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public java.util.Collection findByAccountAndStatus(java.lang.Integer p0,java.lang.String p1,java.sql.Date p2,java.sql.Date p3,String assessmentStatus)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindByAccountAndStatus(p0,p1,p2,p3,assessmentStatus); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public java.util.Collection findByAssessmentRound(java.lang.Integer p0)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindByAssessmentRound(p0); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public java.util.Collection findByEntryGroup(java.lang.Integer p0)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindByEntryGroup(p0); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public java.util.Collection findUnGrouped(java.sql.Date p0,java.sql.Date p1)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindUnGrouped(p0,p1); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public AccountEntry findByPrimaryKey(Object pk) throws javax.ejb.FinderException{ return (AccountEntry) super.findByPrimaryKeyIDO(pk); } public AccountEntry findByInvoiceNumber(int invoiceNumber) throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); Object pk = ((AccountEntryBMPBean)entity).ejbFindByInvoiceNumber(invoiceNumber); this.idoCheckInPooledEntity(entity); return this.findByPrimaryKey(pk); } public java.util.Collection findByBatchNumber(int batchNumber)throws javax.ejb.FinderException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((AccountEntryBMPBean)entity).ejbFindInvoicesByBatchNumber(batchNumber); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public int countByGroup(java.lang.Integer p0)throws com.idega.data.IDOException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); int theReturn = ((AccountEntryBMPBean)entity).ejbHomeCountByGroup(p0); this.idoCheckInPooledEntity(entity); return theReturn; } public java.sql.Date getMaxDateByAccount(java.lang.Integer p0)throws com.idega.data.IDOException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.sql.Date theReturn = ((AccountEntryBMPBean)entity).ejbHomeGetMaxDateByAccount(p0); this.idoCheckInPooledEntity(entity); return theReturn; } public double getTotalSumByAccount(java.lang.Integer p0)throws java.sql.SQLException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); double theReturn = ((AccountEntryBMPBean)entity).ejbHomeGetTotalSumByAccount(p0); this.idoCheckInPooledEntity(entity); return theReturn; } public double getTotalSumByAccount(java.lang.Integer p0,String roundStatus)throws java.sql.SQLException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); double theReturn = ((AccountEntryBMPBean)entity).ejbHomeGetTotalSumByAccount(p0,roundStatus); this.idoCheckInPooledEntity(entity); return theReturn; } public double getTotalSumByAccountAndAssessmentRound(java.lang.Integer p0,java.lang.Integer p1)throws java.sql.SQLException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); double theReturn = ((AccountEntryBMPBean)entity).ejbHomeGetTotalSumByAccountAndAssessmentRound(p0,p1); this.idoCheckInPooledEntity(entity); return theReturn; } public double getTotalSumByAssessmentRound(java.lang.Integer p0)throws java.sql.SQLException{ com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); double theReturn = ((AccountEntryBMPBean)entity).ejbHomeGetTotalSumByAssessmentRound(p0); this.idoCheckInPooledEntity(entity); return theReturn; } }
idega/com.idega.block.finance
src/java/com/idega/block/finance/data/AccountEntryHomeImpl.java
Java
gpl-3.0
4,957
/* Copyright (C) 2017-2022 Topological Manifold 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, see <http://www.gnu.org/licenses/>. */ #include "surface.h" #include "error.h" #include "extensions.h" #include <src/com/error.h> namespace ns::vulkan { namespace { std::uint32_t find_format_count(const VkPhysicalDevice physical_device, const VkSurfaceKHR surface) { std::uint32_t format_count; VULKAN_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &format_count, nullptr)); return format_count; } std::uint32_t find_present_mode_count(const VkPhysicalDevice physical_device, const VkSurfaceKHR surface) { std::uint32_t mode_count; VULKAN_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &mode_count, nullptr)); return mode_count; } std::vector<VkSurfaceFormatKHR> find_surface_formats(const VkPhysicalDevice physical_device, const VkSurfaceKHR surface) { std::uint32_t format_count = find_format_count(physical_device, surface); if (format_count < 1) { return {}; } std::vector<VkSurfaceFormatKHR> formats(format_count); VULKAN_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &format_count, formats.data())); return formats; } std::vector<VkPresentModeKHR> find_present_modes(const VkPhysicalDevice physical_device, const VkSurfaceKHR surface) { std::uint32_t mode_count = find_present_mode_count(physical_device, surface); if (mode_count < 1) { return {}; } std::vector<VkPresentModeKHR> modes(mode_count); VULKAN_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device, surface, &mode_count, modes.data())); return modes; } } bool find_surface_details( const VkSurfaceKHR surface, const VkPhysicalDevice device, VkSurfaceCapabilitiesKHR* const surface_capabilities, std::vector<VkSurfaceFormatKHR>* const surface_formats, std::vector<VkPresentModeKHR>* const present_modes) { ASSERT(surface_capabilities && surface_formats && present_modes); VULKAN_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, surface_capabilities)); *surface_formats = find_surface_formats(device, surface); if (surface_formats->empty()) { return false; } *present_modes = find_present_modes(device, surface); return !present_modes->empty(); } bool surface_suitable(const VkSurfaceKHR surface, const VkPhysicalDevice physical_device) { VkSurfaceCapabilitiesKHR surface_capabilities; std::vector<VkSurfaceFormatKHR> surface_formats; std::vector<VkPresentModeKHR> present_modes; return find_surface_details(surface, physical_device, &surface_capabilities, &surface_formats, &present_modes); } }
cppd/math
src/vulkan/surface.cpp
C++
gpl-3.0
3,445
/* * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.ac.ebi.rcloud.common.animation.transitions; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import javax.swing.JComponent; import uk.ac.ebi.rcloud.common.animation.timing.Animator; import uk.ac.ebi.rcloud.common.animation.transitions.*; import uk.ac.ebi.rcloud.common.animation.transitions.ComponentState; /** * This is the base class for all effects that are used during * screen transitions. * <p> * Subclasses of this base class may override the {@link #init(uk.ac.ebi.rcloud.common.animation.timing.Animator, uk.ac.ebi.rcloud.common.animation.transitions.Effect) * init()}, {@link #setup(java.awt.Graphics2D) setup()}, and {@link #paint(java.awt.Graphics2D) * paint()} methods to achieve the desired effect. * * @author Chet Haase */ public abstract class Effect { /** Information about the start state used by this effect. */ private uk.ac.ebi.rcloud.common.animation.transitions.ComponentState start; /** Information about the end state used by this effect. */ private ComponentState end; /** Flag to indicate whether effect needs to re-render Component */ private boolean renderComponent = false; /** * The image that will be used during the transition, for effects that * opt to not re-render the components directly. The image will be * set when the start and end states are set. */ private Image componentImage; /** Current x location. */ private int x; /** Current y location. */ private int y; /** Current width. */ private int width; /** Current height. */ private int height; // The bounds and location fields are used as utility objects to // be able to change the x/y and width/height fields from // single PropertySetter objects private Rectangle bounds = new Rectangle(); private Point location = new Point(); /** * Set the location and size of the component state being animated * by this effect */ public void setBounds(int x, int y, int width, int height) { this.bounds.x = this.location.x = this.x = x; this.bounds.y = this.location.y = this.y = y; setWidth(width); setHeight(height); } /** * Set the location and size of the component state being animated * by this effect */ public void setBounds(Rectangle bounds) { setBounds(bounds.x, bounds.y, bounds.width, bounds.height); } /** * Set the location of the component state being animated * by this effect */ public void setLocation(Point location) { this.location.x = this.bounds.x = this.x = location.x; this.location.y = this.bounds.y = this.y = location.y; } /** * Set the x location of the component state being animated * by this effect */ public void setX(int x) { this.location.x = this.bounds.x = this.x = x; } /** * Set the y location of the component state being animated * by this effect */ public void setY(int y) { this.location.y = this.bounds.y = this.y = y; } /** * Set the width of the component state being animated * by this effect */ public void setWidth(int width) { this.bounds.width = this.width = width; } /** * Set the height of the component state being animated * by this effect */ public void setHeight(int height) { this.bounds.height = this.height = height; } /** * Get the component being animated by this effect */ protected JComponent getComponent() { if (start != null) { return start.getComponent(); } else if (end != null) { return end.getComponent(); } // Should not get here return null; } /** * Initialize this effect. This method is called at transition start * time, to enable the effect to set up any necessary state prior * to the animation, such as animations that vary * properties of the Effect during the transition. * <p> * Subclasses of <code>Effect</code> will typically call * this superclass method if they override <code>init()</code>, as * many effects will depend on the state that is set up in this * method. */ public void init(Animator animator, Effect parentEffect) { bounds = new Rectangle(); if (start != null) { setBounds(start.getX(), start.getY(), start.getWidth(), start.getHeight()); } else { setBounds(end.getX(), end.getY(), end.getWidth(), end.getHeight()); } // If this effect already has a snapshot image of the // component, but it's not the size that we need, flush it now // and it will be created later during the first setup() call if (componentImage != null && ((start != null && (start.getWidth() != componentImage.getWidth(null))) || ((end != null && (end.getWidth() != componentImage.getWidth(null)))))) { componentImage.flush(); componentImage = null; } } /** * Effect subclasses that create temporary objects for the transition * (such as in the <code>init()</code> method) should override this * method and clean up those resources. For example, TimingTarget * e.g., PropertySetter) objects added to the animator used in the * transition should be removed afterwards to avoid leaking resources that * may otherwise be retained by those objects. */ public void cleanup(Animator animator) {} /** * Tells the Effect to re-render the component during the transition * instead of using an image representation of the component. This is * necessary for some animations which may change how a component * looks internally during the transition. For example, components that * are being scaled during a transition which contain text should probably * be redrawn rather than simply scaling an image, as scaling an image * of the text does not generally look the same as text rendered directly * at a particular size. * * @param renderComponent whether the component should be re-rendered * during the transition. If <code>true</code>, then the component will * be re-rendered during the animation. If <code>false</code>, the system * may choose to render an image representation of the component * instead. */ public void setRenderComponent(boolean renderComponent) { this.renderComponent = renderComponent; } /** * Returns whether the effect will re-render its component during * transitions, as opposed to using an image representation of it. * * @return boolean whether the effect will re-render the component * during the transition */ public boolean getRenderComponent() { return renderComponent; } /** * Sets both the start and end states of this Effect. */ public void setComponentStates(ComponentState start, ComponentState end) { this.start = start; this.end = end; } /** * Sets the start state of this Effect. */ public void setStart(ComponentState start) { this.start = start; } /** * Gets the start state of this Effect. */ public ComponentState getStart() { return start; } /** * Sets the end state of this Effect. */ public void setEnd(ComponentState end) { this.end = end; } /** * Gets the end state of this Effect. */ public ComponentState getEnd() { return end; } /** * Gets the image representation of this Effect. This is not intended * to be called by application code, but rather by custom effects or * other parts of the system. */ public Image getComponentImage() { return componentImage; } /** * Sets the image representation of this Effect. */ protected void setComponentImage(Image componentImage) { this.componentImage = componentImage; } /** * Creates and renders an image representation of the component. */ private void createComponentImage() { if (start != null && end == null) { componentImage = start.getSnapshot(); } else if (start == null && end != null) { componentImage = end.getSnapshot(); } else if (start.getWidth() != end.getWidth() || start.getHeight() != end.getHeight()) { // This block grabs the targetImage // that best represents the component; the larger the better. float widthFraction = (float)end.getWidth() / start.getWidth(); float heightFraction = (float)end.getHeight() / start.getHeight(); if (Math.abs(widthFraction - 1.0f) > Math.abs(heightFraction - 1.0f)) { // difference greater in width if (widthFraction < 1.0f) { // start size larger then end size componentImage = start.getSnapshot(); } else { componentImage = end.getSnapshot(); } } else { // different greater in height if (heightFraction < 1.0f) { // start size larger than end size componentImage = start.getSnapshot(); } else { componentImage = end.getSnapshot(); } } } else { componentImage = start.getSnapshot(); } } /** * This method is called during each frame of the transition animation, * prior to the call to {@link #paint(java.awt.Graphics2D) paint()}. * Subclasses will implement this method to set up the Graphic state, * or other related state, that will be used in the ensuing call to * the <code>paint()</code> method. Note that changes to the * <code>Graphics2D</code> object here will still be present in the * <code>Graphics2D</code> object that is passed into the * <code>paint()</code> method, so this is a good time to set up things * such as transform state that should be active during the rendering * calls. * <p> * Subclasses that override this method should call this superclass * method, because it may set up state used later during rendering. * * @param g2d the Graphics2D destination for this rendering */ public void setup(Graphics2D g2d) { if (!renderComponent && componentImage == null) { createComponentImage(); } } /** * This method is called during each frame of the transition animation, * after the call to {@link #setup(java.awt.Graphics2D) setup()}</code>. * Subclasses may override this method to perform whatever rendering * is necessary to paint the transitioning component into the * <code>Graphics2D</code> object with the desired effect. * <p> * Most subclasses may elect to not override the method, since this version * version of the method already handles the basic painting operation * of a component. * Only subclasses that need facilities beyond the basic drawing of * the component should consider overriding. * * @param g2d The Graphics2D destination for this rendering. Note that * the state of this Graphics2D object is affected by the previous call * to <code>setup()</code> so there may be no more need to perturb the * graphics state further. Functionality in this method should focus, * instead, on the rendering details instead of the graphics state. */ public void paint(Graphics2D g2d) { if (!renderComponent && (componentImage != null)) { g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(componentImage, 0, 0, width, height, null); } else { getComponent().setBounds(bounds); getComponent().validate(); ComponentState.paintSingleBuffered(getComponent(), g2d); } } /** * Called by EffectsManager on each effect during every frame of * the transition, this method calls setup() and paint(). */ void render(Graphics2D g2d) { // First, translate to where we need to render g2d.translate(location.x, location.y); // Now call setup and paint. Splitting rendering into these // two operations allows custom effects to have multiple // sub-effects combine their efforts into the Graphics2D // object prior to calling paint with that altered graphics // object. setup(g2d); paint(g2d); } }
andrewtikhonov/RCloud
rcloud-commons/src/main/java/uk/ac/ebi/rcloud/common/animation/transitions/Effect.java
Java
gpl-3.0
14,679
jsondtd ======= JSON DTD allows you to validate JSON and NoSQL documents for a given structure and type.
royallcompany/jsondtd
README.md
Markdown
gpl-3.0
106
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-commons. -- -- dromozoa-commons 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. -- -- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>. local string_matcher = require "dromozoa.commons.string_matcher" local unpack = require "dromozoa.commons.unpack" local function read_line(self, chomp) if not self:eof() then self:match("[^\n]*") local i = self.i local j = self.j if self:match("\n") then if not chomp then j = self.j end end return self.s:sub(i, j) end end local function read_number(self) local positon = self.positon self:match("%s*[%+%-]?") local i = self.i if self:match("0[xX]%x*") then self:match("%.%x*") self:match("[pP][%-%+]?%x+") elseif self:match("%d+") then self:match("%.%d*") self:match("[eE][%-%+]?%d+") elseif self:match("%.%d+") then self:match("[eE][%-%+]?%d+") else self.positon = position return nil end local v = tonumber(self.s:sub(i, self.position - 1)) if v == nil then self.positon = position return nil end return v end local function read(self, i, n, format, ...) if i < n then i = i + 1 local s = self.s local v local t = type(format) if t == "number" then if not self:eof() then local position = self.position + format v = self.s:sub(self.position, position - 1) self.position = position end elseif t ~= "string" then error("bad argument #" .. i + 1 .. " to 'write' (string expected, got " .. t .. ")") elseif format:find("^%*?n") then v = read_number(self) elseif format:find("^%*?a") then v = self.s:sub(self.position) self.position = #self.s + 1 elseif format:find("^%*?l") then v = read_line(self, true) elseif format:find("^%*?L") then v = read_line(self, false) end if v == nil then return else return v, read(self, i, n, ...) end else return end end local function lines(result, ...) if result == nil then return false else coroutine.yield(result, ...) return true end end local class = {} function class:read(...) local n = select("#", ...) if n == 0 then return read(self, 0, 1, "*l") else return read(self, 0, n, ...) end end function class:lines(...) local formats = {...} return coroutine.wrap(function () repeat until not lines(self:read(unpack(formats))) end) end function class:seek(whence, offset) if whence == nil then whence = "cur" end if offset == nil then offset = 0 end local pos if whence == "set" then pos = offset elseif whence == "cur" then pos = offset + self.position - 1 elseif whence == "end" then pos = offset + #self.s else error("bad argument #2 to 'seek' (invalid option '" .. whence .. "')") end if pos < 0 then return nil, "Invalid argument", 22 -- EINVAL end self.position = pos + 1 return pos end local metatable = { __index = class; } return setmetatable(class, { __index = string_matcher; __call = function (_, s) return setmetatable(class.new(s), metatable) end; })
ld-test/dromozoa-commons
dromozoa/commons/string_reader.lua
Lua
gpl-3.0
3,751
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace MilkShakeFramework.Tools.Maths { public class RotatedRectangle { public Rectangle CollisionRectangle; public float Rotation; public Vector2 Origin; public RotatedRectangle(int X, int Y, int Width, int Height) : this(new Rectangle(X, Y, Width, Height)) { } public RotatedRectangle(Rectangle theRectangle, float theInitialRotation = 0) { CollisionRectangle = theRectangle; Rotation = theInitialRotation; //Calculate the Rectangles origin. We assume the center of the Rectangle will //be the point that we will be rotating around and we use that for the origin Origin = new Vector2((int)theRectangle.Width / 2, (int)theRectangle.Height / 2); } /// <summary> /// Used for changing the X and Y position of the RotatedRectangle /// </summary> /// <param name="theXPositionAdjustment"></param> /// <param name="theYPositionAdjustment"></param> public void ChangePosition(int theXPositionAdjustment, int theYPositionAdjustment) { CollisionRectangle.X += theXPositionAdjustment; CollisionRectangle.Y += theYPositionAdjustment; } /// <summary> /// This intersects method can be used to check a standard XNA framework Rectangle /// object and see if it collides with a Rotated Rectangle object /// </summary> /// <param name="theRectangle"></param> /// <returns></returns> public bool Intersects(Rectangle theRectangle) { return Intersects(new RotatedRectangle(theRectangle, 0.0f)); } /// <summary> /// Check to see if two Rotated Rectangls have collided /// </summary> /// <param name="theRectangle"></param> /// <returns></returns> public bool Intersects(RotatedRectangle theRectangle) { //Calculate the Axis we will use to determine if a collision has occurred //Since the objects are rectangles, we only have to generate 4 Axis (2 for //each rectangle) since we know the other 2 on a rectangle are parallel. List<Vector2> aRectangleAxis = new List<Vector2>(); aRectangleAxis.Add(UpperRightCorner() - UpperLeftCorner()); aRectangleAxis.Add(UpperRightCorner() - LowerRightCorner()); aRectangleAxis.Add(theRectangle.UpperLeftCorner() - theRectangle.LowerLeftCorner()); aRectangleAxis.Add(theRectangle.UpperLeftCorner() - theRectangle.UpperRightCorner()); //Cycle through all of the Axis we need to check. If a collision does not occur //on ALL of the Axis, then a collision is NOT occurring. We can then exit out //immediately and notify the calling function that no collision was detected. If //a collision DOES occur on ALL of the Axis, then there is a collision occurring //between the rotated rectangles. We know this to be true by the Seperating Axis Theorem foreach (Vector2 aAxis in aRectangleAxis) { if (!IsAxisCollision(theRectangle, aAxis)) { return false; } } return true; } /// <summary> /// Determines if a collision has occurred on an Axis of one of the /// planes parallel to the Rectangle /// </summary> /// <param name="theRectangle"></param> /// <param name="aAxis"></param> /// <returns></returns> private bool IsAxisCollision(RotatedRectangle theRectangle, Vector2 aAxis) { //Project the corners of the Rectangle we are checking on to the Axis and //get a scalar value of that project we can then use for comparison List<int> aRectangleAScalars = new List<int>(); aRectangleAScalars.Add(GenerateScalar(theRectangle.UpperLeftCorner(), aAxis)); aRectangleAScalars.Add(GenerateScalar(theRectangle.UpperRightCorner(), aAxis)); aRectangleAScalars.Add(GenerateScalar(theRectangle.LowerLeftCorner(), aAxis)); aRectangleAScalars.Add(GenerateScalar(theRectangle.LowerRightCorner(), aAxis)); //Project the corners of the current Rectangle on to the Axis and //get a scalar value of that project we can then use for comparison List<int> aRectangleBScalars = new List<int>(); aRectangleBScalars.Add(GenerateScalar(UpperLeftCorner(), aAxis)); aRectangleBScalars.Add(GenerateScalar(UpperRightCorner(), aAxis)); aRectangleBScalars.Add(GenerateScalar(LowerLeftCorner(), aAxis)); aRectangleBScalars.Add(GenerateScalar(LowerRightCorner(), aAxis)); //Get the Maximum and Minium Scalar values for each of the Rectangles int aRectangleAMinimum = aRectangleAScalars.Min(); int aRectangleAMaximum = aRectangleAScalars.Max(); int aRectangleBMinimum = aRectangleBScalars.Min(); int aRectangleBMaximum = aRectangleBScalars.Max(); //If we have overlaps between the Rectangles (i.e. Min of B is less than Max of A) //then we are detecting a collision between the rectangles on this Axis if (aRectangleBMinimum <= aRectangleAMaximum && aRectangleBMaximum >= aRectangleAMaximum) { return true; } else if (aRectangleAMinimum <= aRectangleBMaximum && aRectangleAMaximum >= aRectangleBMaximum) { return true; } return false; } /// <summary> /// Generates a scalar value that can be used to compare where corners of /// a rectangle have been projected onto a particular axis. /// </summary> /// <param name="theRectangleCorner"></param> /// <param name="theAxis"></param> /// <returns></returns> private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis) { //Using the formula for Vector projection. Take the corner being passed in //and project it onto the given Axis float aNumerator = (theRectangleCorner.X * theAxis.X) + (theRectangleCorner.Y * theAxis.Y); float aDenominator = (theAxis.X * theAxis.X) + (theAxis.Y * theAxis.Y); float aDivisionResult = aNumerator / aDenominator; Vector2 aCornerProjected = new Vector2(aDivisionResult * theAxis.X, aDivisionResult * theAxis.Y); //Now that we have our projected Vector, calculate a scalar of that projection //that can be used to more easily do comparisons float aScalar = (theAxis.X * aCornerProjected.X) + (theAxis.Y * aCornerProjected.Y); return (int)aScalar; } /// <summary> /// Rotate a point from a given location and adjust using the Origin we /// are rotating around /// </summary> /// <param name="thePoint"></param> /// <param name="theOrigin"></param> /// <param name="theRotation"></param> /// <returns></returns> private Vector2 RotatePoint(Vector2 thePoint, Vector2 theOrigin, float theRotation) { Vector2 aTranslatedPoint = new Vector2(); aTranslatedPoint.X = (float)(theOrigin.X + (thePoint.X - theOrigin.X) * Math.Cos(theRotation) - (thePoint.Y - theOrigin.Y) * Math.Sin(theRotation)); aTranslatedPoint.Y = (float)(theOrigin.Y + (thePoint.Y - theOrigin.Y) * Math.Cos(theRotation) + (thePoint.X - theOrigin.X) * Math.Sin(theRotation)); return aTranslatedPoint; } public Vector2 UpperLeftCorner() { Vector2 aUpperLeft = new Vector2(CollisionRectangle.Left, CollisionRectangle.Top); aUpperLeft = RotatePoint(aUpperLeft, aUpperLeft + Origin, Rotation); return aUpperLeft; } public Vector2 UpperRightCorner() { Vector2 aUpperRight = new Vector2(CollisionRectangle.Right, CollisionRectangle.Top); aUpperRight = RotatePoint(aUpperRight, aUpperRight + new Vector2(-Origin.X, Origin.Y), Rotation); return aUpperRight; } public Vector2 LowerLeftCorner() { Vector2 aLowerLeft = new Vector2(CollisionRectangle.Left, CollisionRectangle.Bottom); aLowerLeft = RotatePoint(aLowerLeft, aLowerLeft + new Vector2(Origin.X, -Origin.Y), Rotation); return aLowerLeft; } public Vector2 LowerRightCorner() { Vector2 aLowerRight = new Vector2(CollisionRectangle.Right, CollisionRectangle.Bottom); aLowerRight = RotatePoint(aLowerRight, aLowerRight + new Vector2(-Origin.X, -Origin.Y), Rotation); return aLowerRight; } public int X { get { return CollisionRectangle.X; } } public int Y { get { return CollisionRectangle.Y; } } public int Width { get { return CollisionRectangle.Width; } } public int Height { get { return CollisionRectangle.Height; } } } }
lucas-jones/MilkShake-old
MilkShake/Tools/Maths/RotatedRectangle.cs
C#
gpl-3.0
9,486
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2011 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) return; /** * donne le chemin du fichier relatif a _DIR_IMG * pour stockage 'tel quel' dans la base de donnees * * http://doc.spip.org/@set_spip_doc * * @param string $fichier * @return string */ function set_spip_doc($fichier) { if (strpos($fichier, _DIR_IMG) === 0) return substr($fichier, strlen(_DIR_IMG)); else return $fichier; // ex: fichier distant } /** * donne le chemin complet du fichier * * http://doc.spip.org/@get_spip_doc * * @param string $fichier * @return bool|string */ function get_spip_doc($fichier) { // fichier distant if (preg_match(',^\w+://,', $fichier)) return $fichier; // gestion d'erreurs, fichier='' if (!strlen($fichier)) return false; $fichier = ( strncmp($fichier,_DIR_IMG, strlen(_DIR_IMG))!=0 ) ? _DIR_IMG . $fichier : $fichier ; // fichier normal return $fichier; } /** * Creer IMG/pdf/ * * http://doc.spip.org/@creer_repertoire_documents * * @param $ext * @return string */ function creer_repertoire_documents($ext) { $rep = sous_repertoire(_DIR_IMG, $ext); if (!$ext OR !$rep) { spip_log("creer_repertoire_documents '$rep' interdit"); exit; } // Cette variable de configuration peut etre posee par un plugin // par exemple acces_restreint if ($GLOBALS['meta']["creer_htaccess"] == 'oui') { include_spip('inc/acces'); verifier_htaccess($rep); } return $rep; } /** * Efface le repertoire de maniere recursive ! * * http://doc.spip.org/@effacer_repertoire_temporaire * * @param string $nom */ function effacer_repertoire_temporaire($nom) { $d = opendir($nom); while (($f = readdir($d)) !== false) { if (is_file("$nom/$f")) spip_unlink("$nom/$f"); else if ($f <> '.' AND $f <> '..' AND is_dir("$nom/$f")) effacer_repertoire_temporaire("$nom/$f"); } closedir($d); @rmdir($nom); } // /** * Copier un document $source un dossier IMG/$ext/$orig.$ext * en numerotant eventuellement si un du meme nom existe deja * * http://doc.spip.org/@copier_document * * @param string $ext * @param string $orig * @param string $source * @return bool|mixed|string */ function copier_document($ext, $orig, $source) { $orig = preg_replace(',\.\.+,', '.', $orig); // pas de .. dans le nom du doc $dir = creer_repertoire_documents($ext); $dest = preg_replace("/[^._=-\w\d]+/", "_", translitteration(preg_replace("/\.([^.]+)$/", "", preg_replace("/<[^>]*>/", '', basename($orig))))); // ne pas accepter de noms de la forme -r90.jpg qui sont reserves // pour les images transformees par rotation (action/documenter) $dest = preg_replace(',-r(90|180|270)$,', '', $dest); // Si le document "source" est deja au bon endroit, ne rien faire if ($source == ($dir . $dest . '.' . $ext)) return $source; // sinon tourner jusqu'a trouver un numero correct $n = 0; while (@file_exists($newFile = $dir . $dest .($n++ ? ('-'.$n) : '').'.'.$ext)); return deplacer_fichier_upload($source, $newFile); } /** * Trouver le dossier utilise pour upload un fichier * * http://doc.spip.org/@determine_upload * * @param string $type * @return bool|string */ function determine_upload($type='') { if(!function_exists('autoriser')) include_spip('inc/autoriser'); if (!autoriser('chargerftp') OR $type == 'logos') # on ne le permet pas pour les logos return false; $repertoire = _DIR_TRANSFERT; if (!@is_dir($repertoire)) { $repertoire = str_replace(_DIR_TMP, '', $repertoire); $repertoire = sous_repertoire(_DIR_TMP, $repertoire); } if (!$GLOBALS['visiteur_session']['restreint']) return $repertoire; else return sous_repertoire($repertoire, $GLOBALS['visiteur_session']['login']); } /** * Deplacer ou copier un fichier * * http://doc.spip.org/@deplacer_fichier_upload * * @param string $source * @param string $dest * @param bool $move * @return bool|mixed|string */ function deplacer_fichier_upload($source, $dest, $move=false) { // Securite if (substr($dest,0,strlen(_DIR_RACINE))==_DIR_RACINE) $dest = _DIR_RACINE.preg_replace(',\.\.+,', '.', substr($dest,strlen(_DIR_RACINE))); else $dest = preg_replace(',\.\.+,', '.', $dest); if ($move) $ok = @rename($source, $dest); else $ok = @copy($source, $dest); if (!$ok) $ok = @move_uploaded_file($source, $dest); if ($ok) @chmod($dest, _SPIP_CHMOD & ~0111); else { $f = @fopen($dest,'w'); if ($f) { fclose ($f); } else { include_spip('inc/flock'); raler_fichier($dest); } spip_unlink($dest); } return $ok ? $dest : false; } // Erreurs d'upload // renvoie false si pas d'erreur // et true si erreur = pas de fichier // pour les autres erreurs affiche le message d'erreur et meurt // http://doc.spip.org/@check_upload_error function check_upload_error($error, $msg='') { global $spip_lang_right; if (!$error) return false; spip_log("Erreur upload $error -- cf. http://php.net/manual/fr/features.file-upload.errors.php"); switch ($error) { case 4: /* UPLOAD_ERR_NO_FILE */ return true; # on peut affiner les differents messages d'erreur case 1: /* UPLOAD_ERR_INI_SIZE */ $msg = _T('upload_limit', array('max' => ini_get('upload_max_filesize'))); break; case 2: /* UPLOAD_ERR_FORM_SIZE */ $msg = _T('upload_limit', array('max' => ini_get('upload_max_filesize'))); break; case 3: /* UPLOAD_ERR_PARTIAL */ $msg = _T('upload_limit', array('max' => ini_get('upload_max_filesize'))); break; default: /* autre */ if (!$msg) $msg = _T('pass_erreur').' '. $error . '<br />' . propre("[->http://php.net/manual/fr/features.file-upload.errors.php]"); break; } spip_log ("erreur upload $error"); if(_request("iframe")=="iframe") { echo "<div class='upload_answer upload_error'>$msg</div>"; exit; } echo minipres($msg, "<div style='text-align: $spip_lang_right'><a href='" . rawurldecode($GLOBALS['redirect']) . "'><button type='button'>" . _T('ecrire:bouton_suivant') . "</button></a></div>"); exit; } ?>
denisbz/SPIP
ecrire/inc/documents.php
PHP
gpl-3.0
6,683
<html> <head> <title>Docs for page Exception.php</title> <link rel="stylesheet" type="text/css" href="../media/style.css"> <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/> </head> <body> <table border="0" cellspacing="0" cellpadding="0" height="48" width="100%"> <tr> <td class="header_top">Marvel</td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> <tr> <td class="header_menu"> [ <a href="../classtrees_Marvel.html" class="menu">class tree: Marvel</a> ] [ <a href="../elementindex_Marvel.html" class="menu">index: Marvel</a> ] [ <a href="../elementindex.html" class="menu">all elements</a> ] </td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="200" class="menu"> <div id="todolist"> <p><a href="../todolist.html">Todo List</a></p> </div> <b>Packages:</b><br /> <a href="../li_Marvel.html">Marvel</a><br /> <br /><br /> <b>Files:</b><br /> <div class="package"> <a href="../Marvel/_abstractes---aDatabase.php.html"> aDatabase.php </a><br> <a href="../Marvel/_abstractes---aDatabaseDriver.php.html"> aDatabaseDriver.php </a><br> <a href="../Marvel/_abstractes---aIterator.php.html"> aIterator.php </a><br> <a href="../Marvel/_abstractes---aModel.php.html"> aModel.php </a><br> <a href="../Marvel/_core---Application.php.html"> Application.php </a><br> <a href="../Marvel/_datahandler---ArrayData.php.html"> ArrayData.php </a><br> <a href="../Marvel/_abstractes---aSingleton.php.html"> aSingleton.php </a><br> <a href="../Marvel/_iterators---AssoziativArrayIterator.php.html"> AssoziativArrayIterator.php </a><br> <a href="../Marvel/_datahandler---Data.php.html"> Data.php </a><br> <a href="../Marvel/_database---mysql---database.php.html"> database.php </a><br> <a href="../Marvel/_core---DataRegistry.php.html"> DataRegistry.php </a><br> <a href="../Marvel/_database---DbQuery.php.html"> DbQuery.php </a><br> <a href="../Marvel/_database---mysql---driver.php.html"> driver.php </a><br> <a href="../Marvel/_core---Exception.php.html"> Exception.php </a><br> <a href="../Marvel/_interfaces---iArrayData.php.html"> iArrayData.php </a><br> <a href="../Marvel/_interfaces---iData.php.html"> iData.php </a><br> <a href="../Marvel/_interfaces---iIterator.php.html"> iIterator.php </a><br> <a href="../Marvel/_interfaces---iRegistry.php.html"> iRegistry.php </a><br> <a href="../Marvel/_interfaces---iSingleton.php.html"> iSingleton.php </a><br> <a href="../Marvel/_Marvel.php.html"> Marvel.php </a><br> <a href="../Marvel/_core---Model.php.html"> Model.php </a><br> <a href="../Marvel/_package---Package.php.html"> Package.php </a><br> <a href="../Marvel/_datahandler---PackageData.php.html"> PackageData.php </a><br> <a href="../Marvel/_core---Router.php.html"> Router.php </a><br> </div><br /> <b>Interfaces:</b><br /> <div class="package"> <a href="../Marvel/iArrayData.html">iArrayData</a><br /> <a href="../Marvel/iData.html">iData</a><br /> <a href="../Marvel/iIterator.html">iIterator</a><br /> <a href="../Marvel/iRegistry.html">iRegistry</a><br /> <a href="../Marvel/iSingleton.html">iSingleton</a><br /> </div> <b>Classes:</b><br /> <div class="package"> <a href="../Marvel/aDatabase.html">aDatabase</a><br /> <a href="../Marvel/aDatabaseDriver.html">aDatabaseDriver</a><br /> <a href="../Marvel/aIterator.html">aIterator</a><br /> <a href="../Marvel/aModel.html">aModel</a><br /> <a href="../Marvel/Application.html">Application</a><br /> <a href="../Marvel/ArrayData.html">ArrayData</a><br /> <a href="../Marvel/aSingleton.html">aSingleton</a><br /> <a href="../Marvel/AssoziativArrayIterator.html">AssoziativArrayIterator</a><br /> <a href="../Marvel/Data.html">Data</a><br /> <a href="../Marvel/database.html">database</a><br /> <a href="../Marvel/DataRegistry.html">DataRegistry</a><br /> <a href="../Marvel/dbQuery.html">dbQuery</a><br /> <a href="../Marvel/driver.html">driver</a><br /> <a href="../Marvel/Exception.html">Exception</a><br /> <a href="../Marvel/Marvel.html">Marvel</a><br /> <a href="../Marvel/Model.html">Model</a><br /> <a href="../Marvel/Package.html">Package</a><br /> <a href="../Marvel/PackageData.html">PackageData</a><br /> <a href="../Marvel/Router.html">Router</a><br /> </div> </td> <td> <table cellpadding="10" cellspacing="0" width="100%" border="0"><tr><td valign="top"> <h1>Procedural File: Exception.php</h1> Source Location: /core/Exception.php<br /><br /> <br> <br> <div class="contents"> <h2>Classes:</h2> <dt><a href="../Marvel/Exception.html">Exception</a></dt> <dd>Exception-class.</dd> </div><br /><br /> <h2>Page Details:</h2> <br /><br /> <br /><br /> <br /><br /> <br /> <div class="credit"> <hr /> Documentation generated on Sun, 25 Nov 2012 13:27:42 +0100 by <a href="http://www.phpdoc.org">phpDocumentor 1.4.3</a> </div> </td></tr></table> </td> </tr> </table> </body> </html>
Benni225/marvel
doc/Marvel/_core---Exception.php.html
HTML
gpl-3.0
5,644
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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, see <http://www.gnu.org/licenses/>. */ /* $Id:$ */ package com.aurel.track.fieldType.runtime.renderer; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.aurel.track.beans.ILabelBean; import com.aurel.track.beans.TFieldBean; import com.aurel.track.beans.TFieldConfigBean; import com.aurel.track.fieldType.constants.BooleanFields; import com.aurel.track.fieldType.runtime.base.WorkItemContext; import com.aurel.track.fieldType.runtime.helpers.MergeUtil; import com.aurel.track.json.JSONUtility; import com.aurel.track.util.IntegerStringBean; /** * * A renderer for combo at designTime * */ public class SelectRendererRT extends AbstractTypeRendererRT { //singleton isntance private static SelectRendererRT instance; /** * get a singleton instance * @return singleton instance */ public static SelectRendererRT getInstance() { if (instance == null) { instance = new SelectRendererRT(); } return instance; } /** * constructor */ public SelectRendererRT() { } @Override public String getExtClassName(){ return "com.aurel.trackplus.field.SelectTypeRenderer"; } @Override public String encodeJsonValue(Object value){ return value==null?null:value.toString(); } @Override public Object decodeJsonValue(String value, Integer fieldID, WorkItemContext workItemContext) throws TypeConversionException{ Integer result=null; if(value!=null){ try{ result=Integer.decode(value); }catch (NumberFormatException ex){ throw new TypeConversionException("common.err.invalid.number",ex); } } return result; } @Override public String createJsonData(TFieldBean field, WorkItemContext workItemContext){ return createJsonData(field,null,workItemContext); } @Override public String createJsonData(TFieldBean field,Integer parameterCode, WorkItemContext workItemContext){ StringBuilder sb=new StringBuilder(); sb.append("{"); if(parameterCode!=null){ //cascade select sb.append("\"forceSelection\"").append(":true,"); } List<ILabelBean> possibleValues=workItemContext.getDropDownContainer().getDataSourceList(MergeUtil.mergeKey(field.getObjectID(), parameterCode)); sb.append("\"list\"").append(":"); String listJSON=encodeOptions(possibleValues); sb.append(listJSON); sb.append("}"); return sb.toString(); } protected String encodeOptions(List<ILabelBean> possibleValues){ return JSONUtility.encodeILabelBeanList(possibleValues); } }
trackplus/Genji
src/main/java/com/aurel/track/fieldType/runtime/renderer/SelectRendererRT.java
Java
gpl-3.0
3,242
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "toolbox.h" #include <QToolBar> #include <QHBoxLayout> #include <QVBoxLayout> #include <QDebug> #include <QFrame> namespace QmlDesigner { ToolBox::ToolBox(QWidget *parentWidget) : Utils::StyledBar(parentWidget), m_leftToolBar(new QToolBar(QLatin1String("LeftSidebar"), this)), m_rightToolBar(new QToolBar(QLatin1String("RightSidebar"), this)) { m_leftToolBar->setFloatable(true); m_leftToolBar->setMovable(true); m_leftToolBar->setOrientation(Qt::Horizontal); auto horizontalLayout = new QHBoxLayout(this); horizontalLayout->setMargin(0); horizontalLayout->setSpacing(0); auto stretchToolbar = new QToolBar(this); m_leftToolBar->setProperty("panelwidget", true); m_leftToolBar->setProperty("panelwidget_singlerow", false); m_rightToolBar->setProperty("panelwidget", true); m_rightToolBar->setProperty("panelwidget_singlerow", false); stretchToolbar->setProperty("panelwidget", true); stretchToolbar->setProperty("panelwidget_singlerow", false); stretchToolbar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_rightToolBar->setOrientation(Qt::Horizontal); horizontalLayout->addWidget(m_leftToolBar); horizontalLayout->addWidget(stretchToolbar); horizontalLayout->addWidget(m_rightToolBar); } void ToolBox::setLeftSideActions(const QList<QAction*> &actions) { m_leftToolBar->clear(); m_leftToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::setRightSideActions(const QList<QAction*> &actions) { m_rightToolBar->clear(); m_rightToolBar->addActions(actions); resize(sizeHint()); } void ToolBox::addLeftSideAction(QAction *action) { m_leftToolBar->addAction(action); } void ToolBox::addRightSideAction(QAction *action) { m_rightToolBar->addAction(action); } QList<QAction*> ToolBox::actions() const { return m_leftToolBar->actions() + m_rightToolBar->actions(); } } // namespace QmlDesigner
sailfish-sdk/sailfish-qtcreator
src/plugins/qmldesigner/components/formeditor/toolbox.cpp
C++
gpl-3.0
3,167
<?php namespace TYPO3\Flow\Tests\Unit\Security\Authentication\Token; /* * This file is part of the TYPO3.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Http\Request; use TYPO3\Flow\Mvc\ActionRequest; use TYPO3\Flow\Security\Authentication\TokenInterface; use TYPO3\Flow\Security\Authentication\Token\UsernamePassword; use TYPO3\Flow\Tests\UnitTestCase; /** * Testcase for username/password authentication token * */ class UsernamePasswordTest extends UnitTestCase { /** * @var UsernamePassword */ protected $token; /** * @var ActionRequest|\PHPUnit_Framework_MockObject_MockObject */ protected $mockActionRequest; /** * @var Request|\PHPUnit_Framework_MockObject_MockObject */ protected $mockHttpRequest; /** * Set up this test case */ public function setUp() { $this->token = new UsernamePassword(); $this->mockActionRequest = $this->getMockBuilder(ActionRequest::class)->disableOriginalConstructor()->getMock(); $this->mockHttpRequest = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock(); $this->mockActionRequest->expects($this->any())->method('getHttpRequest')->will($this->returnValue($this->mockHttpRequest)); } /** * @test */ public function credentialsAreSetCorrectlyFromPostArguments() { $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = 'johndoe'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = 'verysecurepassword'; $this->mockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('POST')); $this->mockActionRequest->expects($this->atLeastOnce())->method('getInternalArguments')->will($this->returnValue($arguments)); $this->token->updateCredentials($this->mockActionRequest); $expectedCredentials = ['username' => 'johndoe', 'password' => 'verysecurepassword']; $this->assertEquals($expectedCredentials, $this->token->getCredentials(), 'The credentials have not been extracted correctly from the POST arguments'); } /** * @test */ public function updateCredentialsSetsTheCorrectAuthenticationStatusIfNewCredentialsArrived() { $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = 'TYPO3.Flow'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = 'verysecurepassword'; $this->mockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('POST')); $this->mockActionRequest->expects($this->atLeastOnce())->method('getInternalArguments')->will($this->returnValue($arguments)); $this->token->updateCredentials($this->mockActionRequest); $this->assertSame(TokenInterface::AUTHENTICATION_NEEDED, $this->token->getAuthenticationStatus()); } /** * @test */ public function updateCredentialsIgnoresAnythingOtherThanPostRequests() { $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = 'TYPO3.Flow'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = 'verysecurepassword'; $this->mockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('POST')); $this->mockActionRequest->expects($this->atLeastOnce())->method('getInternalArguments')->will($this->returnValue($arguments)); $this->token->updateCredentials($this->mockActionRequest); $this->assertEquals(['username' => 'TYPO3.Flow', 'password' => 'verysecurepassword'], $this->token->getCredentials()); $secondToken = new UsernamePassword(); $secondMockActionRequest = $this->getMockBuilder(ActionRequest::class)->disableOriginalConstructor()->getMock(); /** @var ActionRequest|\PHPUnit_Framework_MockObject_MockObject $secondMockActionRequest */ $secondMockHttpRequest = $this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock(); $secondMockActionRequest->expects($this->any())->method('getHttpRequest')->will($this->returnValue($secondMockHttpRequest)); $secondMockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('GET')); $secondToken->updateCredentials($secondMockActionRequest); $this->assertEquals(['username' => '', 'password' => ''], $secondToken->getCredentials()); } /** * @test */ public function tokenCanBeCastToString() { $arguments = []; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['username'] = 'TYPO3.Flow'; $arguments['__authentication']['TYPO3']['Flow']['Security']['Authentication']['Token']['UsernamePassword']['password'] = 'verysecurepassword'; $this->mockHttpRequest->expects($this->atLeastOnce())->method('getMethod')->will($this->returnValue('POST')); $this->mockActionRequest->expects($this->atLeastOnce())->method('getInternalArguments')->will($this->returnValue($arguments)); $this->token->updateCredentials($this->mockActionRequest); $this->assertEquals('Username: "TYPO3.Flow"', (string)$this->token); } }
MoritzVonWirth/Project-Eagle
Packages/Framework/TYPO3.Flow/Tests/Unit/Security/Authentication/Token/UsernamePasswordTest.php
PHP
gpl-3.0
5,867
/* * Copyright 2011-2021 Fraunhofer ISE * * This file is part of OpenMUC. * For more information visit http://www.openmuc.org * * OpenMUC 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. * * OpenMUC 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 OpenMUC. If not, see <http://www.gnu.org/licenses/>. * */ package org.openmuc.framework.lib.mqtt; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; import com.hivemq.client.mqtt.mqtt3.message.subscribe.Mqtt3Subscribe; import com.hivemq.client.mqtt.mqtt3.message.subscribe.Mqtt3SubscribeBuilder; import com.hivemq.client.mqtt.mqtt3.message.subscribe.Mqtt3Subscription; public class MqttReader { private static final Logger logger = LoggerFactory.getLogger(MqttReader.class); private final MqttConnection connection; private boolean connected = false; private final List<SubscribeListenerTuple> subscribes = new LinkedList<>(); private final String pid; /** * Note that the connect method of the connection should be called after the Writer got instantiated. * * @param connection * the {@link MqttConnection} this Writer should use * @param pid * an id which is preceding every log call */ public MqttReader(MqttConnection connection, String pid) { this.connection = connection; this.pid = pid; addConnectedListener(connection); addDisconnectedListener(connection); } private void addDisconnectedListener(MqttConnection connection) { connection.addDisconnectedListener(context -> { if (context.getReconnector().isReconnect()) { if (connected) { warn("Disconnected! {}", context.getCause().getMessage()); } else { warn("Reconnect failed! Reason: {}", context.getCause().getMessage()); } connected = false; } }); } private void addConnectedListener(MqttConnection connection) { connection.addConnectedListener(context -> { for (SubscribeListenerTuple tuple : subscribes) { subscribe(tuple.subscribe, tuple.listener); } connected = true; log("Connected to {}:{}", context.getClientConfig().getServerHost(), context.getClientConfig().getServerPort()); }); } /** * Listens on all topics and notifies the listener when a new message on one of the topics comes in * * @param topics * List with topic string to listen on * @param listener * listener which gets notified of new messages coming in */ public void listen(List<String> topics, MqttMessageListener listener) { Mqtt3Subscribe subscribe = buildSubscribe(topics); if (subscribe == null) { error("No topic given to listen on"); return; } if (connected) { subscribe(subscribe, listener); } subscribes.add(new SubscribeListenerTuple(subscribe, listener)); } private void subscribe(Mqtt3Subscribe subscribe, MqttMessageListener listener) { this.connection.getClient().subscribe(subscribe, mqtt3Publish -> { listener.newMessage(mqtt3Publish.getTopic().toString(), mqtt3Publish.getPayloadAsBytes()); if (logger.isTraceEnabled()) { trace("Message on topic {} received, payload: {}", mqtt3Publish.getTopic().toString(), new String(mqtt3Publish.getPayloadAsBytes())); } }); } private Mqtt3Subscribe buildSubscribe(List<String> topics) { Mqtt3SubscribeBuilder subscribeBuilder = Mqtt3Subscribe.builder(); Mqtt3Subscribe subscribe = null; for (String topic : topics) { Mqtt3Subscription subscription = Mqtt3Subscription.builder().topicFilter(topic).build(); // last topic, build the subscribe object if (topics.get(topics.size() - 1).equals(topic)) { subscribe = subscribeBuilder.addSubscription(subscription).build(); break; } subscribeBuilder.addSubscription(subscription); } return subscribe; } private static class SubscribeListenerTuple { private final Mqtt3Subscribe subscribe; private final MqttMessageListener listener; private SubscribeListenerTuple(Mqtt3Subscribe subscribe, MqttMessageListener listener) { this.subscribe = subscribe; this.listener = listener; } } private void log(String message, Object... args) { message = MessageFormatter.arrayFormat(message, args).getMessage(); logger.info("[{}] {}", pid, message); } private void debug(String message, Object... args) { message = MessageFormatter.arrayFormat(message, args).getMessage(); logger.debug("[{}] {}", pid, message); } private void warn(String message, Object... args) { message = MessageFormatter.arrayFormat(message, args).getMessage(); logger.warn("[{}] {}", pid, message); } private void error(String message, Object... args) { message = MessageFormatter.arrayFormat(message, args).getMessage(); logger.error("[{}] {}", pid, message); } private void trace(String message, Object... args) { message = MessageFormatter.arrayFormat(message, args).getMessage(); logger.trace("[{}] {}", pid, message); } }
isc-konstanz/OpenMUC
projects/lib/mqtt/src/main/java/org/openmuc/framework/lib/mqtt/MqttReader.java
Java
gpl-3.0
6,129
""" WSGI config for mng_files project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os import sys path = os.path.abspath(__file__+'/../..') if path not in sys.path: sys.path.append(path) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mng_files.settings") application = get_wsgi_application()
idjung96/mng_files
mng_files/wsgi.py
Python
gpl-3.0
498
package com.bluepowermod.network; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.NetworkRegistry; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public abstract class LocatedPacketDouble<T extends LocatedPacket<T>> extends Packet<T> { protected BlockPos pos; public LocatedPacketDouble(BlockPos location) { this.pos = location; } public LocatedPacketDouble(double x, double y, double z) { this.pos = new BlockPos(x,y,z); } public LocatedPacketDouble() { } @Override public void read(DataInput buffer) throws IOException { pos = new BlockPos(buffer.readDouble(), buffer.readDouble(), buffer.readDouble()); } @Override public void write(DataOutput buffer) throws IOException { buffer.writeDouble(pos.getX()); buffer.writeDouble(pos.getY()); buffer.writeDouble(pos.getZ()); } public NetworkRegistry.TargetPoint getTargetPoint(World world) { return getTargetPoint(world, 64); } public NetworkRegistry.TargetPoint getTargetPoint(World world, double updateDistance) { return new NetworkRegistry.TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), updateDistance); } }
MoreThanHidden/BluePower
src/main/java/com/bluepowermod/network/LocatedPacketDouble.java
Java
gpl-3.0
1,346
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <link rel="canonical" href="https://www.rakuten.ne.jp/gold/shopjapan/cp/outlet/pc_b.html" /> <title>MAX60%OFF๏ผ๏ฝœใ‚ทใƒงใƒƒใƒ—ใ‚ธใƒฃใƒ‘ใƒณๆฅฝๅคฉๅธ‚ๅ ดๅบ—</title> <!-- ๆฅฝๅคฉTOP่งฃๆžใ‚ฟใ‚ฐ --> <script src="//assets.adobedtm.com/fde17e0362c40547334f4e041add368f158b4119/satelliteLib-e346cd8edc0ac640d3ce7c060b5a38f5169d4add.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script src="https://www.rakuten.ne.jp/gold/shopjapan/trs/iframe/matome/semantic.min.js"></script> <script src="js/smoothscroll.js"></script> <link rel="stylesheet" href="css/semantic.min.css"> <link rel="stylesheet" href="http://www.rakuten.ne.jp/gold/shopjapan/css/normalize.css"> <link rel="stylesheet" href="css/sp_common.css"> <link rel="stylesheet" href="css/slick.css"> <link rel="stylesheet" href="css/lightbox.css"> <link rel="SHORTCUT ICON" href="https://www.rakuten.ne.jp/gold/shopjapan/images/favicon.ico"> <script type="text/javascript"> $(document).ready(function() { //modal็”จHTMLใ‚’่ชญใฟ่พผใฟ $('#target').load('modal_sp.html');//temp disable }); //click modal $('.modal-not-migration').on('click',function(){ $('#modal-not-migration').modal('show'); }); $('#allform').submit(function(event) { // ใ“ใ“ใงsubmitใ‚’ใ‚ญใƒฃใƒณใ‚ปใƒซใ—ใพใ™ใ€‚ event.preventDefault(); }); // # link ็„กๅŠน $(function() { // ใ‚ฏใƒฉใ‚นๅใ‹ใ‚‰Modalๅ†…IDใซๅค‰ๆ› // $('a[href="#"].modal-cero').click(function() { $('a[href="#"]').click(function(e) { var modalId=e.target.className.split( ' ' ); if(modalId.lastIndexOf('modal')){ // $('#modal-cero').modal('show'); $('#'+modalId[0]).modal('show'); return false; } }) }); // # link ็„กๅŠน $(function() { $('a[href="#"].modal-not-migration').click(function() { $('#modal-not-migration').modal('show'); return false; }) }); </script> <!--<script> if (!(navigator.userAgent.indexOf('iPhone') > 0 || navigator.userAgent.indexOf('Windows Phone') > 0 || navigator.userAgent.indexOf('Android') > 0 && navigator.userAgent.indexOf('Mobile'))){ location.href = 'https://www.rakuten.ne.jp/gold/shopjapan/cp/outlet/pc_b.html'; } </script>--> </head> <!--ๆฅฝๅคฉ่งฃๆžใ‚ฟใ‚ฐ--> <script type="text/javascript">_satellite.pageBottom();</script> <body> <div class="outlet_sp_wrap" id="top"> <div class="main_bnr"><img src="img/sp/kvsp1.jpg"></div><br> <div style="width: 95%;margin: 0 auto;"> <a href="https://coupon.rakuten.co.jp/getCoupon?getkey=T1lMRi01VU1ZLVJMWlotRTEyVA--&rt="><img src="img/sp/cou_1000_sp.jpg" width="100%"></a></div><br> <ul class="item_lineup" style="margin:-10px auto;"> <!-------------------------------- bgv ---------------------------------> <li id="bgv" class="item_id"> <img src="img/sp/sai29_sp.png" class="baku" style="width:28%;position: absolute;z-index: 9;top:-2%;left:-1%;"> <img src="img/sp/bgv_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/bgv.jpg" rel="lightbox[bgv-group]"><img src="img/sp/bgv.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/bgv/s_cm1_1.jpg" rel="lightbox[bgv-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/bgv/s_cm1_1.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/bgv/s_cm2_1.jpg" rel="lightbox[bgv-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/bgv/s_cm2_1.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/bgv_s_sp.jpg" style="width:92%;margin:0 auto;"> <img src="img/sp/bgv_t_sp.jpg" style="width:92%;margin:0 auto;"> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <select name="item_id" class="select_btn"> <option value="10003955">ๆ–ฐๅ“ๅŒๆง˜</option> <option value="10003956">็‰นไพก่‰ฏๅ“</option> </select> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003955"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-bgv sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- bgv ---------------------------------> <!-------------------------------- mgt ---------------------------------> <li id="mgt" class="item_id"> <img src="img/sp/sai39_sp.png" class="baku" style="width:28%;position: absolute;z-index: 9;top:-2%;left:-1%;"> <img src="img/sp/mgt1_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/mgt.jpg" rel="lightbox[mgt-group]"><img src="img/sp/mgt.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/mgt/mgt_05.jpg" rel="lightbox[mgt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/mgt/mgt_05.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/mgt/mgt_04.jpg" rel="lightbox[mgt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/mgt/mgt_04.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/mgt_s_sp.jpg" style="width:92%;margin:0 auto;"> <img src="img/sp/mgt_t_sp.jpg" style="width:92%;margin:0 auto;"> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <select name="item_id" class="select_btn"> <option value="10003953">ๆ–ฐๅ“ๅŒๆง˜</option> <option value="10003954">็‰นไพก่‰ฏๅ“</option> </select> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003953"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-mgt sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- mgt ---------------------------------> <!-------------------------------- nice ---------------------------------> <li id="nice" class="item_id"> <img src="img/sp/nice_bak.png" style="width:28%;position: absolute;z-index: 9;top:-2.2%;left:-1%;"> <img src="img/sp/nice_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/nice_2.jpg" rel="lightbox[nice-group]"><img src="img/sp/nice_2.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/nice/s_0210_4.jpg" rel="lightbox[nice-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/nice/s_0210_4.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/nice_s_sp.jpg" style="width:92%;margin:0 auto;"> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <select name="inventory_id" class="select_btn"> <option value="8864">ใƒฌใƒƒใƒ‰</option> <option value="8865">ใƒ–ใƒฉใƒƒใ‚ฏ</option> </select> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003922"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-nice sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- nice ---------------------------------> <!-------------------------------- rvt ---------------------------------> <li id="rvt" class="item_id"> <img src="img/sp/rvt_baku.png" class="baku" style="width:28%;position: absolute;z-index: 9;top:-2%;left:-1%;"> <img src="img/sp/rvt1_ttl.jpg" style="width:92%;margin:4% auto 0;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/rvt_2.jpg" rel="lightbox[rvt-group]"><img src="img/sp/rvt_2.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_400x400.jpg" rel="lightbox[rvt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_400x400.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_2.jpg" rel="lightbox[rvt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_2.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_3.jpg" rel="lightbox[rvt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_3.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_4.jpg" rel="lightbox[rvt-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/rvt/rvt_4.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/rvt_s_sp.jpg" style="width:92%;margin:0 auto;"> <img src="img/sp/rvt_t_sp.jpg" style="width:92%;margin:0 auto;"> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <select name="item_id" class="select_btn"> <option value="10003929">ๆ–ฐๅ“ๅŒๆง˜</option> <option value="10003930">็‰นไพก่‰ฏๅ“</option> </select> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003929"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-rvt sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- rvt ---------------------------------> <!-------------------------------- ngw ---------------------------------> <li id="ngw" class="item_id"> <img src="img/sp/51_sp.png" style="width:28%;position: absolute;z-index: 9;top:-2%;left:-1%;"> <img src="img/sp/ngw_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/ngw_2.jpg" rel="lightbox[ngw-group]"><img src="img/sp/ngw_2.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/ngw/other1.jpg " rel="lightbox[ngw-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/ngw/other1.jpg " style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/ngw/other3.jpg " rel="lightbox[ngw-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/ngw/other3.jpg " style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/ngw_t_sp.jpg" style="width:92%;margin:0 auto;"> <!--<img src="img/sp/sp_uri.jpg" style="width:92%;margin:0 auto;">--> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <select name="inventory_id" class="select_btn"> <option value="8961">ใƒ”ใƒณใ‚ฏ</option> <option value="8962">ใƒ–ใƒฉใ‚ฆใƒณ</option> </select> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003928"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-ngw sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- ngw ---------------------------------> <!-------------------------------- wds ---------------------------------> <li id="wds" class="item_id"> <img src="img/sp/55_sp.png" style="width:28%;position: absolute;z-index: 9;top:-2.2%;left:-1%;"> <img src="img/sp/wds_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/wds.jpg" rel="lightbox[wds-group]"><img src="img/sp/wds.jpg"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/wds/item/wds_s4_0120.jpg" rel="lightbox[wds-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/wds/item/wds_s4_0120.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/wds/item/wds_0831.jpg" rel="lightbox[wds-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/wds/item/wds_0831.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/wds_t_sp.jpg" style="width:92%;margin:0 auto;"> <!-- <img src="img/sp/sp_uri.jpg" style="width:92%;margin:0 auto;">--> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003952"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-wds sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- wds ---------------------------------> <!-------------------------------- trsp2 ---------------------------------> <li id="trsp2" class="item_id"> <img src="img/sp/60_sp.png" class="baku" style="width:28%;position: absolute;z-index: 9;top:-2.2%;left:-1%;"> <img src="img/sp/trsp2_ttl.jpg" style="width:92%;margin:4% auto 0;position: relative;"> <ul class="slider single-item" style="margin:0 0 10px;"> <li><a href="img/sp/trsp2_001.jpg" rel="lightbox[trsp2-group]"><img src="img/sp/trsp2_001.jpg"></a></li> <li><a href="img/sp/trsp2_s2.jpg" rel="lightbox[trsp2-group]"><img src="img/sp/trsp2_s2.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="img/sp/trsp2_s3.jpg" rel="lightbox[trsp2-group]"><img src="img/sp/trsp2_s3.jpg" style="width: 69%;margin: 0 auto;"></a></li> <li><a href="https://image.rakuten.co.jp/shopjapan/cabinet/share/used/khtn4.jpg" rel="lightbox[trsp2-group]"><img src="https://image.rakuten.co.jp/shopjapan/cabinet/share/used/khtn4.jpg" style="width: 69%;margin: 0 auto;"></a></li> </ul> <img src="img/sp/trs2_s_sp.jpg" style="width:92%;margin:0 auto;"> <form target="_blank" method="post" action="https://t.order.step.rakuten.co.jp/rms/mall/basket/vc"> <input type="text" name="units" class="matome_box" size="4" value="1" style="display:none"> <input type="image" src="https://image.rakuten.co.jp/shopjapan/cabinet/share/outlet/1col_cart_btn.jpg" name="button1" style="width:90%;margin:0 auto;"> <input type="hidden" name="__event" value="ES01_003_001"> <input type="hidden" name="shop_bid" value="199614"> <input type="hidden" name="item_id" value="10003933"> <input type="hidden" name="inventory_flag" value="1"> </form> <div class="info"><a href="#" class="modal-trsp2 sp_btn">ๅ•†ๅ“ๅ†…ๅฎนใฏใ“ใกใ‚‰</a></div> </li> <!-------------------------------- trsp2 ---------------------------------> </ul> </div> <br> <div class="out_info_sp"> <div class="about_outlet" id="out" style="width: 90%;margin: 0 auto 10px;"> <img src="img/sp/sp_ttl1.jpg" style="width: 100%;margin-bottom:10px;"> <p style="font-weight: bold;color: #38a13d;text-align: center;"><big>ไธญๅคๅ“ใ‚’ใŠ่ฒทไธŠใ’ใฎ้š›ใฏ<br>ๅฟ…ใšใ‚ณใƒใƒฉใ‚’ใ”็ขบ่ชไธ‹ใ•ใ„ใ€‚</big></p> </div> <div class="about_trs"> <p class="trs_ttl" style="background-color: #38a13d;"><big>ใƒขใƒƒใ‚ฟใ‚คใƒŠใ‚คๅธ‚ใซใคใ„ใฆ</big><br> <small>ใƒขใƒƒใ‚ฟใ‚คใƒŠใ‚คๅธ‚ใฎๅ•†ๅ“ใฏใŠๅฎขๆง˜ใ‹ใ‚‰ใฎ่ฟ”ๅ“ๅ“ใ‚’่ฒฉๅฃฒใ—ใฆใŠใ‚Šใพใ™ใ€‚</small> </p> <p><span>๏ผœๆ–ฐๅ“ๅŒๆง˜๏ผž</span> ๅผŠ็คพใงใฎ็›ฎ่ฆ–ๆคœๅ“ใซใ‚ˆใ‚Šใ€้…้€็”จใฎๆฎตใƒœใƒผใƒซ(ๅค–่ฃ…็ฎฑ)ใ‚’้–‹ๅฐใ—ใŸๆœชไฝฟ็”จใ ใจๆ€ใ‚ใ‚Œใ‚‹ๅ•†ๅ“ใ€‚</p> <p><span>๏ผœ็‰นไพก่‰ฏๅ“๏ผž</span> ๆœฌไฝ“ใƒปๅ‚™ๅ“ใƒปๆขฑๅŒ…็ฎฑใ‚’้–‹ๆขฑใ€ๅˆฉ็”จใ—ใŸๅฏ่ƒฝๆ€งใŒใ‚ใ‚‹ไฝฟ็”จไธŠใ€ๆ”ฏ้šœใฎใชใ„ๆคœๅ“ๆธˆใฟๅ•†ๅ“ใ€‚<br> <small>โ€ปๅฝ“็คพใซใฆๅค–่ฆณๆคœๆŸปใ€ๅ‹•ไฝœ็ขบ่ชใ‚’่กŒใ„ใ€ๅ•้กŒใชใไฝฟ็”จใงใใ‚‹ใจ็ขบ่ชใ•ใ‚ŒใŸ่ฃฝๅ“</small></p> <p><span>๏ผœ่ฟ”ๅ“ไธๅฏ๏ผž</span> ๆœฌใ‚ปใƒผใƒซๅ“ใฏใ€่ฟ”ๅ“ไธๅฏใจใชใ‚Šใพใ™ใ€‚</p> <br> <p>้€šๅธธไพกๆ ผใฏใ€ๆ–ฐๅ“ๅ•†ๅ“ใฎไพกๆ ผใงใ™ใ€‚ๆ–ฐๅ“ๅŒๆง˜ใ€็‰นไพก่‰ฏๅ“ใฎ่กจ็คบใŒใ”ใ–ใ„ใพใ™ๅ•†ๅ“ใฏใ€ๆ–ฐๅ“ๅ•†ๅ“ใจ็Šถๆ…‹ใŒ็•ฐใชใ‚‹ใ“ใจใ‚’ใ”ไบ†ๆ‰ฟใฎไธŠใ€ใ”่ณผๅ…ฅใใ ใ•ใ„</p> <p class="cutomor_number"><span>ใ€ใ‚ซใ‚นใ‚ฟใƒžใƒผใ‚ตใƒผใƒ“ใ‚นใ‚ปใƒณใ‚ฟใƒผใ€‘โ€ป้€š่ฉฑๆ–™็„กๆ–™</span> 0120-096-013๏ผˆ24ๆ™‚้–“365ๆ—ฅๅ—ไป˜๏ผ‰</p> </div> </div><br> <img src="img/sp/yokoku_sp.jpg" style="width:100%;"> <div class="to_top"> <a href="#top">ใ“ใฎใƒšใƒผใ‚ธใฎTOPใธ</a> </div> <div class="to_rsj"> <a href="https://www.rakuten.ne.jp/gold/shopjapan/">ใ‚ทใƒงใƒƒใƒ—ใ‚ธใƒฃใƒ‘ใƒณ<br> ๆฅฝๅคฉๅธ‚ๅ ดๅบ—TOPใธ</a> </div> <br> <script src="js/lightbox.js" type="text/javascript"></script> <script src="js/slick.min.js"></script> <script> $(function() { $('.single-item').slick(); }); </script> <!--ใ‚ซใ‚ฆใƒณใƒˆใƒ€ใ‚ฆใƒณใ‚ฟใ‚คใƒžใƒผ--> <!--<div id="timelimit"><div class="timelimit_inner"> <div class="timer"><span class="catext">ใ‚ญใƒฃใƒณใƒšใƒผใƒณ็ต‚ไบ†ใพใง</span> <div class="timer_1" id="sampleA"></div> </div></div></div>--> <!--ใ‚ซใ‚ฆใƒณใƒˆใƒ€ใ‚ฆใƒณใ‚ฟใ‚คใƒžใƒผ--> <script type="text/javascript" src="js/timer.js" charset="UTF-8"></script> <script type="text/javascript" src="js/hour_limited.js"></script> <script language="JavaScript" type="text/javascript"> // <!-- cdTimer1(); function cdTimer1() { // ่จญๅฎš้ …็›ฎ ใ“ใ“ใ‹ใ‚‰--------------------------------------------- // ใ‚ฟใ‚ฐ่ฆ็ด ใฎIDๅ var elemID = 'sampleA'; // ๆœŸ้™ๆ—ฅใ‚’่จญๅฎš var year = 2017; // ๅนด var month = 9; // ๆœˆ var day = 11; // ๆ—ฅ var hour = 10; // ๆ™‚ // ๆœŸ้™็ต‚ไบ†ๅพŒใฎใƒกใƒƒใ‚ปใƒผใ‚ธ var limitMessage = '<span class="end_camp">็ต‚ไบ†่‡ดใ—ใพใ—ใŸใ€‚</span>'; // ใƒกใƒƒใ‚ปใƒผใ‚ธใฎใ‚นใ‚ฟใ‚คใƒซใ‚ฏใƒฉใ‚นๅ๏ผˆๅค‰ๆ›ดใ—ใชใ„ๅ ดๅˆใฏ็ฉบๆฌ„๏ผ‰ var msgClass = 'msg_1'; // ่จญๅฎš้ …็›ฎ ใ“ใ“ใพใง--------------------------------------------- var timeLimit = new Date( year, month - 1, day , hour ); var timer = new CountdownTimer( elemID, timeLimit, limitMessage, msgClass ); timer.countDown(); } // --> </script> <!----------------------------ใ‚ขใ‚ฆใƒˆใƒฌใƒƒใƒˆ------------------------> <script> $(".out").click(function () { $(".out_info_sp").slideToggle("slow"); $("#down_btn").toggleClass("none"); }); </script> <style> .none{ display:none; } </style> <!----------------------------ใ‚ขใ‚ฆใƒˆใƒฌใƒƒใƒˆ------------------------> <!----------------------------ใƒใƒณใƒ–ใƒผ------------------------> <script type="text/javascript"> var _fout_queue = _fout_queue || {}; if (_fout_queue.segment === void 0) _fout_queue.segment = {}; if (_fout_queue.segment.queue === void 0) _fout_queue.segment.queue = []; _fout_queue.segment.queue.push({ 'user_id': 15627 }); (function() { var el = document.createElement('script'); el.type = 'text/javascript'; el.async = true; el.src = (('https:' == document.location.protocol) ? 'https://' : 'http://') + 'js.fout.jp/segmentation.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(el, s); })(); </script> <!----------------------------ใƒใƒณใƒ–ใƒผ------------------------> <!---------------------------YTM------------------------> <script type="text/javascript"> (function () { var tagjs = document.createElement("script"); var s = document.getElementsByTagName("script")[0]; tagjs.async = true; tagjs.src = "//s.yjtag.jp/tag.js#site=r5x5wBC"; s.parentNode.insertBefore(tagjs, s); }()); </script> <noscript> <iframe src="//b.yjtag.jp/iframe?c=r5x5wBC" width="1" height="1" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe> </noscript> <!---------------------------YTM------------------------> <div class="right_bnr_sp"> <a href="#out"> <img src="img/sp/right_bnr1_sp.png" style="width:25% ; position: fixed ; bottom: 0px; right: 0; z-index: 999;"></a> </div> <!-- User Insight PCDF Code Start : shopjapan.co.jp --> <script type="text/javascript"> var _uic = _uic ||{}; var _uih = _uih ||{};_uih['id'] = 50185; _uih['lg_id'] = ''; _uih['fb_id'] = ''; _uih['tw_id'] = ''; _uih['uigr_1'] = ''; _uih['uigr_2'] = ''; _uih['uigr_3'] = ''; _uih['uigr_4'] = ''; _uih['uigr_5'] = ''; _uih['uigr_6'] = ''; _uih['uigr_7'] = ''; _uih['uigr_8'] = ''; _uih['uigr_9'] = ''; _uih['uigr_10'] = ''; /* DO NOT ALTER BELOW THIS LINE */ /* WITH FIRST PARTY COOKIE */ (function() { var bi = document.createElement('scri'+'pt');bi.type = 'text/javascript'; bi.async = true; bi.src = ('https:' == document.location.protocol ? 'https://bs' : 'http://c') + '.nakanohito.jp/b3/bi.js'; var s = document.getElementsByTagName('scri'+'pt')[0];s.parentNode.insertBefore(bi, s); })(); </script> <!-- User Insight PCDF Code End : shopjapan.co.jp --> </body> </html> <!--ใƒขใƒผใƒ€ใƒซ--> <div id="target"></div> <!--ใƒขใƒผใƒ€ใƒซ-->
tohshige/test
used12_1801_bak/sp.html
HTML
gpl-3.0
22,835
<?php include ($_SERVER["DOCUMENT_ROOT"]."/backend/blocks/metatags.php"); include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/navigation-mobile/navigation-mobile.html"); include($_SERVER["DOCUMENT_ROOT"] . "/src/common.blocks/header/top-header.php"); include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/header/header.html"); include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/proposition/proposition.html"); include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/navigation/navigation.html"); include ($_SERVER["DOCUMENT_ROOT"]."/backend/breadcrumbs/breadcrumbs.php"); include ($_SERVER["DOCUMENT_ROOT"]."/backend/keywords/keywords.php"); echo "<title> $titleconst"; echo $keywords[5][title]; echo "</title>"; echo "<meta name='description' content='"; echo $keywords[5][description]; echo "'/>"; echo "<meta name='keywords' content='"; echo $keywords[5][keywords]; echo "'/>"; ?> <div class="wrapper"> <?php include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/left-nav/left-nav.html"); ?> <div class="wrapper__content"> <div class="tabs"> <div class="tabs__item guestbook__tab-rewiew tabs__item--active">ะ’ัะต ะพั‚ะทั‹ะฒั‹</div> <div class="tabs__item guestbook__tab-add">ะžัั‚ะฐะฒะธั‚ัŒ ะพั‚ะทั‹ะฒ</div> </div> <div class="guestbook__tab guestbook__rewiews guestbook__tab--active"> <h1 class="title title-h1">ะะฐะผ ะฒะฐะถะฝะพ ะ’ะฐัˆะต ะผะฝะตะฝะธะต!</h1> <p class="text">ะะฐ ะดะฐะฝะฝะพะน ัั‚ั€ะฐะฝะธั†ะต ะ’ั‹ ะผะพะถะตั‚ะต ะพัั‚ะฐะฒะธั‚ัŒ ะพั‚ะทั‹ะฒ ะพ ะฝะฐัˆะตะน ะฟั€ะพะดะตะปะฐะฝะฝะพะน ั€ะฐะฑะพั‚ะต, ะปะธะฑะพ ะฝะฐะฟะธัะฐั‚ัŒ ะฝะฐะผ ะบะฐะบะธะต-ะปะธะฑะพ ะฟะพะถะตะปะฐะฝะธั. ะ ั‚ะฐะบะถะต ะฟะพัะผะพั‚ั€ะตั‚ัŒ ะดั€ัƒะณะธะต ะพั‚ะทั‹ะฒั‹ ะพ ะฝะฐั.</p> <?php // ะกะพะตะดะธะฝะตะฝะธะต ั ะ‘ะ” MySQL $dbname = "9082410193_zakaz"; include ($_SERVER["DOCUMENT_ROOT"]."/backend/connectdb.php"); // ะšะพะปะธั‡ะตัั‚ะฒะพ ะทะฐะฟะธัะตะน ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต $on_page = 10; // ะŸะพะปัƒั‡ะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะทะฐะฟะธัะตะน ั‚ะฐะฑะปะธั†ั‹ $query = "SELECT COUNT(*) FROM guestbook INNER JOIN `status` ON guestbook.status = status.status_name AND status.status_name <> 'ะฃะ”ะะ›ะ•ะ'"; $res = mysqli_query($connect, $query); $count_records = mysqli_fetch_row($res); $count_records = $count_records[0]; // ะŸะพะปัƒั‡ะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ัั‚ั€ะฐะฝะธั† // ะ”ะตะปะธะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฒัะตั… ะทะฐะฟะธัะตะน ะฝะฐ ะบะพะปะธั‡ะตัั‚ะฒะพ ะทะฐะฟะธัะตะน ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต // ะธ ะพะบั€ัƒะณะปัะตะผ ะฒ ะฑะพะปัŒัˆัƒัŽ ัั‚ะพั€ะพะฝัƒ $num_pages = ceil($count_records / $on_page); // ะขะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ ะธะท GET-ะฟะฐั€ะฐะผะตั‚ั€ะฐ page // ะ•ัะปะธ ะฟะฐั€ะฐะผะตั‚ั€ ะฝะต ะพะฟั€ะตะดะตะปะตะฝ, ั‚ะพ ั‚ะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ ั€ะฐะฒะฝะฐ 1 $current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // ะ•ัะปะธ ั‚ะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ ะผะตะฝัŒัˆะต ะตะดะธะฝะธั†ั‹, ั‚ะพ ัั‚ั€ะฐะฝะธั†ะฐ ั€ะฐะฒะฝะฐ 1 if ($current_page < 1) { $current_page = 1; } // ะ•ัะปะธ ั‚ะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ ะฑะพะปัŒัˆะต ะพะฑั‰ะตะณะพ ะบะพะปะธั‡ะตัั‚ะฒะฐ ัั‚ั€ะฐะฝะธั†ะฐ, ั‚ะพ // ั‚ะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ ั€ะฐะฒะฝะฐ ะบะพะปะธั‡ะตัั‚ะฒัƒ ัั‚ั€ะฐะฝะธั† elseif ($current_page > $num_pages) { $current_page = $num_pages; } // ะะฐั‡ะฐั‚ัŒ ะฟะพะปัƒั‡ะตะฝะธะต ะดะฐะฝะฝั‹ั… ะพั‚ ั‡ะธัะปะฐ (ั‚ะตะบัƒั‰ะฐั ัั‚ั€ะฐะฝะธั†ะฐ - 1) * ะบะพะปะธั‡ะตัั‚ะฒะพ ะทะฐะฟะธัะตะน ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต $start_from = ($current_page - 1) * $on_page; // ะคะพั€ะผะฐั‚ ะพะฟะตั€ะฐั‚ะพั€ะฐ LIMIT <ะ—ะะŸะ˜ะกะฌ ะžะข>, <ะšะžะ›ะ˜ะงะ•ะกะขะ’ะž ะ—ะะŸะ˜ะกะ•ะ™> $query = "SELECT * FROM `guestbook` INNER JOIN `status` ON guestbook.status = status.status_name AND status.status_name <> 'ะฃะ”ะะ›ะ•ะ' ORDER BY `id` DESC LIMIT $start_from, $on_page"; $res = mysqli_query($connect, $query); if ($count_records == 0) { echo '<div class="good-message">'; echo '<p class="text">ะะฐ ัะฐะนั‚ะต ะฟะพะบะฐ ะฝะต ะพัั‚ะฐะฒะปะตะฝะพ ะฝะธ ะพะดะฝะพะณะพ ะพั‚ะทั‹ะฒะฐ :( ะ’ั‹ ะผะพะถะตั‚ะต ัะดะตะปะฐั‚ัŒ ัั‚ะพ ะฟะตั€ะฒั‹ะผ!</p>'; echo '</div>'; } elseif ($count_records <> 0){ // ะ’ั‹ะฒะพะด ั€ะตะทัƒะปัŒั‚ะฐั‚ะพะฒ while ($row = mysqli_fetch_assoc($res)) { echo '<div class="rewiew">'; echo '<div class="rewiew__name">'; echo '<span>'.$row['name'].'</span>'; echo '</div>'; echo '<div class="rewiew__text-wrap">'; echo '<p class="text rewiew__text">'.$row['rewiew'].'</p>'; echo '</div>'; echo '<div class="rewiew__text-wrap">'; echo '<p class="text rewiew__answer">'.$row['answer'].'</p>'; echo '</div>'; echo '</div>'; } // ะ’ั‹ะฒะพะด ัะฟะธัะบะฐ ัั‚ั€ะฐะฝะธั† echo '<p class="page-numbers">'; for ($page = 1; $page <= $num_pages; $page++) { if ($page == $current_page) { echo '<strong>'.$page.'</strong> &nbsp;'; } else { echo '<a class="link" href="guestbook.php?page='.$page.'">'.$page.'</a> &nbsp;'; } } ?> <div class="tabs__item guestbook__tab-add link-green">ะ”ะพะฑะฐะฒะธั‚ัŒ ะพั‚ะทั‹ะฒ ะฝะฐ ัะฐะนั‚</div> <?php } echo '</p>'; ?> </div> <div class="guestbook__tab guestbook__rewiews-add"> <h2 class="title title-h2">ะžัั‚ะฐะฒะธั‚ัŒ ัะฒะพะน ะพั‚ะทั‹ะฒ ะพ ะฝะฐั!</h2> <?php include ($_SERVER["DOCUMENT_ROOT"]."/backend/forms/rewiewform.php"); ?> </div> </div> </div> <?php include ($_SERVER["DOCUMENT_ROOT"]."/src/common.blocks/footer/footer.html"); include ($_SERVER["DOCUMENT_ROOT"]."/backend/blocks/counters.html"); ?>
igoldyrev/autobagaz
guestbook.php
PHP
gpl-3.0
6,770
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2004-2011. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2001-2003 // William E. Kempf // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. William E. Kempf makes no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. #ifndef BOOST_INTERPROCESS_TEST_MUTEX_TEST_TEMPLATE_HEADER #define BOOST_INTERPROCESS_TEST_MUTEX_TEST_TEMPLATE_HEADER #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/exceptions.hpp> #include "boost_interprocess_check.hpp" #include "util.hpp" #include <boost/thread/thread.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <iostream> namespace boost { namespace interprocess { namespace test { template <typename M> struct test_lock { typedef M mutex_type; typedef boost::interprocess::scoped_lock<mutex_type> lock_type; void operator()() { mutex_type interprocess_mutex; // Test the lock's constructors. { lock_type lock(interprocess_mutex, boost::interprocess::defer_lock); BOOST_INTERPROCES_CHECK(!lock); } lock_type lock(interprocess_mutex); BOOST_INTERPROCES_CHECK(lock ? true : false); // Test the lock and unlock methods. lock.unlock(); BOOST_INTERPROCES_CHECK(!lock); lock.lock(); BOOST_INTERPROCES_CHECK(lock ? true : false); } }; template <typename M> struct test_trylock { typedef M mutex_type; typedef boost::interprocess::scoped_lock<mutex_type> try_to_lock_type; void operator()() { mutex_type interprocess_mutex; // Test the lock's constructors. { try_to_lock_type lock(interprocess_mutex, boost::interprocess::try_to_lock); BOOST_INTERPROCES_CHECK(lock ? true : false); } { try_to_lock_type lock(interprocess_mutex, boost::interprocess::defer_lock); BOOST_INTERPROCES_CHECK(!lock); } try_to_lock_type lock(interprocess_mutex); BOOST_INTERPROCES_CHECK(lock ? true : false); // Test the lock, unlock and trylock methods. lock.unlock(); BOOST_INTERPROCES_CHECK(!lock); lock.lock(); BOOST_INTERPROCES_CHECK(lock ? true : false); lock.unlock(); BOOST_INTERPROCES_CHECK(!lock); BOOST_INTERPROCES_CHECK(lock.try_lock()); BOOST_INTERPROCES_CHECK(lock ? true : false); } }; template <typename M> struct test_timedlock { typedef M mutex_type; typedef boost::interprocess::scoped_lock<mutex_type> timed_lock_type; void operator()() { mutex_type interprocess_mutex; // Test the lock's constructors. { // Construct and initialize an ptime for a fast time out. boost::posix_time::ptime pt = delay(1*BaseSeconds, 0); timed_lock_type lock(interprocess_mutex, pt); BOOST_INTERPROCES_CHECK(lock ? true : false); } { timed_lock_type lock(interprocess_mutex, boost::interprocess::defer_lock); BOOST_INTERPROCES_CHECK(!lock); } timed_lock_type lock(interprocess_mutex); BOOST_INTERPROCES_CHECK(lock ? true : false); // Test the lock, unlock and timedlock methods. lock.unlock(); BOOST_INTERPROCES_CHECK(!lock); lock.lock(); BOOST_INTERPROCES_CHECK(lock ? true : false); lock.unlock(); BOOST_INTERPROCES_CHECK(!lock); boost::posix_time::ptime pt = delay(3*BaseSeconds, 0); BOOST_INTERPROCES_CHECK(lock.timed_lock(pt)); BOOST_INTERPROCES_CHECK(lock ? true : false); } }; template <typename M> struct test_recursive_lock { typedef M mutex_type; typedef boost::interprocess::scoped_lock<mutex_type> lock_type; void operator()() { mutex_type mx; { lock_type lock1(mx); lock_type lock2(mx); } { lock_type lock1(mx, defer_lock); lock_type lock2(mx, defer_lock); } { lock_type lock1(mx, try_to_lock); lock_type lock2(mx, try_to_lock); } { //This should always lock boost::posix_time::ptime pt = delay(2*BaseSeconds); lock_type lock1(mx, pt); lock_type lock2(mx, pt); } } }; // plain_exclusive exercises the "infinite" lock for each // read_write_mutex type. template<typename M> void lock_and_sleep(void *arg, M &sm) { data<M> *pdata = static_cast<data<M>*>(arg); boost::interprocess::scoped_lock<M> l(sm); if(pdata->m_secs){ boost::thread::sleep(xsecs(pdata->m_secs)); } else{ boost::thread::sleep(xsecs(2*BaseSeconds)); } ++shared_val; pdata->m_value = shared_val; } template<typename M> void lock_and_catch_errors(void *arg, M &sm) { data<M> *pdata = static_cast<data<M>*>(arg); try { boost::interprocess::scoped_lock<M> l(sm); if(pdata->m_secs){ boost::thread::sleep(xsecs(pdata->m_secs)); } else{ boost::thread::sleep(xsecs(2*BaseSeconds)); } ++shared_val; pdata->m_value = shared_val; } catch(interprocess_exception const & e) { pdata->m_error = e.get_error_code(); } } template<typename M> void try_lock_and_sleep(void *arg, M &sm) { data<M> *pdata = static_cast<data<M>*>(arg); boost::interprocess::scoped_lock<M> l(sm, boost::interprocess::defer_lock); if (l.try_lock()){ boost::thread::sleep(xsecs(2*BaseSeconds)); ++shared_val; pdata->m_value = shared_val; } } template<typename M> void timed_lock_and_sleep(void *arg, M &sm) { data<M> *pdata = static_cast<data<M>*>(arg); boost::posix_time::ptime pt(delay(pdata->m_secs)); boost::interprocess::scoped_lock<M> l (sm, boost::interprocess::defer_lock); if (l.timed_lock(pt)){ boost::thread::sleep(xsecs(2*BaseSeconds)); ++shared_val; pdata->m_value = shared_val; } } template<typename M> void test_mutex_lock() { shared_val = 0; M mtx; data<M> d1(1); data<M> d2(2); // Locker one launches, holds the lock for 2*BaseSeconds seconds. boost::thread tm1(thread_adapter<M>(&lock_and_sleep, &d1, mtx)); //Wait 1*BaseSeconds boost::thread::sleep(xsecs(1*BaseSeconds)); // Locker two launches, but it won't hold the lock for 2*BaseSeconds seconds. boost::thread tm2(thread_adapter<M>(&lock_and_sleep, &d2, mtx)); //Wait completion tm1.join(); boost::thread::sleep(xsecs(1*BaseSeconds)); tm2.join(); BOOST_INTERPROCES_CHECK(d1.m_value == 1); BOOST_INTERPROCES_CHECK(d2.m_value == 2); } template<typename M> void test_mutex_lock_timeout() { shared_val = 0; M mtx; int wait_time_s = BOOST_INTERPROCESS_TIMEOUT_WHEN_LOCKING_DURATION_MS / 1000; if (wait_time_s == 0 ) wait_time_s = 1; data<M> d1(1, wait_time_s * 3); data<M> d2(2, wait_time_s * 2); // Locker one launches, and holds the lock for wait_time_s * 2 seconds. boost::thread tm1(thread_adapter<M>(&lock_and_sleep, &d1, mtx)); //Wait 1*BaseSeconds boost::thread::sleep(xsecs(wait_time_s)); // Locker two launches, and attempts to hold the lock for wait_time_s * 2 seconds. boost::thread tm2(thread_adapter<M>(&lock_and_catch_errors, &d2, mtx)); //Wait completion tm1.join(); boost::thread::sleep(xsecs(1*BaseSeconds)); tm2.join(); BOOST_INTERPROCES_CHECK(d1.m_value == 1); BOOST_INTERPROCES_CHECK(d2.m_value == -1); BOOST_INTERPROCES_CHECK(d1.m_error == no_error); BOOST_INTERPROCES_CHECK(d2.m_error == boost::interprocess::timeout_when_locking_error); } template<typename M> void test_mutex_try_lock() { shared_val = 0; M mtx; data<M> d1(1); data<M> d2(2); // Locker one launches, holds the lock for 2*BaseSeconds seconds. boost::thread tm1(thread_adapter<M>(&try_lock_and_sleep, &d1, mtx)); //Wait 1*BaseSeconds boost::thread::sleep(xsecs(1*BaseSeconds)); // Locker two launches, but it should fail acquiring the lock boost::thread tm2(thread_adapter<M>(&try_lock_and_sleep, &d2, mtx)); //Wait completion tm1.join(); tm2.join(); //Only the first should succeed locking BOOST_INTERPROCES_CHECK(d1.m_value == 1); BOOST_INTERPROCES_CHECK(d2.m_value == -1); } template<typename M> void test_mutex_timed_lock() { shared_val = 0; M mtx, m2; data<M> d1(1, 2*BaseSeconds); data<M> d2(2, 2*BaseSeconds); // Locker one launches, holds the lock for 2*BaseSeconds seconds. boost::thread tm1(thread_adapter<M>(&timed_lock_and_sleep, &d1, mtx)); //Wait 1*BaseSeconds boost::thread::sleep(xsecs(1*BaseSeconds)); // Locker two launches, holds the lock for 2*BaseSeconds seconds. boost::thread tm2(thread_adapter<M>(&timed_lock_and_sleep, &d2, mtx)); //Wait completion tm1.join(); tm2.join(); //Both should succeed locking BOOST_INTERPROCES_CHECK(d1.m_value == 1); BOOST_INTERPROCES_CHECK(d2.m_value == 2); } template <typename M> inline void test_all_lock() { //Now generic interprocess_mutex tests std::cout << "test_lock<" << typeid(M).name() << ">" << std::endl; test_lock<M>()(); std::cout << "test_trylock<" << typeid(M).name() << ">" << std::endl; test_trylock<M>()(); std::cout << "test_timedlock<" << typeid(M).name() << ">" << std::endl; test_timedlock<M>()(); } template <typename M> inline void test_all_recursive_lock() { //Now generic interprocess_mutex tests std::cout << "test_recursive_lock<" << typeid(M).name() << ">" << std::endl; test_recursive_lock<M>()(); } template<typename M> void test_all_mutex() { std::cout << "test_mutex_lock<" << typeid(M).name() << ">" << std::endl; test_mutex_lock<M>(); std::cout << "test_mutex_try_lock<" << typeid(M).name() << ">" << std::endl; test_mutex_try_lock<M>(); std::cout << "test_mutex_timed_lock<" << typeid(M).name() << ">" << std::endl; test_mutex_timed_lock<M>(); } }}} //namespace boost { namespace interprocess { namespace test { #include <boost/interprocess/detail/config_end.hpp> #endif //BOOST_INTERPROCESS_TEST_MUTEX_TEST_TEMPLATE_HEADER
tianyang-li/de-novo-rna-seq-quant-1
boost_1_51_0/libs/interprocess/test/mutex_test_template.hpp
C++
gpl-3.0
10,762
# node-bing-wallpaper Simple node script to retrieve latest daily bing wallpaper
mihab/node-bing-wallpaper
README.md
Markdown
gpl-3.0
81
package org.kramerlab.seitan.api.services; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.kramerlab.seitan.api.exceptions.SEITANException; import org.springframework.beans.factory.annotation.Required; import org.springframework.stereotype.Service; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import java.io.IOException; @Service public interface GroupIDService extends SEITANService { @GET @Produces({MediaType.APPLICATION_JSON}) public String getGroup(@Context UriInfo uri, @QueryParam("modal") String modal); @POST public void updateGroup(@Context UriInfo uri, @FormParam("name") String newName, @FormParam("description") String newDescription, @FormParam("owner") String newOwner, @FormParam("addReader") String newReader, @FormParam("addWriter") String newWriter, @FormParam("rmReader") String rmReader, @FormParam("rmWriter") String rmWriter, @Multipart(value = "isDelete", required = false) String isDelete) throws SEITANException, IOException; @DELETE public void deleteGroup(@Context UriInfo uri) throws SEITANException, IOException; }
joergwicker/seitan
seitan-api/src/main/java/org/kramerlab/seitan/api/services/GroupIDService.java
Java
gpl-3.0
1,466
/** * Created by tmanson on 03/05/2016. */ angular.module('redCrossQuestClient').factory('YearlyGoalsResource', function ($resource, $localStorage) { return $resource('/rest/:roleId/ul/:ulId/yearlyGoals/:id', { roleId: function () { return $localStorage.currentUser.roleId}, ulId : function () { return $localStorage.currentUser.ulId }, id : '@id' }, { update: { method: 'PUT' // this method issues a PUT request }, createYear: { method: 'POST' }, getByYear:{ method: 'GET' } }); });
dev-mansonthomas/RedCrossQuest
client/src/app/admin/yearlyGoals/yearlyGoals.resource.js
JavaScript
gpl-3.0
584
Source : https://bootswatch.com/ Themes : Flatly
antonraharja/playSMS
web/plugin/themes/flatly/jscss/bootstrap/README.md
Markdown
gpl-3.0
49
package l2s.commons.data.xml.helpers; import l2s.commons.data.xml.AbstractParser; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Author: VISTALL * Date: 20:43/30.11.2010 */ public class ErrorHandlerImpl implements ErrorHandler { private AbstractParser<?> _parser; public ErrorHandlerImpl(AbstractParser<?> parser) { _parser = parser; } @Override public void warning(SAXParseException exception) throws SAXException { _parser.warn("File: " + _parser.getCurrentFileName() + ":" + exception.getLineNumber() + " warning: " + exception.getMessage()); } @Override public void error(SAXParseException exception) throws SAXException { _parser.error("File: " + _parser.getCurrentFileName() + ":" + exception.getLineNumber() + " error: " + exception.getMessage()); } @Override public void fatalError(SAXParseException exception) throws SAXException { _parser.error("File: " + _parser.getCurrentFileName() + ":" + exception.getLineNumber() + " fatal: " + exception.getMessage()); } }
pantelis60/L2Scripts_Underground
commons/src/main/java/l2s/commons/data/xml/helpers/ErrorHandlerImpl.java
Java
gpl-3.0
1,073
/* BEGIN LICENSE BLOCK Copyright 2010-2011, Heiko Mueller, Sam Lindley, James Cheney and University of Edinburgh This file is part of Database Wiki. Database Wiki 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. Database Wiki 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 Database Wiki. If not, see <http://www.gnu.org/licenses/>. END LICENSE BLOCK */ package org.dbwiki.web.ui.printer; import org.dbwiki.exception.WikiException; import org.dbwiki.web.html.HtmlLinePrinter; import org.dbwiki.web.request.WikiRequest; import org.dbwiki.web.request.parameter.RequestParameter; import org.dbwiki.web.request.parameter.RequestParameterAction; import org.dbwiki.web.server.DatabaseWiki; import org.dbwiki.web.server.WikiServerConstants; import org.dbwiki.web.ui.CSS; /** Prints out a form that will generate file edit requests * * @author jcheney * */ public class FileEditor extends HtmlContentPrinter { /* * Private Variables */ private WikiRequest _request; private String _title; /* * Constructors */ public FileEditor(WikiRequest request, String title) { _request = request; _title = title; } /* * Public Methods */ public void print(HtmlLinePrinter printer) throws WikiException { int fileType = -1; if (_request.parameters().hasParameter(RequestParameter.ParameterTemplate)) { fileType = WikiServerConstants.RelConfigFileColFileTypeValTemplate; } else if (_request.parameters().hasParameter(RequestParameter.ParameterStyleSheet)) { fileType = WikiServerConstants.RelConfigFileColFileTypeValCSS; } else if (_request.parameters().hasParameter(RequestParameter.ParameterURLDecoding)) { fileType = WikiServerConstants.RelConfigFileColFileTypeValURLDecoding; } printer.paragraph(_title, CSS.CSSHeadline); printer.openFORM("frmEditor", "POST", _request.parameters().get(RequestParameter.ParameterResource).value()); printer.addHIDDEN(DatabaseWiki.ParameterDatabaseID, Integer.toString(_request.wiki().id())); printer.addHIDDEN(DatabaseWiki.ParameterFileType, Integer.toString(fileType)); printer.openTABLE(CSS.CSSFormContainer); printer.openTR(); printer.openTD(CSS.CSSFormContainer); printer.addTEXTAREA(DatabaseWiki.ParameterFileContent, "110", "30", true, _request.wiki().getContent(fileType)); printer.openPARAGRAPH(CSS.CSSButtonLine); printer.openCENTER(); printer.addREALBUTTON("submit", "action", RequestParameterAction.ActionUpdate, "<img src=\"/pictures/button_save.gif\">"); printer.text("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); printer.addREALBUTTON("submit", "action", RequestParameterAction.ActionCancel, "<img src=\"/pictures/button_cancel.gif\">"); printer.closeCENTER(); printer.closePARAGRAPH(); printer.closeFORM(); printer.closeTD(); printer.closeTR(); printer.closeTABLE(); } }
jamescheney/database-wiki
src/org/dbwiki/web/ui/printer/FileEditor.java
Java
gpl-3.0
3,343
package isms.api; import java.util.concurrent.ExecutionException; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.apache.kafka.clients.producer.RecordMetadata; import isms.common.Constants; import isms.models.SensorRecord; import isms.services.Producer; import isms.services.ProducerSupplier; @Path(Constants.API_ENDPOINT_RECORDS) @Consumes(MediaType.APPLICATION_JSON) public class RecordsApi extends BaseApi { private Producer producer; public RecordsApi() { super(); producer = new ProducerSupplier().get(); } @POST public long send(SensorRecord record) { producer.send(record); return record.getTime(); } @POST @Path("/sync") public long sendSync(SensorRecord record) throws InterruptedException, ExecutionException { return producer.sendSync(record).timestamp(); } }
aci2n/isms
Web/src/isms/api/RecordsApi.java
Java
gpl-3.0
877
#!/usr/bin/env python2.7 # coding=utf-8 # Author: Dustyn Gibson <miigotu@gmail.com> # URL: http://github.com/SickRage/SickRage # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. """ Test sickbeard.helpers Methods: fixGlob indentXML remove_non_release_groups isMediaFile isRarFile isBeingWritten remove_file_failed makeDir searchIndexerForShowID listMediaFiles copyFile moveFile link hardlinkFile symlink moveAndSymlinkFile make_dirs rename_ep_file delete_empty_folders fileBitFilter chmodAsParent fixSetGroupID is_anime_in_show_list update_anime_support get_absolute_number_from_season_and_episode get_all_episodes_from_absolute_number sanitizeSceneName arithmeticEval create_https_certificates backupVersionedFile restoreVersionedFile md5_for_file get_lan_ip check_url anon_url encrypt decrypt full_sanitizeSceneName _check_against_names get_show is_hidden_folder real_path validateShow set_up_anidb_connection makeZip extractZip backupConfigZip restoreConfigZip mapIndexersToShow touchFile _getTempDir _setUpSession getURL download_file get_size generateApiKey remove_article generateCookieSecret verify_freespace pretty_time_delta isFileLocked getDiskSpaceUsage """ import os.path import sys import unittest sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib'))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from sickbeard.helpers import remove_non_release_groups TEST_RESULT = 'Show.Name.S01E01.HDTV.x264-RLSGROUP' TEST_CASES = { 'removewords': [ TEST_RESULT, 'Show.Name.S01E01.HDTV.x264-RLSGROUP[cttv]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP.RiPSaLoT', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[GloDLS]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[EtHD]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP-20-40', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[NO-RAR] - [ www.torrentday.com ]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[rarbg]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[Seedbox]', '{ www.SceneTime.com } - Show.Name.S01E01.HDTV.x264-RLSGROUP', '].[www.tensiontorrent.com] - Show.Name.S01E01.HDTV.x264-RLSGROUP', '[ www.TorrentDay.com ] - Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[silv4]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[AndroidTwoU]', '[www.newpct1.com]Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP-NZBGEEK', '.www.Cpasbien.pwShow.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP [1044]', '[ www.Cpasbien.pw ] Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP.[BT]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[vtv]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP.[www.usabit.com]', '[www.Cpasbien.com] Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[ettv]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[rartv]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP-Siklopentan', 'Show.Name.S01E01.HDTV.x264-RLSGROUP-RP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[PublicHD]', '[www.Cpasbien.pe] Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP[eztv]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP-[SpastikusTV]', '].[ www.tensiontorrent.com ] - Show.Name.S01E01.HDTV.x264-RLSGROUP', '[ www.Cpasbien.com ] Show.Name.S01E01.HDTV.x264-RLSGROUP', 'Show.Name.S01E01.HDTV.x264-RLSGROUP- { www.SceneTime.com }', 'Show.Name.S01E01.HDTV.x264-RLSGROUP- [ www.torrentday.com ]', 'Show.Name.S01E01.HDTV.x264-RLSGROUP.Renc' ] } class HelpersTests(unittest.TestCase): """ Test using test generator """ def __init__(self, *args, **kwargs): """ Initialize test """ super(HelpersTests, self).__init__(*args, **kwargs) def test_generator(test_strings): """ Generate tests from test strings :param test_strings: to generate tests from :return: test """ def _test(self): """ Generate tests :param self: :return: test to run """ for test_string in test_strings: self.assertEqual(remove_non_release_groups(test_string), TEST_RESULT) return _test class HelpersZipTests(unittest.TestCase): """ Test zip methods """ @unittest.skip('Not yet implemented') def test_make_zip(self): """ Test makeZip """ pass @unittest.skip('Not yet implemented') def test_extract_zip(self): """ Test extractZip """ pass @unittest.skip('Not yet implemented') def test_backup_config_zip(self): """ Test backupConfigZip """ pass @unittest.skip('Not yet implemented') def test_restore_config_zip(self): """ Test restoreConfigZip """ pass @unittest.skip('Not yet implemented') def test_is_rar_file(self): """ Test isRarFile """ pass class HelpersDirectoryTests(unittest.TestCase): """ Test directory methods """ @unittest.skip('Not yet implemented') def test_make_dirs(self): """ Test make_dirs """ pass @unittest.skip('Not yet implemented') def test_delete_empty_folders(self): """ Test delete_empty_folders """ pass @unittest.skip('Not yet implemented') def test_make_dir(self): """ Test makeDir """ pass @unittest.skip('Not yet implemented') def test_get_temp_dir(self): """ Test _getTempDir """ pass @unittest.skip('Not yet implemented') def test_is_hidden_folder(self): """ Test is_hidden_folder """ pass @unittest.skip('Not yet implemented') def test_real_path(self): """ Test real_path """ pass class HelpersFileTests(unittest.TestCase): """ Test file helpers """ @unittest.skip('Not yet implemented') def test_is_media_file(self): """ Test isMediaFile """ pass @unittest.skip('Not yet implemented') def test_is_file_locked(self): """ Test isFileLocked """ pass @unittest.skip('Not yet implemented') def test_is_being_written(self): """ Test isBeingWritten """ pass @unittest.skip('Not yet implemented') def test_remove_file_failed(self): """ Test remove_file_failed """ pass @unittest.skip('Not yet implemented') def test_list_media_files(self): """ Test listMediaFiles """ pass @unittest.skip('Not yet implemented') def test_copy_file(self): """ Test copyFile """ pass @unittest.skip('Not yet implemented') def test_move_file(self): """ Test moveFile """ pass @unittest.skip('Not yet implemented') def test_rename_ep_file(self): """ Test rename_ep_file """ pass @unittest.skip('Not yet implemented') def test_file_bit_filter(self): """ Test fileBitFilter """ pass @unittest.skip('Not yet implemented') def test_chmod_as_parent(self): """ Test chmodAsParent """ pass @unittest.skip('Not yet implemented') def test_backup_versioned_file(self): """ Test backupVersionedFile """ pass @unittest.skip('Not yet implemented') def test_restore_versioned_file(self): """ Test restoreVersionedFile """ pass @unittest.skip('Not yet implemented') def test_verify_free_space(self): """ Test verify_freespace """ pass @unittest.skip('Not yet implemented') def test_get_disk_space_usage(self): """ Test getDiskSpaceUsage """ pass @unittest.skip('Not yet implemented') def test_download_file(self): """ Test download_file """ pass @unittest.skip('Not yet implemented') def test_get_size(self): """ Test get_size """ pass @unittest.skip('Not yet implemented') def test_md5_for_file(self): """ Test md5_for_file """ pass @unittest.skip('Not yet implemented') def test_touch_file(self): """ Test touchFile """ pass class HelpersFileLinksTests(unittest.TestCase): """ Test sym and hard links """ @unittest.skip('Not yet implemented') def test_link(self): """ Test link """ pass @unittest.skip('Not yet implemented') def test_hardlink_file(self): """ Test hardlinkFile """ pass @unittest.skip('Not yet implemented') def test_symlink(self): """ Test symlink """ pass @unittest.skip('Not yet implemented') def test_move_and_symlink_file(self): """ Test moveAndSymlinkFile """ pass class HelpersEncryptionTests(unittest.TestCase): """ Test encryption and decryption """ @unittest.skip('Not yet implemented') def test_create_https_certificates(self): """ Test create_https_certificates """ pass @unittest.skip('Not yet implemented') def test_encrypt(self): """ Test encrypt """ pass @unittest.skip('Not yet implemented') def test_decrypt(self): """ Test decrypt """ pass @unittest.skip('Not yet implemented') def test_generate_cookie_secret(self): """ Test generateCookieSecret """ pass class HelpersShowTests(unittest.TestCase): """ Test show methods """ @unittest.skip('Not yet implemented') def test_search_indexer_for_show_id(self): """ Test searchIndexerForShowID """ pass @unittest.skip('Not yet implemented') def test_is_anime_in_show_list(self): """ Test is_anime_in_show_list """ pass @unittest.skip('Not yet implemented') def test_check_against_names(self): """ Test _check_against_names """ pass @unittest.skip('Not yet implemented') def test_get_show(self): """ Test get_show """ pass @unittest.skip('Not yet implemented') def test_validate_show(self): """ Test validateShow """ pass @unittest.skip('Not yet implemented') def test_map_indexers_to_show(self): """ Test mapIndexersToShow """ pass @unittest.skip('Not yet implemented') def test_get_abs_no_from_s_and_e(self): """ Test get_absolute_number_from_season_and_episode """ pass @unittest.skip('Not yet implemented') def test_get_all_eps_from_abs_no(self): """ Test get_all_episodes_from_absolute_number """ pass class HelpersConnectionTests(unittest.TestCase): """ Test connections """ @unittest.skip('Not yet implemented') def test_get_lan_ip(self): """ Test get_lan_ip """ pass @unittest.skip('Not yet implemented') def test_check_url(self): """ Test check_url """ pass @unittest.skip('Not yet implemented') def test_anon_url(self): """ Test anon_url """ pass @unittest.skip('Not yet implemented') def test_set_up_anidb_connection(self): """ Test set_up_anidb_connection """ pass @unittest.skip('Not yet implemented') def test_set_up_session(self): """ Test _setUpSession """ pass @unittest.skip('Not yet implemented') def test_get_url(self): """ Test getURL """ pass @unittest.skip('Not yet implemented') def test_generate_api_key(self): """ Test generateApiKey """ pass class HelpersMiscTests(unittest.TestCase): """ Test misc helper methods """ @unittest.skip('Not yet implemented') def test_fix_glob(self): """ Test fixGlob """ pass @unittest.skip('Not yet implemented') def test_indent_xml(self): """ Test indentXML """ pass @unittest.skip('Not yet implemented') def test_remove_non_release_groups(self): """ Test remove_non_release_groups """ pass @unittest.skip('Not yet implemented') def test_fix_set_group_id(self): """ Test fixSetGroupID """ pass @unittest.skip('Not yet implemented') def test_update_anime_support(self): """ Test update_anime_support """ pass @unittest.skip('Not yet implemented') def test_sanitize_scene_name(self): """ Test sanitizeSceneName """ pass @unittest.skip('Not yet implemented') def test_arithmetic_eval(self): """ Test arithmeticEval """ pass @unittest.skip('Not yet implemented') def test_full_sanitize_scene_name(self): """ Test full_sanitizeSceneName """ pass @unittest.skip('Not yet implemented') def test_remove_article(self): """ Test remove_article """ pass @unittest.skip('Not yet implemented') def test_pretty_time_delta(self): """ Test pretty_time_delta """ pass if __name__ == '__main__': print "==================" print "STARTING - Helpers TESTS" print "==================" print "######################################################################" for name, test_data in TEST_CASES.items(): test_name = 'test_%s' % name test = test_generator(test_data) setattr(HelpersTests, test_name, test) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersConnectionTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersDirectoryTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersEncryptionTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersFileLinksTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersFileTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersMiscTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersShowTests) unittest.TextTestRunner(verbosity=2).run(SUITE) SUITE = unittest.TestLoader().loadTestsFromTestCase(HelpersZipTests) unittest.TextTestRunner(verbosity=2).run(SUITE)
hernandito/SickRage
tests/helpers_tests.py
Python
gpl-3.0
16,369
''' Decomposition ------------- The core of sector decomposition. This module implements the actual decomposition routines. Common ~~~~~~ This module collects routines that are used by multiple decompition modules. .. autoclass:: pySecDec.decomposition.Sector .. autofunction:: pySecDec.decomposition.squash_symmetry_redundant_sectors_sort .. autofunction:: pySecDec.decomposition.squash_symmetry_redundant_sectors_dreadnaut Iterative ~~~~~~~~~ .. automodule:: pySecDec.decomposition.iterative :members: Geometric ~~~~~~~~~ .. automodule:: pySecDec.decomposition.geometric :members: Splitting ~~~~~~~~~ .. automodule:: pySecDec.decomposition.splitting :members: ''' from . import iterative, geometric, splitting from .common import *
mppmu/secdec
pySecDec/decomposition/__init__.py
Python
gpl-3.0
758
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE AS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa.Impl { /** * @author Taha BEN SALAH <taha.bensalah@gmail.com> * @creationdate 1/8/13 2:25 PM*/ internal class DefaultEntityPrivateAddItemInterceptor : Net.TheVpc.Upa.Impl.Util.ItemInterceptor<Net.TheVpc.Upa.EntityPart> { private Net.TheVpc.Upa.Impl.DefaultEntity defaultEntity; public DefaultEntityPrivateAddItemInterceptor(Net.TheVpc.Upa.Impl.DefaultEntity defaultEntity) { this.defaultEntity = defaultEntity; } public virtual void Before(Net.TheVpc.Upa.EntityPart item, int index) { Net.TheVpc.Upa.EntityPart oldParent = item.GetParent(); if (oldParent != null) { if (!(oldParent is Net.TheVpc.Upa.Section) && !(oldParent is Net.TheVpc.Upa.CompoundField)) { throw new System.ArgumentException ("Field Parent is neither a Field Section nor a Field"); } } defaultEntity.BeforePartAdded(null, item, index); if (oldParent != null) { if (oldParent is Net.TheVpc.Upa.Section) { Net.TheVpc.Upa.Section x = (Net.TheVpc.Upa.Section) oldParent; x.RemovePartAt(x.IndexOfPart(item)); } else if (oldParent is Net.TheVpc.Upa.CompoundField) { Net.TheVpc.Upa.CompoundField x = (Net.TheVpc.Upa.CompoundField) oldParent; ((Net.TheVpc.Upa.Impl.DefaultCompoundField) x).DropFieldAt(x.IndexOfField((Net.TheVpc.Upa.PrimitiveField) item)); } } // Net.TheVpc.Upa.Impl.Util.DefaultBeanAdapter a = new Net.TheVpc.Upa.Impl.Util.DefaultBeanAdapter(item); if (oldParent != null) { a.InjectNull("parent"); } a.SetProperty("entity", defaultEntity); } public virtual void After(Net.TheVpc.Upa.EntityPart item, int index) { defaultEntity.AfterPartAdded(null, item, index); } } }
thevpc/upa
upa-impl-core/src/main/csharp/Sources/Auto/DefaultEntityPrivateAddItemInterceptor.cs
C#
gpl-3.0
2,602
/* Copyright (C) 2014 Sergey Lamzin, https://github.com/sergeylamzin/stark This file is part of the StarK genome assembler. StarK 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. StarK 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ #ifndef STARK_STATUS_H #define STARK_STATUS_H #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <sys/syscall.h> struct stark_status_s { pthread_mutex_t mutex; // thread_pool_t threadpool; struct distributor_s * distributor; volatile struct stark_thread_status_s * stark_thread_status; struct stark_hierarchical_assembler_s * hierarchical_assembler; // stark_t * stark; size_t reads_total; }; struct stark_thread_status_s { volatile struct stark_thread_status_s * next; pthread_t thread_id; size_t reads_inserted; // const char* current_action; struct { char * seq4; size_t length; size_t maxk; } current_insert; size_t total_insert_mis; size_t total_insertions; int last_cpu; pid_t linux_tid; struct stark_coverage_mytoken_s * mytoken; struct stark_hierarchical_assembler_test_and_merge_groups_dispatch_s * volatile dispatch; char current_action[128]; }; int stark_status_init(uintptr_t port); void stark_status_kill(); void stark_status_register_thread(); // const char stark_status_action_waiting_for_jobs[] = "Waiting for Jobs."; // const char stark_status_action_waiting_for_barrier[] = "Waiting on Barrier Job."; extern const char stark_status_action_inserting_read[]; extern volatile struct stark_status_s stark_status; // #ifndef __MACH__ #define get_stark_thread_status() stark_thread_status // #else // static inline volatile struct stark_thread_status_s * get_stark_thread_status() { // volatile struct stark_thread_status_s * next; // for (next = stark_status.stark_thread_status; next; next = next->next) { // if (next->thread_id == pthread_self()) // return next; // } // return NULL; // } // #endif // #ifdef SYS_getcpu // static inline int getcpu() { // int cpu, status; // status = syscall(SYS_getcpu, &cpu, NULL, NULL); // return (status == -1) ? status : cpu; // } // // static inline void stark_status_update_last_cpu() { // if (get_stark_thread_status()) // get_stark_thread_status()->last_cpu = getcpu(); // } // #else // #define stark_status_update_last_cpu() // #endif // #define stark_set_status_action(...) if (get_stark_thread_status()) // snprintf((char *)(get_stark_thread_status()->current_action), sizeof(get_stark_thread_status()->current_action), __VA_ARGS__) #ifndef STARK_MAIN_STATUS_C #define STARK_MAIN_STATUS_C extern #endif STARK_MAIN_STATUS_C struct stark_thread_status_s * stark_thread_status; #pragma omp threadprivate(stark_thread_status) #include <stdarg.h> static inline void stark_set_status_action(const char *fmt, ...) { if (get_stark_thread_status()) { va_list args; va_start(args, fmt); vsnprintf((char *)(get_stark_thread_status()->current_action), sizeof(get_stark_thread_status()->current_action), fmt, args); va_end(args); } } // #endif // static inline void stark_set_status_action(const char * status) { // if (get_stark_thread_status()) { // // } // get_stark_thread_status()->current_action = status; // } #endif
sergeylamzin/stark
src/stark_status.h
C
gpl-3.0
3,770
while true do curl -s -u nova:$1 http://localhost:15672/api/queues/%2F/$2 | python -c 'import json,sys;obj=json.load(sys.stdin); print "%s %s" % (obj["message_stats"]["publish_details"]["rate"], obj["message_stats"]["deliver_get_details"]["rate"])' | sed "s/^/$(date '+%Y-%m-%d %H:%M:%S') /" sleep 5 done
f3flight/openstack-tools
rabbitmq/rabbitmq-metering-queue-details.sh
Shell
gpl-3.0
309
/******************************************************************************* Copyright ยฉ 2010 Didier Corbiere Distributable under the terms of the GNU Lesser General Public License, as specified in the LICENSE file. EntryTest.cpp *******************************************************************************/ #include "../Portability.hpp" #include "EntryTest.hpp" #include "UnitTestSuites.hpp" #include "../common/BinaryBuffer.hpp" #include "../util/Entry.hpp" //------------------------------------------------------------------------------ using namespace Atoll; using namespace Common; // Register test suite CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(EntryTest, Atoll::UnitTestSuites::Engine()); EntryTest::EntryTest() { } //------------------------------------------------------------------------------ EntryTest::~EntryTest() { } //------------------------------------------------------------------------------ void EntryTest::setUp(void) { } //------------------------------------------------------------------------------ void EntryTest::tearDown(void) { } //------------------------------------------------------------------------------ void EntryTest::testEmpty(void) { Entry e; CPPUNIT_ASSERT(e.IsEmpty()); e.Set(0, 0, 0); CPPUNIT_ASSERT(e.IsEmpty()); e.Set(0, 0, 1); CPPUNIT_ASSERT(e.IsEmpty() == false); e.Set(0, 1, 0); CPPUNIT_ASSERT(e.IsEmpty() == false); e.Set(1, 0, 0); CPPUNIT_ASSERT(e.IsEmpty() == false); } //------------------------------------------------------------------------------ void EntryTest::testDppMax(void) { CPPUNIT_ASSERT(DEF_IntMax == 0xffff); CPPUNIT_ASSERT(DEF_IntMax == 65535); CPPUNIT_ASSERT(DEF_LongMax == 0xffffffff); CPPUNIT_ASSERT(DEF_LongMax == 4294967295UL); // Unsigned long unsigned int uiTest = DEF_IntMax; CPPUNIT_ASSERT(uiTest == DEF_IntMax); unsigned long ulTest = DEF_LongMax; CPPUNIT_ASSERT(ulTest == DEF_LongMax); } //------------------------------------------------------------------------------ void EntryTest::testBinaryStorage(void) { Entry e1, e2; char buf[DEF_SizeOfEntry]; // Set entry and store it into the binary buffer e1.Set(DEF_IntMax, DEF_LongMax, DEF_LongMax); NotInlineEntryToBuf(buf, &e1); // Set new entry from the binary buffer e2.Set(0, 0, 0); NotInlineBufToEntry(buf, &e2); CPPUNIT_ASSERT(e2.mUiEntDoc == DEF_IntMax); CPPUNIT_ASSERT(e2.mUlEntPge == DEF_LongMax); CPPUNIT_ASSERT(e2.mUlEntPos == DEF_LongMax); } //------------------------------------------------------------------------------ void EntryTest::testStringStorage(void) { Entry e1, e2; char bufScan[DEF_SizeOfEntryScan]; // Set entry and store it into the string buffer e1.Set(DEF_IntMax, DEF_LongMax, DEF_LongMax); e1.ToStringDocPagePos(bufScan); // Set new entry from the string buffer e2.Set(0, 0, 0); e2.FromStringDocPagePos(bufScan); CPPUNIT_ASSERT(e2.mUiEntDoc == DEF_IntMax); CPPUNIT_ASSERT(e2.mUlEntPge == DEF_LongMax); CPPUNIT_ASSERT(e2.mUlEntPos == DEF_LongMax); CPPUNIT_ASSERT(strcmp(bufScan, "65535-4294967295-4294967295") == 0); } //------------------------------------------------------------------------------ void EntryTest::testEntryOperator(void) { Entry e1(1, 1, 1), e2; e2 = e1; CPPUNIT_ASSERT(e1 == e2); e2 = e1; e2.mUiEntDoc++; CPPUNIT_ASSERT(e1 < e2); e2 = e1; e2.mUlEntPge++; CPPUNIT_ASSERT(e1 < e2); e2 = e1; e2.mUlEntPos++; CPPUNIT_ASSERT(e1 < e2); } //------------------------------------------------------------------------------ void EntryTest::testEntrySet(void) { Entry e; EntrySet set1, set2; e.Set(1, 0, 0); set1.insert(e); e.Set(111, 222, 333); set1.insert(e); e.Set(DEF_IntMax, DEF_LongMax, DEF_LongMax); set1.insert(e); // Binary storage into flat buffer size_t dataSize; BinaryBuffer buffer; size_t nb1 = EntrySetToBuf(buffer, dataSize, set1); size_t nb2 = BufToEntrySet(set2, buffer.getBuffer(), buffer.getOccupancy(), NULL); size_t nb3 = GetBufEntrySetCount(buffer.getBuffer()); // Check the size of the sets CPPUNIT_ASSERT(nb1 == nb2); CPPUNIT_ASSERT(set1.size() == nb1); CPPUNIT_ASSERT(set2.size() == nb2); CPPUNIT_ASSERT(nb2 == nb3); // Check the content of the sets Entry e1, e2; EntrySet::iterator it1, it2; // Set iterator for (it1 = set1.begin(), it2 = set2.begin(); it1 != set1.end(); ++it1, ++it2) { e1 = (*it1); e2 = (*it2); CPPUNIT_ASSERT(e1 == e2); } // Check the binary storage of an empty set EntrySet set; EntrySetToBuf(buffer, dataSize, set); size_t nb = BufToEntrySet(set, buffer.getBuffer(), buffer.getOccupancy(), NULL); CPPUNIT_ASSERT(nb == 0); } //------------------------------------------------------------------------------
marsender/atoll-digital-library
src/unittest/EntryTest.cpp
C++
gpl-3.0
4,854
<?php if ( $posts->have_posts() ): extract($posts->info); $size = (!$img_size)? 'pergo-400x--nocrop' : $img_size; ?> <!-- PORTFOLIO IMAGES HOLDER --> <div class="row"> <div class="col-md-12"> <div class="grid" id="portfolio-grid"> <?php $count = 0; while ( $posts->have_posts() ) : $posts->the_post(); ?> <!-- IMAGE #1 --> <div class="grid-item grid-item--width1 grid-sizer portfolio-item"> <div class="hover-overlay"> <?php if( $link_type == 'link' ): ?> <a class="portfolio-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php else: ?> <!-- Image Zoom --> <a class="image-link" href="<?php the_post_thumbnail_url( 'full' ); ?>" title="<?php the_title_attribute(); ?>"> <?php endif; ?> <?php if( has_post_thumbnail() ): ?> <!-- Project Preview Image --> <img class="img-fluid" src="<?php the_post_thumbnail_url( $size ); ?>" alt="<?php the_title_attribute(); ?>" /> <?php endif; ?> <div class="item-overlay"></div> <!-- Project Description --> <div class="project-description white-color"> <!-- Project Meta --> <span class="<?php echo pergo_default_color() ?>-color"><?php echo pergo_get_the_term_list( get_the_ID(), 'portfolio_category', '', ', ', '', true ) ?></span> <!-- Project Link --> <h5 class="h5-sm"><?php the_title(); ?></h5> </div> </a> </div> </div> <!-- END IMAGE #1 --> <?php endwhile; ?> </div> </div> </div> <!-- END PORTFOLIO IMAGES HOLDER --> <?php // Posts not found else : echo '<h4>' . __( 'Portfolio not found', 'pergo' ) . '</h4>'; endif; ?>
beeznest/web
portfolio/isotope.php
PHP
gpl-3.0
1,791
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2016 Evan Debenham * * Lovecraft Pixel Dungeon * Copyright (C) 2016-2017 Leon Horn * * 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 eben the implied warranty of * GNU General Public License for more details. * * You should have have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses> */ package com.shatteredpixel.lovecraftpixeldungeon.sprites; import com.shatteredpixel.lovecraftpixeldungeon.Assets; import com.watabou.noosa.TextureFilm; public class PoorThiefSprite extends MobSprite { public PoorThiefSprite() { super(); texture( Assets.POORTHIEF ); TextureFilm film = new TextureFilm( texture, 12, 13 ); idle = new Animation( 1, true ); idle.frames( film, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); run = new Animation( 15, true ); run.frames( film, 0, 0, 2, 3, 3, 4 ); die = new Animation( 10, false ); die.frames( film, 5, 6, 7, 8, 9 ); attack = new Animation( 12, false ); attack.frames( film, 10, 11, 12, 0 ); idle(); } }
TypedScroll/Lovercraft.Pixel.Dungeon
core/src/main/java/com/shatteredpixel/lovecraftpixeldungeon/sprites/PoorThiefSprite.java
Java
gpl-3.0
1,462
#ifndef BUNKERBUILDER_SDL_H #define BUNKERBUILDER_SDL_H #include <string> #include <functional> #include <unordered_map> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL_ttf.h> #include <algorithm> #include "game.h" #include "utils.h" namespace bb { using namespace std; struct Button { SDL_Texture *texture; function<void(Button *self)> action; bool pressed = false; }; enum Command { COMMAND_SELECT = 0, COMMAND_STAIRCASE, COMMAND_CORRIDOR, COMMAND_MUSHROOM_FARM }; SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *selection_texture; unordered_map<StructureType, SDL_Texture *, EnumClassHash> textures; SDL_Texture *item_textures[NO_ITEM_TYPE]; SDL_Texture *sky; SDL_Texture *dwarf; SDL_Rect windowRect = {900, 300, 800, 1000}; TTF_Font *font; vector<Button *> buttons; Button *active_button = nullptr; Command active_command = COMMAND_SELECT; Point camera; double scale = 1; bool middle_down = false; int middle_down_x, middle_down_y; double last_scale = .5; int middle_down_time; StructureType fill_structure; set<Cell> toggled_cells; void SetScale(double new_scale) { int mx, my; SDL_GetMouseState(&mx, &my); int cx = camera.x + int(mx / scale); int cy = camera.y + int(my / scale); scale = clamp(new_scale, 0.1, 10.); camera.y = cy - int(my / scale); camera.x = cx - int(mx / scale); } SDL_Texture *LoadTexture(const string &filename) { SDL_Surface *surface = IMG_Load(filename.c_str()); if (surface == nullptr) { fprintf(stderr, "Failure while loading texture surface : %s\n", SDL_GetError()); return nullptr; } SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); if (texture == nullptr) { fprintf(stderr, "Failure while loading texture : %s\n", SDL_GetError()); return nullptr; } SDL_FreeSurface(surface); return texture; } void GetEffectiveSDL_Rect(const Dwarf &d, SDL_Rect *rect) { int w = 82; int h = 100; rect->x = (int) ((d.pos.x - w / 2 - camera.x) * scale); rect->y = (int) ((d.pos.y - h - camera.y) * scale); rect->w = int(w * scale); rect->h = int(h * scale); } void GetMouseCell(Cell *out) { int mx, my; SDL_GetMouseState(&mx, &my); *out = Cell(Point(camera.y + my / scale, camera.x + mx / scale)); } void TogglePlan(const Cell &c, StructureType structure_type) { auto it = plans.find(c); if (it != plans.end()) { bool the_same = it->second->structure_type == structure_type; delete it->second; plans.erase(it); if (the_same) return; } plans[c] = new Plan(structure_type); } bool InitTextures() { sky = LoadTexture("sky.png"); dwarf = LoadTexture("dwarf.gif"); textures[NONE] = LoadTexture("ground.png"); textures[STAIRCASE] = LoadTexture("staircase.png"); textures[CORRIDOR] = LoadTexture("corridor.png"); textures[MUSHROOM_FARM] = LoadTexture("mushroom_farm.png"); selection_texture = LoadTexture("block_selection.png"); buttons.clear(); for (auto p : initializer_list<pair<string, Command >> { { "btn_corridor.png", COMMAND_CORRIDOR}, { "btn_staircase.png", COMMAND_STAIRCASE}, { "btn_mushroom_farm.png", COMMAND_MUSHROOM_FARM} } ) { Button *b = new Button(); b->texture = LoadTexture(p.first); Command c = p.second; b->action = [c](Button *self) { if (active_button == self) { active_button = nullptr; active_command = COMMAND_SELECT; } else { active_button = self; active_command = c; } }; buttons.push_back(b); } for (int i = 0; i < NO_ITEM_TYPE; ++i) { item_textures[i] = LoadTexture(item_defs[i].texture_name); } TTF_Init(); font = TTF_OpenFont("./Katibeh-Regular.ttf", 24); if (!font) { fprintf(stderr, "TTF_OpenFont: %s\n", TTF_GetError()); return false; } return true; } bool InitRenderer() { if (renderer) SDL_DestroyRenderer(renderer); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr) { fprintf(stderr, "Failed to create renderer : %s\n", SDL_GetError()); return false; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); SDL_GetRendererOutputSize(renderer, &windowRect.w, &windowRect.h); SDL_SetRenderDrawColor(renderer, 64, 0, 0, 255); return InitTextures(); } bool HandleInput() { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) return false; else if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { case SDLK_ESCAPE: return false; default: windowRect.w += 100; //InitRenderer(); return true; } } else if (event.type == SDL_MOUSEBUTTONDOWN) { if (event.button.button == SDL_BUTTON_MIDDLE) { middle_down = true; middle_down_time = SDL_GetTicks(); middle_down_x = camera.x + int(event.button.x / scale); middle_down_y = camera.y + int(event.button.y / scale); } else if (event.button.button == SDL_BUTTON_LEFT) { if (event.button.x < 100) { int ind = event.button.y / 100; if (ind < buttons.size()) { Button *b = buttons[ind]; b->action(b); } } else { Cell c; GetMouseCell(&c); switch (active_command) { case COMMAND_STAIRCASE: fill_structure = STAIRCASE; break; case COMMAND_CORRIDOR: fill_structure = CORRIDOR; break; case COMMAND_MUSHROOM_FARM: fill_structure = MUSHROOM_FARM; break; default: break; } toggled_cells.insert(c); TogglePlan(c, fill_structure); } } } else if (event.type == SDL_MOUSEBUTTONUP) { if (event.button.button == SDL_BUTTON_MIDDLE) { middle_down = false; int time = SDL_GetTicks(); if (time - middle_down_time < 200) { if (scale == 1) { SetScale(last_scale); } else { last_scale = scale; SetScale(1); } } } else if (event.button.button == SDL_BUTTON_LEFT) { fill_structure = NONE; toggled_cells.clear(); } } else if (event.type == SDL_MOUSEMOTION) { if (middle_down) { camera.y = middle_down_y - int(event.motion.y / scale); camera.x = middle_down_x - int(event.motion.x / scale); } if (fill_structure != NONE) { Cell c; GetMouseCell(&c); if (toggled_cells.find(c) == toggled_cells.end()) { toggled_cells.insert(c); TogglePlan(c, fill_structure); } } } else if (event.type == SDL_MOUSEWHEEL) { SetScale(scale * exp2(event.wheel.y / 4.)); } else if (event.type == SDL_WINDOWEVENT) { switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: windowRect.w = event.window.data1; windowRect.h = event.window.data2; break; defualt: windowRect.w += 100;//= event.window.data1; windowRect.h += 100; //= event.window.data2; break; } } } return true; } SDL_Texture *GetTextureForStructureType(StructureType structure_type) { return textures[structure_type]; } SDL_Texture *GetTextureForCell(const Cell &cell) { auto it = cells.find(cell); if (it == cells.end()) { return cell.row <= 0 ? sky : textures[NONE]; } return GetTextureForStructureType(it->second->type); } void GetTileRect(int row, int col, SDL_Rect *out) { out->x = int((col * W - camera.x) * scale); out->y = int((row * H - camera.y) * scale); out->w = int(((col + 1) * W - camera.x) * scale) - out->x; out->h = int(((row + 1) * H - camera.y) * scale) - out->y; } struct Text { SDL_Texture *texture; SDL_Rect size; Text(const std::string &s, SDL_Color fg = {255, 255, 255, 0}, SDL_Color bg = {0, 0, 0, 0}) { int outline_width = 3; TTF_SetFontOutline(font, outline_width); SDL_Surface *surface_outer = TTF_RenderText_Blended(font, s.c_str(), bg); TTF_SetFontOutline(font, 0); SDL_Surface *surface_inner = TTF_RenderText_Blended(font, s.c_str(), fg); TTF_SizeText(font, s.c_str(), &size.w, &size.h); size.x = outline_width; size.y = outline_width; SDL_BlitSurface(surface_inner, NULL, surface_outer, &size); TTF_SetFontOutline(font, outline_width); TTF_SizeText(font, s.c_str(), &size.w, &size.h); TTF_SetFontOutline(font, 0); SDL_FreeSurface(surface_inner); SDL_Surface *surface = surface_outer; texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } virtual ~Text() { SDL_DestroyTexture(texture); } }; struct SaidText : Text { int time_said; SaidText(const string &s, const SDL_Color &fg, const SDL_Color &bg) : Text(s, fg, bg), time_said(SDL_GetTicks()) { } }; map<Dwarf *, deque<SaidText *>> said_texts; map<Dwarf *, Text *> name_texts; Text* GetMoneyText() { static int last_money = money; static Text* money_text = new Text('$' + FormatWithCommas(money), {128,255,128,0}, {64, 128, 64, 0}); return money_text; } void Draw() { SDL_RenderClear(renderer); SDL_Rect tile_rect; int left = int(camera.x + 100 / scale); int right = left + int(windowRect.w / scale); int top = camera.y; int bottom = top + int(windowRect.h / scale); Cell top_left = Cell(Point(top, left)); Cell bottom_right = Cell(Point(bottom, right)); // Draw cells & plans for (int row = top_left.row; row <= bottom_right.row; ++row) { for (int col = top_left.col; col <= bottom_right.col; ++col) { Cell cell = {row, col}; SDL_Texture *texture = GetTextureForCell(cell); GetTileRect(row, col, &tile_rect); SDL_RenderCopy(renderer, texture, nullptr, &tile_rect); auto it = plans.find(cell); if (it != plans.end()) { int orig_h = tile_rect.h; tile_rect.h *= 1 - it->second->progress; SDL_Rect source_rect = {0, 0, W, int(H * (1 - it->second->progress))}; SDL_Texture *structure_texture = GetTextureForStructureType(it->second->structure_type); SDL_SetTextureAlphaMod(structure_texture, 64); SDL_SetTextureBlendMode(structure_texture, SDL_BLENDMODE_BLEND); SDL_RenderCopy(renderer, structure_texture, &source_rect, &tile_rect); SDL_SetTextureBlendMode(structure_texture, SDL_BLENDMODE_NONE); source_rect.y = source_rect.h; source_rect.h = H - source_rect.h; tile_rect.y += tile_rect.h; tile_rect.h = orig_h - tile_rect.h; SDL_RenderCopy(renderer, structure_texture, &source_rect, &tile_rect); tile_rect.h = orig_h; //SDL_SetTextureAlphaMod(structure_texture, 255); } } } // Draw dwarves for (Dwarf *d:dwarves) { SDL_Rect r; GetEffectiveSDL_Rect(*d, &r); SDL_RenderCopy(renderer, dwarf, nullptr, &r); } // Draw items for (int row = top_left.row; row <= bottom_right.row; ++row) { for (int col = top_left.col; col <= bottom_right.col; ++col) { Cell cell = {row, col}; auto range = items.equal_range(cell); for (auto it = range.first; it != range.second; ++it) { SDL_Rect rect; rect.x = it->second->pos.x; rect.y = it->second->pos.y; rect.w = it->second->def->w; rect.h = it->second->def->h; SDL_RenderCopy(renderer, item_textures[it->second->def->type], nullptr, &rect); } } } // Draw text bubbles & interface for (Dwarf *d:dwarves) { SDL_Rect r; GetEffectiveSDL_Rect(*d, &r); Text *name_texture = name_texts[d]; name_texture->size.x = r.x + r.w / 2 - name_texture->size.w / 2; name_texture->size.y = r.y - name_texture->size.h; SDL_RenderCopy(renderer, name_texture->texture, nullptr, &name_texture->size); int y = name_texture->size.y; auto &said = said_texts[d]; int now = SDL_GetTicks(); while (!said.empty() && (now - said.front()->time_said > 5000)) { delete said.front(); said.pop_front(); } for (SaidText *said_text : said) { said_text->size.x = r.x + r.w / 2 - said_text->size.w / 2; said_text->size.y = y - said_text->size.h; y -= said_text->size.h; SDL_RenderCopy(renderer, said_text->texture, nullptr, &said_text->size); } } Text* money_text = GetMoneyText(); money_text->size.x = 110; money_text->size.y = 10; SDL_RenderCopy(renderer, money_text->texture, nullptr, &money_text->size); // Draw plan selection marker if (active_command != COMMAND_SELECT) { Cell c; GetMouseCell(&c); GetTileRect(c.row, c.col, &tile_rect); SDL_RenderCopy(renderer, selection_texture, nullptr, &tile_rect); } // Draw buttons SDL_Rect button_rect{ 0, 0, 100, 100}; for (int i = 0; i < buttons.size(); ++i) { button_rect.y = i * 100; if (buttons[i] == active_button) { SDL_SetTextureColorMod(buttons[i]->texture, 128, 128, 128); } else { SDL_SetTextureColorMod(buttons[i]->texture, 255, 255, 255); } SDL_RenderCopy(renderer, buttons[i]->texture, nullptr, &button_rect); } SDL_RenderPresent(renderer); } bool Init() { if (SDL_Init(SDL_INIT_EVERYTHING) == -1) { fprintf(stderr, "Failed to initialize SDL : %s\n", SDL_GetError()); return false; } window = SDL_CreateWindow("Server", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowRect.w, windowRect.h, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (window == nullptr) { fprintf(stderr, "Failed to create window : %s\n", SDL_GetError()); return false; } dwarf_created.handlers.push_back([](Dwarf *dwarf) { name_texts[dwarf] = new Text(dwarf->name, {150, 255, 150, 0}, {20, 60, 20, 0}); dwarf->said_something.handlers.push_back([dwarf](string *s) { said_texts[dwarf].push_back(new SaidText(*s, {230, 230, 230, 0}, {60, 60, 60, 0})); }); }); if (!InitRenderer()) return false; return true; } } #endif //BUNKERBUILDER_SDL_BASE_H
mafik/bunker-builder
sdl.h
C
gpl-3.0
14,191
/* * Copyright (c) 2010 The Jackson Laboratory * * This 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. */ package org.jax.util.gui; import java.util.List; import javax.swing.tree.DefaultMutableTreeNode; /** * A tree node type for representing a list of subitems * @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A> * @param <E> the list element type */ public class ListTreeNode<E> extends DefaultMutableTreeNode { /** * every {@link java.io.Serializable} is supposed to have one of these */ private static final long serialVersionUID = 9031914890413713919L; private final String name; /** * Constructor * @param name * the name to use * @param list * the list */ public ListTreeNode( String name, List<E> list) { super(list); this.setAllowsChildren(true); this.name = name; } /** * Get the list which is just a typecast version of {@link #getUserObject()} * @return * the list */ @SuppressWarnings("unchecked") public List<E> getList() { return (List<E>)this.getUserObject(); } /** * Getter for the name * @return the name */ public String getName() { return this.name; } /** * {@inheritDoc} */ @Override public String toString() { List<E> list = this.getList(); StringBuffer sb = new StringBuffer(this.getName()); sb.append(" ("); if(list.isEmpty()) { sb.append("empty"); } else { sb.append(list.size()); } sb.append(")"); return sb.toString(); } }
cgd/java-util
src/java/org/jax/util/gui/ListTreeNode.java
Java
gpl-3.0
2,388
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> Uses of Class com.google.gwt.editor.ui.client.ValueBoxEditorDecorator (Google Web Toolkit Javadoc) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.google.gwt.editor.ui.client.ValueBoxEditorDecorator (Google Web Toolkit Javadoc)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../com/google/gwt/editor/ui/client/ValueBoxEditorDecorator.html" title="class in com.google.gwt.editor.ui.client"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> GWT 2.4.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?com/google/gwt/editor/ui/client//class-useValueBoxEditorDecorator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ValueBoxEditorDecorator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.google.gwt.editor.ui.client.ValueBoxEditorDecorator</B></H2> </CENTER> No usage of com.google.gwt.editor.ui.client.ValueBoxEditorDecorator <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../com/google/gwt/editor/ui/client/ValueBoxEditorDecorator.html" title="class in com.google.gwt.editor.ui.client"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> GWT 2.4.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?com/google/gwt/editor/ui/client//class-useValueBoxEditorDecorator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ValueBoxEditorDecorator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
dandrocec/PaaSInterop
SemanticCloudClient/build/web/WEB-INF/lib/doc/javadoc/com/google/gwt/editor/ui/client/class-use/ValueBoxEditorDecorator.html
HTML
gpl-3.0
6,133
/* * * Copyright (C) 2009-2010 IPB Halle, Sebastian Wolf * * Contact: swolf@ipb-halle.de * * 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, see <http://www.gnu.org/licenses/>. * */ package de.ipbhalle.metfusion.integration.Similarity; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openscience.cdk.DefaultChemObjectBuilder; import org.openscience.cdk.exception.CDKException; import org.openscience.cdk.exception.InvalidSmilesException; import org.openscience.cdk.fingerprint.ExtendedFingerprinter; import org.openscience.cdk.fingerprint.Fingerprinter; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IMolecule; import org.openscience.cdk.isomorphism.UniversalIsomorphismTester; import org.openscience.cdk.similarity.Tanimoto; import org.openscience.cdk.smiles.SmilesParser; public class Similarity { private float[][] matrix = null; private Map<String, IAtomContainer> candidateToStructure = null; private Map<String, Integer> candidateToPosition = null; private Map<String, String> candidatesToSmiles = null; private StringBuilder allSimilarityValues = new StringBuilder(); private float similarityThreshold; private boolean hasAtomContainer = false; public Similarity(Map<String,String> candidatesToSmiles, float similarityThreshold) throws CDKException { matrix = new float[candidatesToSmiles.size()][candidatesToSmiles.size()]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { matrix[i][j] = Float.MIN_VALUE; } } this.candidateToStructure = new HashMap<String, IAtomContainer>(candidatesToSmiles.size()); this.similarityThreshold = similarityThreshold; this.candidatesToSmiles = candidatesToSmiles; initializePositions(); calculateSimilarity(similarityThreshold); } public Similarity(Map<String, IAtomContainer> candidateToStructure, float similarityThreshold, boolean check) throws CDKException { matrix = new float[candidateToStructure.size()][candidateToStructure.size()]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { matrix[i][j] = Float.MIN_VALUE; } } this.candidateToStructure = candidateToStructure; this.similarityThreshold = similarityThreshold; this.hasAtomContainer = check; initializePositions(); calculateSimilarity(similarityThreshold); } //initialize the position of the candidates in the matrix private void initializePositions() { int i = 0; candidateToPosition = new HashMap<String, Integer>(); if(hasAtomContainer) { for (String candidate : candidateToStructure.keySet()) { candidateToPosition.put(candidate, i); i++; } } else { for (String candidate : candidatesToSmiles.keySet()) { candidateToPosition.put(candidate, i); i++; } } } /** * Returns a similarity matrix based on the tanimoto distance * of the fingerprints. (Upper triangular matrix) * * @param molList the mol list * @param similarityThreshold the similarity threshold * * @return the float[][] * * @throws CDKException the CDK exception */ private float[][] calculateSimilarity(float similarityThreshold) throws CDKException { Map<String, BitSet> candidateToFingerprint = new HashMap<String, BitSet>(); if(hasAtomContainer) { for (String strCandidate : candidateToStructure.keySet()) { Fingerprinter f = new Fingerprinter(); //ExtendedFingerprinter f = new ExtendedFingerprinter(); BitSet fp = f.getFingerprint(candidateToStructure.get(strCandidate)); candidateToFingerprint.put(strCandidate, fp); } } else { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); for (String string : candidatesToSmiles.keySet()) { try { IMolecule mol = sp.parseSmiles(candidatesToSmiles.get(string)); Fingerprinter f = new Fingerprinter(); //ExtendedFingerprinter f = new ExtendedFingerprinter(); BitSet fp = f.getFingerprint(mol); candidateToFingerprint.put(string, fp); } catch(Exception e) { System.err.println("Error in smiles!" + e.getMessage()); } } } int countJ = 0; int countI = 0; if(!hasAtomContainer) { for (String candidate1 : candidatesToSmiles.keySet()) { for (String candidate2 : candidatesToSmiles.keySet()) { if(countJ < countI || candidate1.equals(candidate2)) { countJ++; continue; } float similarity = compareFingerprints(candidateToFingerprint.get(candidate1), candidateToFingerprint.get(candidate2)); matrix[countI][countJ] = similarity; countJ++; } countJ = 0; countI++; } } else { for (String candidate1 : candidateToStructure.keySet()) { for (String candidate2 : candidateToStructure.keySet()) { if(countJ < countI || candidate1.equals(candidate2)) { countJ++; continue; } float similarity = compareFingerprints(candidateToFingerprint.get(candidate1), candidateToFingerprint.get(candidate2)); matrix[countI][countJ] = similarity; countJ++; } countJ = 0; countI++; } } return matrix; } /** * Gets the all similarity values. * * @return the all similarity values */ public StringBuilder getAllSimilarityValues() { return allSimilarityValues; } /** * Gets the tanimoto distance between two candidate structures. * * @param candidate1 the candidate1 * @param candidate2 the candidate2 * * @return the tanimoto distance */ public float getTanimotoDistance(String candidate1, String candidate2) { int pos1 = 0; int pos2 = 0; try { pos1 = candidateToPosition.get(candidate1); pos2 = candidateToPosition.get(candidate2); } catch(NullPointerException e) { return 0; } if(matrix[pos1][pos2] != Float.MIN_VALUE) return matrix[pos1][pos2]; else return matrix[pos2][pos1]; } /** * Gets the tanimoto distance from a list of candidates and groups them!. * * @param candidateGroup the candidate group * @param threshold the threshold * * @return the tanimoto distance list */ public List<SimilarityGroup> getTanimotoDistanceList(List<String> candidateGroup) { List<SimilarityGroup> groupedCandidates = new ArrayList<SimilarityGroup>(); for (String cand1 : candidateGroup) { SimilarityGroup simGroup = new SimilarityGroup(cand1); for (String cand2 : candidateGroup) { if(cand1.equals(cand2)) continue; else if(cand1 == null || cand2 == null) continue; else { Float tanimoto = getTanimotoDistance(cand1, cand2); if(tanimoto > similarityThreshold) simGroup.addSimilarCompound(cand2, tanimoto); } } //now add similar compound to the group list //if(!isContainedInPreviousResults(groupedCandidates, simGroup)) groupedCandidates.add(simGroup); } groupedCandidates = cleanList(groupedCandidates); return groupedCandidates; } /** * Checks if is identical. * * @param similar1 the similar1 * @param similar2 the similar2 * * @return true, if is identical */ private boolean isIdentical(List<String> similar1, List<String> similar2) { String[] candidatesToCompare = new String[similar1.size()]; candidatesToCompare = similar1.toArray(candidatesToCompare); Arrays.sort(candidatesToCompare); boolean isAlreadyContained = false; String[] candidateListTemp = new String[similar2.size()]; candidateListTemp = similar2.toArray(candidateListTemp); Arrays.sort(candidateListTemp); if(Arrays.equals(candidatesToCompare, candidateListTemp)) { isAlreadyContained = true; } return isAlreadyContained; } /** * Removes the duplicates. * * @param groupedCandidates the grouped candidates * * @return the list< similarity group> */ private List<SimilarityGroup> removeDuplicates(List<SimilarityGroup> groupedCandidates) { List<SimilarityGroup> toRemove = new ArrayList<SimilarityGroup>(); if(groupedCandidates.size() == 1) return groupedCandidates; else { for (SimilarityGroup simGroup1 : groupedCandidates) { if(toRemove.contains(simGroup1)) continue; String[] candidatesToCompare = new String[simGroup1.getSimilarCandidatesWithBase().size()]; candidatesToCompare = simGroup1.getSimilarCandidatesWithBase().toArray(candidatesToCompare); Arrays.sort(candidatesToCompare); for (SimilarityGroup simGroup2 : groupedCandidates) { if(simGroup1.equals(simGroup2) || toRemove.contains(simGroup2)) continue; List<String> temp = simGroup2.getSimilarCandidatesWithBase(); String[] candidateListTemp = new String[temp.size()]; candidateListTemp = simGroup2.getSimilarCandidatesWithBase().toArray(candidateListTemp); Arrays.sort(candidateListTemp); if(Arrays.equals(candidatesToCompare, candidateListTemp)) toRemove.add(simGroup2); } } for (SimilarityGroup simGroup : toRemove) { groupedCandidates.remove(simGroup); } return groupedCandidates; } } /** * Cleans list: remove transitive relations * Only the largest sets are used * * @param groupedCandidates the grouped candidates * * @return the list< similarity group> */ private List<SimilarityGroup> cleanList(List<SimilarityGroup> groupedCandidates) { List<SimilarityGroup> cleanedList = new ArrayList<SimilarityGroup>(); List<SimilarityGroup> alreadyRemoved = new ArrayList<SimilarityGroup>(); Map<String, List<String>> candidatesToCompareMapBase = new HashMap<String, List<String>>(); Map<String, SimilarityGroup> candidatesToCompareMap = new HashMap<String, SimilarityGroup>(); for (SimilarityGroup simGroup : groupedCandidates) { candidatesToCompareMap.put(simGroup.getCandidateTocompare(), simGroup); candidatesToCompareMapBase.put(simGroup.getCandidateTocompare(), simGroup.getSimilarCandidatesWithBase()); } if(groupedCandidates.size() == 1) cleanedList = groupedCandidates; else { //initialize with one value cleanedList.add(groupedCandidates.get(0)); for (String key1 : candidatesToCompareMap.keySet()) { for (String key2 : candidatesToCompareMap.keySet()) { if(key1.equals(key2)) continue; List<String> similar1 = candidatesToCompareMapBase.get(key1); List<String> similar2 = candidatesToCompareMapBase.get(key2); if(isIdentical(similar1, similar2)) { continue; } if(similar1.size() > similar2.size() && similar1.containsAll(similar2)) { cleanedList.remove(candidatesToCompareMap.get(key2)); alreadyRemoved.add(candidatesToCompareMap.get(key2)); } else if(similar2.containsAll(similar1)) { cleanedList.remove(candidatesToCompareMap.get(key1)); alreadyRemoved.add(candidatesToCompareMap.get(key1)); } else { if(!cleanedList.contains(candidatesToCompareMap.get(key2)) && !alreadyRemoved.contains(candidatesToCompareMap.get(key2))) cleanedList.add(candidatesToCompareMap.get(key2)); if(!cleanedList.contains(candidatesToCompareMap.get(key1)) && !alreadyRemoved.contains(candidatesToCompareMap.get(key1))) cleanedList.add(candidatesToCompareMap.get(key1)); } } } cleanedList = removeDuplicates(cleanedList); } return cleanedList; } /** * Checks if the given structures are isomorph. * * @param candidate1 the candidate1 * @param candidate2 the candidate2 * * @return true, if is isomorph * * @throws CDKException the CDK exception */ public boolean isIsomorph(String candidate1, String candidate2) throws CDKException { IAtomContainer cand1 = null; IAtomContainer cand2 = null; if(hasAtomContainer) { cand1 = this.candidateToStructure.get(candidate1); cand2 = this.candidateToStructure.get(candidate2); } else { SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); cand1 = sp.parseSmiles(candidatesToSmiles.get(candidate1)); cand2 = sp.parseSmiles(candidatesToSmiles.get(candidate2)); } return UniversalIsomorphismTester.isIsomorph(cand1, cand2); } /** * Compare fingerprints by returning the Tanimoto distance. * * @param bitSet1 the bit set1 * @param bitSet2 the bit set2 * * @return the float * * @throws CDKException the CDK exception */ private float compareFingerprints(BitSet bitSet1, BitSet bitSet2) throws CDKException { return Tanimoto.calculate(bitSet1, bitSet2); } public static void main(String[] args) { //SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); try { String mol = "C1CCC(C1)(C(=O)O)N"; String mol1 = "CCC1CC1(C(=O)O)N"; // String mol2 = "C1C(OC(=O)C2=C(C=C(C=C21)O)O)C3=CC=C(C=C3)O"; // String mol3 = "C1C(OC2=CC(=CC(=C2C1=O)O)O)C3=CC=C(C=C3)O"; // String mol4 = "C1C(OC2=CC(=CC(=C2C1=O)O)O)C3=CC=C(C=C3)O"; // String mol5 = "C1C(OC2=CC(=CC(=C2C1=O)O)O)C3=CC(=CC=C3)O"; // String mol6 = "C1C(OC2=CC(=C(C=C2C1=O)O)O)C3=CC=C(C=C3)O"; // String mol7 = "C1C(OC2=CC(=CC(=C2C1=O)O)O)C3=CC=CC=C3O"; // String mol8 = "C1C(C(=O)C2=CC(=C(C=C2O1)O)O)C3=CC=C(C=C3)O"; Map<String, String> testMap = new HashMap<String, String>(); testMap.put("2901", mol); testMap.put("133485", mol1); // testMap.put("10333412", mol2); // testMap.put("439246", mol3); // testMap.put("667495", mol4); // testMap.put("113638", mol5); // testMap.put("23724670", mol6); // testMap.put("13889010", mol7); // testMap.put("125100", mol8); List<String> cands = new ArrayList<String>(); cands.add("2901"); cands.add("133485"); // cands.add("10333412"); // cands.add("439246"); // cands.add("667495"); // cands.add("113638"); // cands.add("23724670"); // cands.add("13889010"); // cands.add("125100"); Similarity sim = new Similarity(testMap, 0.95f); // System.out.println(sim.getTanimotoDistance("cand3", "cand1")); List<SimilarityGroup> groupedCandidates = sim.getTanimotoDistanceList(cands); for (SimilarityGroup similarityGroup : groupedCandidates) { if(similarityGroup.getSimilarCompounds().size() == 0) System.out.print("Single: " + similarityGroup.getCandidateTocompare() + "\n"); else { System.out.print("Group of " + similarityGroup.getSimilarCompounds().size() + " " + similarityGroup.getCandidateTocompare() + ": "); for (int i = 0; i < similarityGroup.getSimilarCompounds().size(); i++) { System.out.print(similarityGroup.getSimilarCompounds().get(i) + "(" + similarityGroup.getSimilarCompoundsTanimoto().get(i) + ") "); } System.out.println(""); } } } catch (InvalidSmilesException e) { System.err.println("InvalidSmiles Exception occured!"); e.printStackTrace(); } catch (CDKException e) { System.err.println("CDK Exception occured!"); e.printStackTrace(); } } }
mgerlich/MetFusion
src/main/java/de/ipbhalle/metfusion/integration/Similarity/Similarity.java
Java
gpl-3.0
15,598
/* * AbstractWindow.java * Copyright 2008-2015 Gamegineer contributors and others. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License 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, see <http://www.gnu.org/licenses/>. * * Created on Sep 11, 2010 at 2:56:08 PM. */ package org.gamegineer.common.ui.window; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import javax.swing.JPanel; import net.jcip.annotations.NotThreadSafe; import org.eclipse.jdt.annotation.Nullable; import org.gamegineer.common.ui.util.Geometry; /** * Superclass for all windows. * * @param <T> * The type of the window shell. */ @NotThreadSafe public abstract class AbstractWindow<T extends Window> { // ====================================================================== // Fields // ====================================================================== /** The window content. */ private @Nullable Component content_; /** The window parent shell. */ private @Nullable Window parentShell_; /** The window return code. */ private int returnCode_; /** The window shell. */ private @Nullable T shell_; // ====================================================================== // Constructors // ====================================================================== /** * Initializes a new instance of the {@code AbstractWindow} class. * * @param parentShell * The parent shell or {@code null} to create a top-level shell. */ protected AbstractWindow( final @Nullable Window parentShell ) { content_ = null; parentShell_ = parentShell; returnCode_ = WindowConstants.RETURN_CODE_OK; shell_ = null; } // ====================================================================== // Methods // ====================================================================== /** * Closes the window. * * @return {@code true} if the window was closed; {@code false} if the * window is still open. */ public boolean close() { final @Nullable T shell = shell_; if( (shell == null) || !shell.isDisplayable() ) { return true; } shell.dispose(); shell_ = null; content_ = null; return true; } /** * Configures the specified shell before opening the window. * * <p> * This implementation sets the layout of the shell. * </p> * * @param shell * The shell. */ protected void configureShell( final T shell ) { final LayoutManager layout = getLayout(); if( layout != null ) { shell.setLayout( layout ); } } /** * Constrains the shell size to be no larger than the display size. */ private void constrainShellSize() { final @Nullable T shell = shell_; assert shell != null; final Rectangle bounds = shell.getBounds(); final Rectangle constrainedBounds = getConstrainedBounds( bounds ); if( !bounds.equals( constrainedBounds ) ) { shell.setBounds( constrainedBounds ); } } /** * Invoked after the window content has been created. * * <p> * This implementation does nothing. * </p> */ protected void contentCreated() { // do nothing } /** * Invoked after the window content has been realized. * * <p> * This implementation does nothing. * </p> */ protected void contentRealized() { // do nothing } /** * Creates the window. */ public final void create() { final T shell = createShell( getParentShell() ); shell_ = shell; configureShell( shell ); content_ = createContent( shell ); contentCreated(); shell.pack(); contentRealized(); initializeBounds(); } /** * Creates the window content. * * <p> * This implementation creates a panel. * </p> * * @param parent * The parent container for all content. * * @return The window content. */ protected Component createContent( final Container parent ) { final Component content = new JPanel(); parent.add( content ); return content; } /** * Creates the window shell. * * @param parent * The parent shell or {@code null} to create a top-level shell. * * @return The window shell. */ protected abstract T createShell( final @Nullable Window parent ); /** * Adjusts the specified preferred bounds so that they do not extend beyond * the display bounds. * * @param preferredBounds * The preferred bounds. * * @return The adjusted bounds that are as close to the preferred bounds as * possible without extending beyond the display bounds. */ private static Rectangle getConstrainedBounds( final Rectangle preferredBounds ) { final Rectangle bounds = new Rectangle( preferredBounds ); final Rectangle displayBounds = new Rectangle( new Point( 0, 0 ), Toolkit.getDefaultToolkit().getScreenSize() ); if( bounds.width > displayBounds.width ) { bounds.width = displayBounds.width; } if( bounds.height > displayBounds.height ) { bounds.height = displayBounds.height; } bounds.x = Math.max( displayBounds.x, Math.min( bounds.x, displayBounds.x + displayBounds.width - bounds.width ) ); bounds.y = Math.max( displayBounds.y, Math.min( bounds.y, displayBounds.y + displayBounds.height - bounds.height ) ); return bounds; } /** * Get the window content. * * @return The window content or {@code null} if the window content has not * yet been created. */ protected final @Nullable Component getContent() { return content_; } /** * Gets the initial location of shell. * * <p> * This implementation centers the shell horizontally (1/2 to the left and * 1/2 to the right) and vertically (1/3 above and 2/3 below) relative to * the parent shell or the display bounds if there is no parent shell. * </p> * * @param initialSize * The initial size of the shell. * * @return The initial location of the shell. */ protected Point getInitialLocation( final Dimension initialSize ) { final @Nullable T shell = shell_; assert shell != null; final Container parent = shell.getParent(); final Rectangle displayBounds = new Rectangle( new Point( 0, 0 ), Toolkit.getDefaultToolkit().getScreenSize() ); final Point centerPoint = Geometry.calculateCenterPoint( (parent != null) ? parent.getBounds() : displayBounds ); return new Point( // centerPoint.x - (initialSize.width / 2), // Math.max( displayBounds.y, Math.min( centerPoint.y - (initialSize.height * 2 / 3), displayBounds.y + displayBounds.height - initialSize.height ) ) ); } /** * Gets the initial size of the shell. * * <p> * This implementation returns the preferred size of the shell. * </p> * * @return The initial size of the shell. */ protected Dimension getInitialSize() { final @Nullable T shell = shell_; assert shell != null; return shell.getPreferredSize(); } /** * Gets the layout for the shell. * * <p> * This implementation returns an instance of {@link BorderLayout}. * </p> * * @return The layout for the shell or {@code null} if no layout should be * associated with the shell. */ protected @Nullable LayoutManager getLayout() { return new BorderLayout(); } /** * Gets the window parent shell. * * @return The window parent shell or {@code null} if the window has no * parent shell. */ protected final @Nullable Window getParentShell() { return parentShell_; } /** * Gets the window return code. * * @return The window return code. */ public final int getReturnCode() { return returnCode_; } /** * Gets the window shell. * * @return The window shell or {@code null} if the window shell has not yet * been created. */ public final @Nullable T getShell() { return shell_; } /** * Initializes the bounds of the window shell. */ private void initializeBounds() { final Dimension size = getInitialSize(); final Point location = getInitialLocation( size ); final Rectangle bounds = getConstrainedBounds( new Rectangle( location, size ) ); final @Nullable T shell = shell_; assert shell != null; shell.setBounds( bounds ); shell.setPreferredSize( bounds.getSize() ); } /** * Opens the window, creating it first if necessary. * * @return The window return code. */ public final int open() { @Nullable T shell = shell_; if( (shell == null) || !shell.isDisplayable() ) { shell = shell_ = null; create(); shell = shell_; assert shell != null; } constrainShellSize(); shell.setVisible( true ); return returnCode_; } /** * Sets the window return code. * * @param returnCode * The window return code. */ protected final void setReturnCode( final int returnCode ) { returnCode_ = returnCode; } }
gamegineer/dev
main/common/org.gamegineer.common.ui/src/org/gamegineer/common/ui/window/AbstractWindow.java
Java
gpl-3.0
11,104
๏ปฟ'============================================================================== ' ' EveHQ - An Eve-Onlineโ„ข character assistance application ' Copyright ยฉ 2005-2015 EveHQ Development Team ' ' This file is part of EveHQ. ' ' The source code for EveHQ is free and you may redistribute ' it and/or modify it under the terms of the MIT License. ' ' Refer to the NOTICES file in the root folder of EVEHQ source ' project for details of 3rd party components that are covered ' under their own, separate licenses. ' ' EveHQ 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 MIT ' license below for details. ' ' ------------------------------------------------------------------------------ ' ' The MIT License (MIT) ' ' Copyright ยฉ 2005-2015 EveHQ Development Team ' ' 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. ' ' ============================================================================== Imports DevComponents.AdvTree Imports EveHQ.EveApi Imports EveHQ.Core Imports DevComponents.DotNetBar Imports System.Globalization Imports System.Xml Imports EveHQ.Common.Extensions Namespace Controls.DBControls Public Class DBCLastTransactions ReadOnly _styleRed As New ElementStyle ReadOnly _styleRedRight As New ElementStyle ReadOnly _styleGreen As New ElementStyle ReadOnly _styleGreenRight As New ElementStyle ReadOnly _culture As CultureInfo = New CultureInfo("en-GB") Public Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() ControlConfigForm = "EveHQ.Controls.DBConfigs.DBCLasttransactionConfig" ControlConfigInfo = "Last transaction description" 'populate Pilot ComboBox cboPilotList.BeginUpdate() cboPilotList.Items.Clear() For Each pilot As EveHQPilot In HQ.Settings.Pilots.Values If pilot.Active = True And pilot.Account <> "" Then cboPilotList.Items.Add(pilot.Name) End If Next cboPilotList.EndUpdate() ' Create the styles _styleRed = adtLastTransactions.Styles("ElementStyle1").Copy _styleRed.TextColor = Color.Red _styleRedRight = adtLastTransactions.Styles("ElementStyle1").Copy _styleRedRight.TextColor = Color.Red _styleRedRight.TextAlignment = eStyleTextAlignment.Far _styleGreen = adtLastTransactions.Styles("ElementStyle1").Copy _styleGreen.TextColor = Color.DarkGreen _styleGreenRight = adtLastTransactions.Styles("ElementStyle1").Copy _styleGreenRight.TextColor = Color.DarkGreen _styleGreenRight.TextAlignment = eStyleTextAlignment.Far End Sub Public Overrides ReadOnly Property ControlName() As String Get Return "Last Transactions" End Get End Property Dim _dbcDefaultPilotName As String = "" Public Property DBCDefaultPilotName() As String Get Return _dbcDefaultPilotName End Get Set(ByVal value As String) _dbcDefaultPilotName = value cboPilotList.SelectedItem = value If ReadConfig = False Then SetConfig("DBCDefaultPilotName", value) SetConfig("ControlConfigInfo", "Default Pilot: " & DBCDefaultPilotName.ToString & ", Transactions: " & DBCDefaultTransactionsCount.ToString) End If End Set End Property Dim _dbcDefaultTransactionsCount As Integer = 10 Public Property DBCDefaultTransactionsCount() As Integer Get Return _dbcDefaultTransactionsCount End Get Set(ByVal value As Integer) _dbcDefaultTransactionsCount = value If ReadConfig = False Then SetConfig("DBCDefaultTransactionsCount", value) SetConfig("ControlConfigInfo", "Default Pilot: " & DBCDefaultPilotName.ToString & ", Transactions: " & DBCDefaultTransactionsCount.ToString) End If ' This will update the transactions nudEntries.Value = value End Set End Property Private Sub UpdateTransactions() If cboPilotList.SelectedItem IsNot Nothing Then 'Get transactions XML Dim numTransactionsDisplay As Integer = nudEntries.Value ' how much transactions to display in listview/ Dim cPilot As EveHQPilot = HQ.Settings.Pilots(cboPilotList.SelectedItem.ToString) Dim cAccount As EveHQAccount = HQ.Settings.Accounts(cPilot.Account) Dim cCharID As String = cPilot.ID Const AccountKey As Integer = 1000 Const BeforeRefID As String = "" 'Dim apiReq As New EveAPIRequest(HQ.EveHQAPIServerInfo, HQ.RemoteProxy, HQ.Settings.APIFileExtension, HQ.ApiCacheFolder) 'transactionsXML = apiReq.GetAPIXML(APITypes.WalletTransChar, cAccount.ToAPIAccount, cCharID, accountKey, beforeRefID, APIReturnMethods.ReturnStandard) Dim transactions = HQ.ApiProvider.Character.WalletTransactions(cAccount.UserID, cAccount.APIKey, cCharID.ToInt32(), AccountKey) 'Parse the XML document If transactions.IsSuccess Then ' Get transactions Dim transactionList = transactions.ResultData Dim sortedTransactions As List(Of WalletTransaction) = transactionList.ToList() adtLastTransactions.BeginUpdate() adtLastTransactions.Nodes.Clear() For currentTransactionCounter As Integer = 0 To Math.Min(numTransactionsDisplay - 1, sortedTransactions.Count - 1) Dim newTransaction As New Node Dim transaction As WalletTransaction = sortedTransactions(currentTransactionCounter) If transaction IsNot Nothing Then newTransaction.Text = transaction.TransactionDateTime.DateTime.ToInvariantString() newTransaction.Name = transaction.TypeName & currentTransactionCounter.ToInvariantString() newTransaction.Cells.Add(New Cell(transaction.TypeName)) newTransaction.Cells.Add(New Cell(transaction.Quantity.ToInvariantString("N0"))) If transaction.TransactionType = "sell" Then newTransaction.Style = _styleGreen newTransaction.Cells.Add(New Cell(transaction.Price.ToInvariantString("N2"), _styleGreenRight)) Else newTransaction.Style = _styleRed newTransaction.Cells.Add(New Cell(transaction.Price.ToInvariantString("N2"), _styleRedRight)) End If adtLastTransactions.Nodes.Add(newTransaction) End If Next adtLastTransactions.EndUpdate() End If End If End Sub Private Sub cboPilotList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cboPilotList.SelectedIndexChanged UpdateTransactions() End Sub Private Sub nudEntries_LostFocus(ByVal sender As Object, ByVal e As EventArgs) Handles nudEntries.LostFocus DBCDefaultTransactionsCount = nudEntries.Value End Sub Private Sub nudEntries_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles nudEntries.ValueChanged If cboPilotList.SelectedItem IsNot Nothing Then DBCDefaultTransactionsCount = nudEntries.Value Call UpdateTransactions() End If End Sub Private Sub btnRefresh_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRefresh.Click Call UpdateTransactions() End Sub End Class End Namespace
schpidi2015/EveHQ
EveHQ/Controls/DBControls/DBCLastTransactions.vb
Visual Basic
gpl-3.0
9,358
/* * XFireDB ruby database * Copyright (C) 2015 Michel Megens <dev@michelmegens.net> * * 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, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <ruby.h> #include <xfiredb/xfiredb.h> #include <xfiredb/mem.h> #include <xfiredb/database.h> #include <xfiredb/container.h> #include <xfiredb/bio.h> #include <xfiredb/list.h> #include <xfiredb/string.h> #include <xfiredb/hashmap.h> #include "se.h" static void rb_db_release(void *p) { } static VALUE rb_container_to_obj(struct db_entry_container *c) { if(c->obj_released) { c->obj = Data_Wrap_Struct(c->type, NULL, c->release, c); c->obj_released = false; } return c->obj; } /* * Document-method: new * @return [Database] A new database instance. */ static VALUE rb_db_new(VALUE klass) { struct database *db = db_alloc("xfire-database"); VALUE obj = Data_Wrap_Struct(klass, NULL, rb_db_release, db); return obj; } static VALUE rb_db_ref(VALUE self, VALUE key) { struct database *db; struct container *c; struct db_entry_container *entry; struct string *s; char *tmp; VALUE rv; db_data_t dbdata; Data_Get_Struct(self, struct database, db); if(db_lookup(db, StringValueCStr(key), &dbdata) != -XFIREDB_OK) return Qnil; c = dbdata.ptr; entry = container_of(c, struct db_entry_container, c); if(entry->type != rb_cString) { return rb_container_to_obj(entry); } else { s = container_get_data(&entry->c); string_get(s, &tmp); rv = rb_str_new2(tmp); xfiredb_free(tmp); return rv; } } static void raw_rb_db_delete(struct db_entry_container *entry) { struct container *c = &entry->c; entry->intree = false; if(entry->type == rb_cString) { /* string type, free it here */ xfiredb_notice_disk(entry->key, NULL, NULL, STRING_DEL); container_destroy(c); xfiredb_free(entry->key); xfiredb_free(entry); return; } else if(entry->type == c_list) { rb_list_free(entry); entry->obj = Qnil; } else if(entry->type == c_hashmap) { rb_hashmap_free(entry); entry->obj = Qnil; } else if(entry->type == c_set) { rb_set_free(entry); entry->obj = Qnil; } } static VALUE rb_db_size(VALUE self) { struct database *db; Data_Get_Struct(self, struct database, db); return LONG2NUM(db_get_size(db)); } static VALUE rb_db_store(VALUE self, VALUE key, VALUE data) { struct database *db; struct container *c; struct db_entry_container *rb_c; struct string *s; const char *tmp = StringValueCStr(key); db_data_t dbdata; Data_Get_Struct(self, struct database, db); if(db_delete(db, tmp, &dbdata) == -XFIREDB_OK) { c = dbdata.ptr; rb_c = container_of(c, struct db_entry_container, c); if(rb_c->obj != data) { if(rb_c->type == rb_cString && rb_obj_class(data) == rb_cString) { c = dbdata.ptr; s = container_get_data(c); string_set(s, StringValueCStr(data)); xfiredb_notice_disk((char*)tmp, NULL, StringValueCStr(data), STRING_UPDATE); return db_store(db, tmp, c) == -XFIREDB_OK ? data : Qnil; } raw_rb_db_delete(rb_c); } } if(rb_obj_class(data) != rb_cString) { Data_Get_Struct(data, struct db_entry_container, rb_c); rb_c->obj = data; rb_c->intree = true; } else { rb_c = xfiredb_zalloc(sizeof(*rb_c)); rb_c->obj = Qnil; rb_c->type = rb_cString; container_init(&rb_c->c, CONTAINER_STRING); s = container_get_data(&rb_c->c); string_set(s, StringValueCStr(data)); } xfiredb_sprintf(&rb_c->key, "%s", tmp); if(db_store(db, tmp, &rb_c->c) != -XFIREDB_OK) { rb_c->intree = false; return Qnil; } xfiredb_store_container((char*)tmp, &rb_c->c); return data; } /* * Document-mehtod: delete * * Delete a key from the database. */ static VALUE rb_db_delete(VALUE self, VALUE key) { struct database *db; struct container *c; struct db_entry_container *entry; db_data_t dbdata; Data_Get_Struct(self, struct database, db); if(db_delete(db, StringValueCStr(key), &dbdata) != -XFIREDB_OK) return Qnil; c = dbdata.ptr; entry = container_of(c, struct db_entry_container, c); raw_rb_db_delete(entry); return key; } void rb_db_free(VALUE self) { struct database *db; Data_Get_Struct(self, struct database, db); db_free(db); } static VALUE db_enum_size(VALUE db, VALUE args, VALUE obj) { return rb_db_size(db); } /* * call-seq: * database.each {|key, value| block } -> db * * Creates an enumerator to enumerate each object in the database. */ static VALUE rb_db_each_pair(VALUE db) { struct db_iterator *it; struct db_entry *e; struct database *dbase; struct container *c; struct db_entry_container *db_c; char *value; VALUE k, v; struct string *s_val; Data_Get_Struct(db, struct database, dbase); RETURN_SIZED_ENUMERATOR(db, 0, 0, db_enum_size); it = db_get_iterator(dbase); for(e = db_iterator_next(it); e; e = db_iterator_next(it)) { c = e->value.ptr; db_c = container_of(c, struct db_entry_container, c); k = rb_str_new2(e->key); if(db_c->type != rb_cString) { v = rb_container_to_obj(db_c); } else { s_val = container_get_data(c); string_get(s_val, &value); v = rb_str_new2(value); xfiredb_free(value); } rb_yield(rb_assoc_new(k, v)); } return db; } VALUE c_database; /* * Document-class: XFireDB::Database * * The XFireDB::Database class is the backend of the XFireDB storage * engine. This class is responsible for saving references to the stored * data. */ void init_database(void) { c_database = rb_define_class_under(c_xfiredb_mod, "Database", rb_cObject); rb_include_module(c_database, rb_mEnumerable); rb_define_singleton_method(c_database, "new", rb_db_new, 0); rb_define_method(c_database, "[]=", rb_db_store, 2); rb_define_method(c_database, "[]", rb_db_ref, 1); rb_define_method(c_database, "delete", rb_db_delete, 1); rb_define_method(c_database, "size", rb_db_size, 0); rb_define_method(c_database, "each", rb_db_each_pair, 0); }
xfiredb/xfiredb
ext/xfiredb-serv/database.c
C
gpl-3.0
6,449
<?php /** * Piwik - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ namespace Piwik\Plugins\SEO\Metric; use Piwik\Http; use Piwik\Metrics\Formatter; use Psr\Log\LoggerInterface; /** * Fetches the domain age using archive.org, who.is and whois.com. */ class DomainAge implements MetricsProvider { /** * @var Formatter */ private $formatter; /** * @var LoggerInterface */ private $logger; public function __construct(Formatter $formatter, LoggerInterface $logger) { $this->formatter = $formatter; $this->logger = $logger; } public function getMetrics($domain) { $domain = str_replace('www.', '', $domain); $ages = array(); $age = $this->getAgeArchiveOrg($domain); if ($age > 0) { $ages[] = $age; } $age = $this->getAgeWhoIs($domain); if ($age > 0) { $ages[] = $age; } $age = $this->getAgeWhoisCom($domain); if ($age > 0) { $ages[] = $age; } if (count($ages) > 0) { $value = min($ages); $value = $this->formatter->getPrettyTimeFromSeconds(time() - $value, true); } else { $value = null; } return array( new Metric('domain-age', 'SEO_DomainAge', $value, 'plugins/Morpheus/icons/dist/SEO/whois.png') ); } /** * Returns the domain age archive.org lists for the current url * * @param string $domain * @return int */ private function getAgeArchiveOrg($domain) { $response = $this->getUrl('https://archive.org/wayback/available?timestamp=19900101&url=' . urlencode($domain)); $data = json_decode($response, true); if (empty($data["archived_snapshots"]["closest"]["timestamp"])) { return 0; } return strtotime($data["archived_snapshots"]["closest"]["timestamp"]); } /** * Returns the domain age who.is lists for the current url * * @param string $domain * @return int */ private function getAgeWhoIs($domain) { $data = $this->getUrl('https://www.who.is/whois/' . urlencode($domain)); preg_match('#(?:Creation Date|Created On|created|Registered on)\.*:\s*([ \ta-z0-9\/\-:\.]+)#si', $data, $p); if (!empty($p[1])) { $value = strtotime(trim($p[1])); if ($value === false) { return 0; } return $value; } return 0; } /** * Returns the domain age whois.com lists for the current url * * @param string $domain * @return int */ private function getAgeWhoisCom($domain) { $data = $this->getUrl('https://www.whois.com/whois/' . urlencode($domain)); preg_match('#(?:Creation Date|Created On|created|Registration Date):\s*([ \ta-z0-9\/\-:\.]+)#si', $data, $p); if (!empty($p[1])) { $value = strtotime(trim($p[1])); if ($value === false) { return 0; } return $value; } return 0; } private function getUrl($url) { try { return $this->getHttpResponse($url); } catch (\Exception $e) { $this->logger->warning('Error while getting SEO stats (domain age): {message}', array('message' => $e->getMessage())); return ''; } } private function getHttpResponse($url) { return str_replace('&nbsp;', ' ', Http::sendHttpRequest($url, $timeout = 10, @$_SERVER['HTTP_USER_AGENT'])); } }
piwik/piwik
plugins/SEO/Metric/DomainAge.php
PHP
gpl-3.0
3,718
## Types of data 1. Quantitative * Continuous - numerical values with decimals like 1.2, 1.8, 20, 2.3. * Discrete - numerical values without decimals (only integers) like 5, 80, 99, 556. * Ratio - numerical values with order among them like height 5.9", 6.0". * Interval - numerical values with known order and separated with fixed interval/gaps like 5, 10, 15, 20. 2. Qualitative * Binary - categorical values but only 2 categories like Male, Female. * Nominal - categorical values with no relation among them (more than 2 categories) like Laptop, Computer, Keyboard. * Ordinal - categorical values with relation/order among them like good, best, excellent.
vivekec/datascience
notes/data_types.md
Markdown
gpl-3.0
678
package com.avaliacao360zanco.config; import com.avaliacao360zanco.async.ExceptionHandlingAsyncTaskExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.*; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import javax.inject.Inject; @Configuration @EnableAsync @EnableScheduling public class AsyncConfiguration implements AsyncConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); @Inject private JHipsterProperties jHipsterProperties; @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize()); executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize()); executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity()); executor.setThreadNamePrefix("avaliacao-360-zanco-Executor-"); return new ExceptionHandlingAsyncTaskExecutor(executor); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
Maiconfz/avaliacao360zanco
src/main/java/com/avaliacao360zanco/config/AsyncConfiguration.java
Java
gpl-3.0
1,645
๏ปฟusing System.ComponentModel; namespace cmdr.TsiLib.Enums { public enum LoopRecorderSize { [Description("4")] _4 = 0, [Description("8")] _8 = 1, [Description("16")] _16 = 2, [Description("32")] _32 = 3 } }
TakTraum/cmdr
cmdr/cmdr.TsiLib/Enums/LoopRecorderSize.cs
C#
gpl-3.0
307
// ************************************************************************************************ // // BornAgain: simulate and fit reflection and scattering // //! @file GUI/coregui/Views/JobWidgets/ProjectionsEditorCanvas.cpp //! @brief Implements class ProjectionsEditorCanvas //! //! @homepage http://www.bornagainproject.org //! @license GNU General Public License v3 or higher (see COPYING) //! @copyright Forschungszentrum Jรผlich GmbH 2018 //! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) // // ************************************************************************************************ #include "GUI/coregui/Views/JobWidgets/ProjectionsEditorCanvas.h" #include "GUI/coregui/Models/IntensityDataItem.h" #include "GUI/coregui/Models/MaskItems.h" #include "GUI/coregui/Models/SessionModel.h" #include "GUI/coregui/Views/IntensityDataWidgets/ColorMap.h" #include "GUI/coregui/Views/IntensityDataWidgets/PlotStatusLabel.h" #include "GUI/coregui/Views/IntensityDataWidgets/ScientificPlotEvent.h" #include "GUI/coregui/Views/MaskWidgets/MaskGraphicsScene.h" #include "GUI/coregui/Views/MaskWidgets/MaskGraphicsView.h" #include <QItemSelectionModel> #include <QVBoxLayout> ProjectionsEditorCanvas::ProjectionsEditorCanvas(QWidget* parent) : QWidget(parent) , m_scene(new MaskGraphicsScene(this)) , m_view(new MaskGraphicsView(m_scene)) , m_colorMap(nullptr) , m_statusLabel(new PlotStatusLabel(nullptr, this)) , m_liveProjection(nullptr) , m_model(nullptr) , m_intensityDataItem(nullptr) , m_currentActivity(MaskEditorFlags::HORIZONTAL_LINE_MODE) , m_block_update(false) { setObjectName("MaskEditorCanvas"); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QVBoxLayout* mainLayout = new QVBoxLayout; mainLayout->addWidget(m_view); mainLayout->addWidget(m_statusLabel); mainLayout->setMargin(0); mainLayout->setSpacing(0); setLayout(mainLayout); connect(m_view, &MaskGraphicsView::changeActivityRequest, this, &ProjectionsEditorCanvas::changeActivityRequest); connect(m_view, &MaskGraphicsView::deleteSelectedRequest, this, &ProjectionsEditorCanvas::deleteSelectedRequest); } void ProjectionsEditorCanvas::setContext(SessionModel* model, const QModelIndex& shapeContainerIndex, IntensityDataItem* intensityItem) { m_model = model; m_scene->setMaskContext(model, shapeContainerIndex, intensityItem); m_view->updateSize(m_view->size()); m_containerIndex = shapeContainerIndex; m_intensityDataItem = intensityItem; setColorMap(m_scene->colorMap()); getScene()->onActivityModeChanged(m_currentActivity); } void ProjectionsEditorCanvas::resetContext() { m_intensityDataItem = nullptr; m_containerIndex = {}; setConnected(false); m_colorMap = nullptr; m_scene->resetContext(); } void ProjectionsEditorCanvas::setSelectionModel(QItemSelectionModel* model) { getScene()->setSelectionModel(model); } void ProjectionsEditorCanvas::onEnteringColorMap() { if (m_liveProjection || m_block_update) return; m_block_update = true; if (m_currentActivity == MaskEditorFlags::HORIZONTAL_LINE_MODE) m_liveProjection = m_model->insertItem<HorizontalLineItem>(m_containerIndex); else if (m_currentActivity == MaskEditorFlags::VERTICAL_LINE_MODE) m_liveProjection = m_model->insertItem<VerticalLineItem>(m_containerIndex); if (m_liveProjection) m_liveProjection->setItemValue(MaskItem::P_IS_VISIBLE, false); m_block_update = false; } void ProjectionsEditorCanvas::onLeavingColorMap() { if (m_block_update) return; m_block_update = true; if (m_liveProjection) { m_liveProjection->parent()->takeRow( m_liveProjection->parent()->rowOfChild(m_liveProjection)); delete m_liveProjection; m_liveProjection = nullptr; } m_block_update = false; } void ProjectionsEditorCanvas::onPositionChanged(double x, double y) { if (m_block_update) return; m_block_update = true; if (m_liveProjection) { if (m_currentActivity == MaskEditorFlags::HORIZONTAL_LINE_MODE) m_liveProjection->setItemValue(HorizontalLineItem::P_POSY, y); else if (m_currentActivity == MaskEditorFlags::VERTICAL_LINE_MODE) m_liveProjection->setItemValue(VerticalLineItem::P_POSX, x); } m_block_update = false; } void ProjectionsEditorCanvas::onResetViewRequest() { m_view->onResetViewRequest(); m_intensityDataItem->resetView(); } void ProjectionsEditorCanvas::onActivityModeChanged(MaskEditorFlags::Activity value) { m_currentActivity = value; getScene()->onActivityModeChanged(value); onLeavingColorMap(); } void ProjectionsEditorCanvas::setColorMap(ColorMap* colorMap) { ASSERT(colorMap); setConnected(false); m_colorMap = colorMap; setConnected(true); m_statusLabel->reset(); m_statusLabel->addPlot(colorMap); } void ProjectionsEditorCanvas::setConnected(bool isConnected) { if (!m_colorMap) return; if (isConnected) { connect(m_colorMap->plotEvent(), &ScientificPlotEvent::enteringPlot, this, &ProjectionsEditorCanvas::onEnteringColorMap, Qt::UniqueConnection); connect(m_colorMap->plotEvent(), &ScientificPlotEvent::leavingPlot, this, &ProjectionsEditorCanvas::onLeavingColorMap, Qt::UniqueConnection); connect(m_colorMap->plotEvent(), &ScientificPlotEvent::positionChanged, this, &ProjectionsEditorCanvas::onPositionChanged, Qt::UniqueConnection); connect(m_colorMap, &ColorMap::marginsChanged, this, &ProjectionsEditorCanvas::marginsChanged, Qt::UniqueConnection); } else { disconnect(m_colorMap->plotEvent(), &ScientificPlotEvent::enteringPlot, this, &ProjectionsEditorCanvas::onEnteringColorMap); disconnect(m_colorMap->plotEvent(), &ScientificPlotEvent::leavingPlot, this, &ProjectionsEditorCanvas::onLeavingColorMap); disconnect(m_colorMap->plotEvent(), &ScientificPlotEvent::positionChanged, this, &ProjectionsEditorCanvas::onPositionChanged); disconnect(m_colorMap, &ColorMap::marginsChanged, this, &ProjectionsEditorCanvas::marginsChanged); } }
gpospelov/BornAgain
GUI/coregui/Views/JobWidgets/ProjectionsEditorCanvas.cpp
C++
gpl-3.0
6,508
/* * Copyright (C) 2016 Alex Yatskov <alex@foosoft.net> * Author: Alex Yatskov <alex@foosoft.net> * * 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, see <http://www.gnu.org/licenses/>. */ class Popup { constructor() { this.popup = null; this.offset = 10; } showAt(pos, content) { this.inject(); this.popup.style.left = pos.x + 'px'; this.popup.style.top = pos.y + 'px'; this.popup.style.visibility = 'visible'; this.setContent(content); } showNextTo(elementRect, content) { this.inject(); const popupRect = this.popup.getBoundingClientRect(); let posX = elementRect.left; if (posX + popupRect.width >= window.innerWidth) { posX = window.innerWidth - popupRect.width; } let posY = elementRect.bottom + this.offset; if (posY + popupRect.height >= window.innerHeight) { posY = elementRect.top - popupRect.height - this.offset; } this.showAt({x: posX, y: posY}, content); } hide() { if (this.popup !== null) { this.popup.style.visibility = 'hidden'; } } setContent(content) { if (this.popup === null) { return; } this.popup.contentWindow.scrollTo(0, 0); const doc = this.popup; doc.srcdoc=content; } sendMessage(action, params, callback) { if (this.popup !== null) { this.popup.contentWindow.postMessage({action, params}, '*'); } } inject() { if (this.popup !== null) { return; } this.popup = document.createElement('iframe'); this.popup.id = 'yomichan-popup'; this.popup.addEventListener('mousedown', (e) => e.stopPropagation()); this.popup.addEventListener('scroll', (e) => e.stopPropagation()); let simpread = document.querySelector('.simpread-read-root'); let root = simpread ? simpread : document.body; root.appendChild(this.popup); } }
ninja33/anki-dict-helper
ext/fg/js/popup.js
JavaScript
gpl-3.0
2,644
<?php /** * Unit test class for WordPress Coding Standard. * * @package WPCS\WordPressCodingStandards * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards * @license https://opensource.org/licenses/MIT MIT */ namespace WordPressCS\WordPress\Tests\WP; use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest; /** * Unit test class for the DeprecatedParameterValues sniff. * * @package WPCS\WordPressCodingStandards * * @since 1.0.0 */ class DeprecatedParameterValuesUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * * @return array <int line number> => <int number of errors> */ public function getErrorList() { return array( 5 => 1, 6 => 1, 7 => 1, 8 => 1, 9 => 1, 10 => 1, 11 => 1, 12 => 1, 13 => 1, 14 => 1, 15 => 1, 16 => 1, 17 => 1, 18 => 1, ); } /** * Returns the lines where warnings should occur. * * @return array <int line number> => <int number of warnings> */ public function getWarningList() { return array(); } }
mkdo/kapow-skeleton
wpcs/WordPress/Tests/WP/DeprecatedParameterValuesUnitTest.php
PHP
gpl-3.0
1,098
package br.edu.curso.dubles.stub.exemplo.facebook; import facebook4j.User; public class MailerStub implements IMailer { public static final String sendmsg = "sending email stubber :) to %s"; public boolean sendMail(User user) { System.out.println( String.format(sendmsg, user.getName()) ); return true; } }
rafarocha/ceshi
patterns/xunit/src/test/java/br/edu/curso/dubles/stub/exemplo/facebook/MailerStub.java
Java
gpl-3.0
321
/** ****************************************************************************** * @file stm32l1xx_flash.h * @author MCD Application Team * @version V1.1.0 * @date 24-January-2012 * @brief This file contains all the functions prototypes for the FLASH * firmware library. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * FOR MORE INFORMATION PLEASE READ CAREFULLY THE LICENSE AGREEMENT FILE * LOCATED IN THE ROOT DIRECTORY OF THIS FIRMWARE PACKAGE. * * <h2><center>&copy; COPYRIGHT 2012 STMicroelectronics</center></h2> ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32L1xx_FLASH_H #define __STM32L1xx_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx.h" /** @addtogroup STM32L1xx_StdPeriph_Driver * @{ */ /** @addtogroup FLASH * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief FLASH Status */ typedef enum { FLASH_BUSY = 1, FLASH_ERROR_WRP, FLASH_ERROR_PROGRAM, FLASH_COMPLETE, FLASH_TIMEOUT }FLASH_Status; /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants * @{ */ /** @defgroup FLASH_Latency * @{ */ #define FLASH_Latency_0 ((uint8_t)0x00) /*!< FLASH Zero Latency cycle */ #define FLASH_Latency_1 ((uint8_t)0x01) /*!< FLASH One Latency cycle */ #define IS_FLASH_LATENCY(LATENCY) (((LATENCY) == FLASH_Latency_0) || \ ((LATENCY) == FLASH_Latency_1)) /** * @} */ /** @defgroup FLASH_Interrupts * @{ */ #define FLASH_IT_EOP FLASH_PECR_EOPIE /*!< End of programming interrupt source */ #define FLASH_IT_ERR FLASH_PECR_ERRIE /*!< Error interrupt source */ #define IS_FLASH_IT(IT) ((((IT) & (uint32_t)0xFFFCFFFF) == 0x00000000) && (((IT) != 0x00000000))) /** * @} */ /** @defgroup FLASH_Address * @{ */ #define IS_FLASH_DATA_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08080000) && ((ADDRESS) <= 0x08082FFF)) #define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) <= 0x0805FFFF)) /** * @} */ /** @defgroup Option_Bytes_Write_Protection * @{ */ #define OB_WRP_Pages0to15 ((uint32_t)0x00000001) /* Write protection of Sector0 */ #define OB_WRP_Pages16to31 ((uint32_t)0x00000002) /* Write protection of Sector1 */ #define OB_WRP_Pages32to47 ((uint32_t)0x00000004) /* Write protection of Sector2 */ #define OB_WRP_Pages48to63 ((uint32_t)0x00000008) /* Write protection of Sector3 */ #define OB_WRP_Pages64to79 ((uint32_t)0x00000010) /* Write protection of Sector4 */ #define OB_WRP_Pages80to95 ((uint32_t)0x00000020) /* Write protection of Sector5 */ #define OB_WRP_Pages96to111 ((uint32_t)0x00000040) /* Write protection of Sector6 */ #define OB_WRP_Pages112to127 ((uint32_t)0x00000080) /* Write protection of Sector7 */ #define OB_WRP_Pages128to143 ((uint32_t)0x00000100) /* Write protection of Sector8 */ #define OB_WRP_Pages144to159 ((uint32_t)0x00000200) /* Write protection of Sector9 */ #define OB_WRP_Pages160to175 ((uint32_t)0x00000400) /* Write protection of Sector10 */ #define OB_WRP_Pages176to191 ((uint32_t)0x00000800) /* Write protection of Sector11 */ #define OB_WRP_Pages192to207 ((uint32_t)0x00001000) /* Write protection of Sector12 */ #define OB_WRP_Pages208to223 ((uint32_t)0x00002000) /* Write protection of Sector13 */ #define OB_WRP_Pages224to239 ((uint32_t)0x00004000) /* Write protection of Sector14 */ #define OB_WRP_Pages240to255 ((uint32_t)0x00008000) /* Write protection of Sector15 */ #define OB_WRP_Pages256to271 ((uint32_t)0x00010000) /* Write protection of Sector16 */ #define OB_WRP_Pages272to287 ((uint32_t)0x00020000) /* Write protection of Sector17 */ #define OB_WRP_Pages288to303 ((uint32_t)0x00040000) /* Write protection of Sector18 */ #define OB_WRP_Pages304to319 ((uint32_t)0x00080000) /* Write protection of Sector19 */ #define OB_WRP_Pages320to335 ((uint32_t)0x00100000) /* Write protection of Sector20 */ #define OB_WRP_Pages336to351 ((uint32_t)0x00200000) /* Write protection of Sector21 */ #define OB_WRP_Pages352to367 ((uint32_t)0x00400000) /* Write protection of Sector22 */ #define OB_WRP_Pages368to383 ((uint32_t)0x00800000) /* Write protection of Sector23 */ #define OB_WRP_Pages384to399 ((uint32_t)0x01000000) /* Write protection of Sector24 */ #define OB_WRP_Pages400to415 ((uint32_t)0x02000000) /* Write protection of Sector25 */ #define OB_WRP_Pages416to431 ((uint32_t)0x04000000) /* Write protection of Sector26 */ #define OB_WRP_Pages432to447 ((uint32_t)0x08000000) /* Write protection of Sector27 */ #define OB_WRP_Pages448to463 ((uint32_t)0x10000000) /* Write protection of Sector28 */ #define OB_WRP_Pages464to479 ((uint32_t)0x20000000) /* Write protection of Sector29 */ #define OB_WRP_Pages480to495 ((uint32_t)0x40000000) /* Write protection of Sector30 */ #define OB_WRP_Pages496to511 ((uint32_t)0x80000000) /* Write protection of Sector31 */ #define OB_WRP_AllPages ((uint32_t)0xFFFFFFFF) /*!< Write protection of all Sectors */ #define OB_WRP1_Pages512to527 ((uint32_t)0x00000001) /* Write protection of Sector32 */ #define OB_WRP1_Pages528to543 ((uint32_t)0x00000002) /* Write protection of Sector33 */ #define OB_WRP1_Pages544to559 ((uint32_t)0x00000004) /* Write protection of Sector34 */ #define OB_WRP1_Pages560to575 ((uint32_t)0x00000008) /* Write protection of Sector35 */ #define OB_WRP1_Pages576to591 ((uint32_t)0x00000010) /* Write protection of Sector36 */ #define OB_WRP1_Pages592to607 ((uint32_t)0x00000020) /* Write protection of Sector37 */ #define OB_WRP1_Pages608to623 ((uint32_t)0x00000040) /* Write protection of Sector38 */ #define OB_WRP1_Pages624to639 ((uint32_t)0x00000080) /* Write protection of Sector39 */ #define OB_WRP1_Pages640to655 ((uint32_t)0x00000100) /* Write protection of Sector40 */ #define OB_WRP1_Pages656to671 ((uint32_t)0x00000200) /* Write protection of Sector41 */ #define OB_WRP1_Pages672to687 ((uint32_t)0x00000400) /* Write protection of Sector42 */ #define OB_WRP1_Pages688to703 ((uint32_t)0x00000800) /* Write protection of Sector43 */ #define OB_WRP1_Pages704to719 ((uint32_t)0x00001000) /* Write protection of Sector44 */ #define OB_WRP1_Pages720to735 ((uint32_t)0x00002000) /* Write protection of Sector45 */ #define OB_WRP1_Pages736to751 ((uint32_t)0x00004000) /* Write protection of Sector46 */ #define OB_WRP1_Pages752to767 ((uint32_t)0x00008000) /* Write protection of Sector47 */ #define OB_WRP1_Pages768to783 ((uint32_t)0x00010000) /* Write protection of Sector48 */ #define OB_WRP1_Pages784to799 ((uint32_t)0x00020000) /* Write protection of Sector49 */ #define OB_WRP1_Pages800to815 ((uint32_t)0x00040000) /* Write protection of Sector50 */ #define OB_WRP1_Pages816to831 ((uint32_t)0x00080000) /* Write protection of Sector51 */ #define OB_WRP1_Pages832to847 ((uint32_t)0x00100000) /* Write protection of Sector52 */ #define OB_WRP1_Pages848to863 ((uint32_t)0x00200000) /* Write protection of Sector53 */ #define OB_WRP1_Pages864to879 ((uint32_t)0x00400000) /* Write protection of Sector54 */ #define OB_WRP1_Pages880to895 ((uint32_t)0x00800000) /* Write protection of Sector55 */ #define OB_WRP1_Pages896to911 ((uint32_t)0x01000000) /* Write protection of Sector56 */ #define OB_WRP1_Pages912to927 ((uint32_t)0x02000000) /* Write protection of Sector57 */ #define OB_WRP1_Pages928to943 ((uint32_t)0x04000000) /* Write protection of Sector58 */ #define OB_WRP1_Pages944to959 ((uint32_t)0x08000000) /* Write protection of Sector59 */ #define OB_WRP1_Pages960to975 ((uint32_t)0x10000000) /* Write protection of Sector60 */ #define OB_WRP1_Pages976to991 ((uint32_t)0x20000000) /* Write protection of Sector61 */ #define OB_WRP1_Pages992to1007 ((uint32_t)0x40000000) /* Write protection of Sector62 */ #define OB_WRP1_Pages1008to1023 ((uint32_t)0x80000000) /* Write protection of Sector63 */ #define OB_WRP1_AllPages ((uint32_t)0xFFFFFFFF) /*!< Write protection of all Sectors */ #define OB_WRP2_Pages1024to1039 ((uint32_t)0x00000001) /* Write protection of Sector64 */ #define OB_WRP2_Pages1040to1055 ((uint32_t)0x00000002) /* Write protection of Sector65 */ #define OB_WRP2_Pages1056to1071 ((uint32_t)0x00000004) /* Write protection of Sector66 */ #define OB_WRP2_Pages1072to1087 ((uint32_t)0x00000008) /* Write protection of Sector67 */ #define OB_WRP2_Pages1088to1103 ((uint32_t)0x00000010) /* Write protection of Sector68 */ #define OB_WRP2_Pages1104to1119 ((uint32_t)0x00000020) /* Write protection of Sector69 */ #define OB_WRP2_Pages1120to1135 ((uint32_t)0x00000040) /* Write protection of Sector70 */ #define OB_WRP2_Pages1136to1151 ((uint32_t)0x00000080) /* Write protection of Sector71 */ #define OB_WRP2_Pages1152to1167 ((uint32_t)0x00000100) /* Write protection of Sector72 */ #define OB_WRP2_Pages1168to1183 ((uint32_t)0x00000200) /* Write protection of Sector73 */ #define OB_WRP2_Pages1184to1199 ((uint32_t)0x00000400) /* Write protection of Sector74 */ #define OB_WRP2_Pages1200to1215 ((uint32_t)0x00000800) /* Write protection of Sector75 */ #define OB_WRP2_Pages1216to1231 ((uint32_t)0x00001000) /* Write protection of Sector76 */ #define OB_WRP2_Pages1232to1247 ((uint32_t)0x00002000) /* Write protection of Sector77 */ #define OB_WRP2_Pages1248to1263 ((uint32_t)0x00004000) /* Write protection of Sector78 */ #define OB_WRP2_Pages1264to1279 ((uint32_t)0x00008000) /* Write protection of Sector79 */ #define OB_WRP2_Pages1280to1295 ((uint32_t)0x00010000) /* Write protection of Sector80 */ #define OB_WRP2_Pages1296to1311 ((uint32_t)0x00020000) /* Write protection of Sector81 */ #define OB_WRP2_Pages1312to1327 ((uint32_t)0x00040000) /* Write protection of Sector82 */ #define OB_WRP2_Pages1328to1343 ((uint32_t)0x00080000) /* Write protection of Sector83 */ #define OB_WRP2_Pages1344to1359 ((uint32_t)0x00100000) /* Write protection of Sector84 */ #define OB_WRP2_Pages1360to1375 ((uint32_t)0x00200000) /* Write protection of Sector85 */ #define OB_WRP2_Pages1376to1391 ((uint32_t)0x00400000) /* Write protection of Sector86 */ #define OB_WRP2_Pages1392to1407 ((uint32_t)0x00800000) /* Write protection of Sector87 */ #define OB_WRP2_Pages1408to1423 ((uint32_t)0x01000000) /* Write protection of Sector88 */ #define OB_WRP2_Pages1424to1439 ((uint32_t)0x02000000) /* Write protection of Sector89 */ #define OB_WRP2_Pages1440to1455 ((uint32_t)0x04000000) /* Write protection of Sector90 */ #define OB_WRP2_Pages1456to1471 ((uint32_t)0x08000000) /* Write protection of Sector91 */ #define OB_WRP2_Pages1472to1487 ((uint32_t)0x10000000) /* Write protection of Sector92 */ #define OB_WRP2_Pages1488to1503 ((uint32_t)0x20000000) /* Write protection of Sector93 */ #define OB_WRP2_Pages1504to1519 ((uint32_t)0x40000000) /* Write protection of Sector94 */ #define OB_WRP2_Pages1520to1535 ((uint32_t)0x80000000) /* Write protection of Sector95 */ #define OB_WRP2_AllPages ((uint32_t)0xFFFFFFFF) /*!< Write protection of all Sectors */ #define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000)) /** * @} */ /** @defgroup Option_Bytes_Read_Protection * @{ */ /** * @brief Read Protection Level */ #define OB_RDP_Level_0 ((uint8_t)0xAA) #define OB_RDP_Level_1 ((uint8_t)0xBB) /*#define OB_RDP_Level_2 ((uint8_t)0xCC)*/ /* Warning: When enabling read protection level 2 it's no more possible to go back to level 1 or 0 */ #define IS_OB_RDP(LEVEL) (((LEVEL) == OB_RDP_Level_0)||\ ((LEVEL) == OB_RDP_Level_1))/*||\ ((LEVEL) == OB_RDP_Level_2))*/ /** * @} */ /** @defgroup Option_Bytes_IWatchdog * @{ */ #define OB_IWDG_SW ((uint8_t)0x10) /*!< Software WDG selected */ #define OB_IWDG_HW ((uint8_t)0x00) /*!< Hardware WDG selected */ #define IS_OB_IWDG_SOURCE(SOURCE) (((SOURCE) == OB_IWDG_SW) || ((SOURCE) == OB_IWDG_HW)) /** * @} */ /** @defgroup Option_Bytes_nRST_STOP * @{ */ #define OB_STOP_NoRST ((uint8_t)0x20) /*!< No reset generated when entering in STOP */ #define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ #define IS_OB_STOP_SOURCE(SOURCE) (((SOURCE) == OB_STOP_NoRST) || ((SOURCE) == OB_STOP_RST)) /** * @} */ /** @defgroup Option_Bytes_nRST_STDBY * @{ */ #define OB_STDBY_NoRST ((uint8_t)0x40) /*!< No reset generated when entering in STANDBY */ #define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ #define IS_OB_STDBY_SOURCE(SOURCE) (((SOURCE) == OB_STDBY_NoRST) || ((SOURCE) == OB_STDBY_RST)) /** * @} */ /** @defgroup Option_Bytes_BOOT * @{ */ #define OB_BOOT_BANK2 ((uint8_t)0x00) /*!< At startup, if boot pins are set in boot from user Flash position and this parameter is selected the device will boot from Bank 2 or Bank 1, depending on the activation of the bank */ #define OB_BOOT_BANK1 ((uint8_t)0x80) /*!< At startup, if boot pins are set in boot from user Flash position and this parameter is selected the device will boot from Bank1(Default) */ #define IS_OB_BOOT_BANK(BANK) (((BANK) == OB_BOOT_BANK2) || ((BANK) == OB_BOOT_BANK1)) /** * @} */ /** @defgroup Option_Bytes_BOR_Level * @{ */ #define OB_BOR_OFF ((uint8_t)0x00) /*!< BOR is disabled at power down, the reset is asserted when the VDD power supply reaches the PDR(Power Down Reset) threshold (1.5V) */ #define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< BOR Reset threshold levels for 1.7V - 1.8V VDD power supply */ #define OB_BOR_LEVEL2 ((uint8_t)0x09) /*!< BOR Reset threshold levels for 1.9V - 2.0V VDD power supply */ #define OB_BOR_LEVEL3 ((uint8_t)0x0A) /*!< BOR Reset threshold levels for 2.3V - 2.4V VDD power supply */ #define OB_BOR_LEVEL4 ((uint8_t)0x0B) /*!< BOR Reset threshold levels for 2.55V - 2.65V VDD power supply */ #define OB_BOR_LEVEL5 ((uint8_t)0x0C) /*!< BOR Reset threshold levels for 2.8V - 2.9V VDD power supply */ #define IS_OB_BOR_LEVEL(LEVEL) (((LEVEL) == OB_BOR_OFF) || \ ((LEVEL) == OB_BOR_LEVEL1) || \ ((LEVEL) == OB_BOR_LEVEL2) || \ ((LEVEL) == OB_BOR_LEVEL3) || \ ((LEVEL) == OB_BOR_LEVEL4) || \ ((LEVEL) == OB_BOR_LEVEL5)) /** * @} */ /** @defgroup FLASH_Flags * @{ */ #define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ #define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Programming flag */ #define FLASH_FLAG_ENDHV FLASH_SR_ENHV /*!< FLASH End of High Voltage flag */ #define FLASH_FLAG_READY FLASH_SR_READY /*!< FLASH Ready flag after low power mode */ #define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ #define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ #define FLASH_FLAG_SIZERR FLASH_SR_SIZERR /*!< FLASH Size error flag */ #define FLASH_FLAG_OPTVERR FLASH_SR_OPTVERR /*!< FLASH Option Validity error flag */ #define FLASH_FLAG_OPTVERRUSR FLASH_SR_OPTVERRUSR /*!< FLASH Option User Validity error flag */ #define IS_FLASH_CLEAR_FLAG(FLAG) ((((FLAG) & (uint32_t)0xFFFFE0FD) == 0x00000000) && ((FLAG) != 0x00000000)) #define IS_FLASH_GET_FLAG(FLAG) (((FLAG) == FLASH_FLAG_BSY) || ((FLAG) == FLASH_FLAG_EOP) || \ ((FLAG) == FLASH_FLAG_ENDHV) || ((FLAG) == FLASH_FLAG_READY ) || \ ((FLAG) == FLASH_FLAG_WRPERR) || ((FLAG) == FLASH_FLAG_PGAERR ) || \ ((FLAG) == FLASH_FLAG_SIZERR) || ((FLAG) == FLASH_FLAG_OPTVERR) || \ ((FLAG) == FLASH_FLAG_OPTVERRUSR)) /** * @} */ /** @defgroup FLASH_Keys * @{ */ #define FLASH_PDKEY1 ((uint32_t)0x04152637) /*!< Flash power down key1 */ #define FLASH_PDKEY2 ((uint32_t)0xFAFBFCFD) /*!< Flash power down key2: used with FLASH_PDKEY1 to unlock the RUN_PD bit in FLASH_ACR */ #define FLASH_PEKEY1 ((uint32_t)0x89ABCDEF) /*!< Flash program erase key1 */ #define FLASH_PEKEY2 ((uint32_t)0x02030405) /*!< Flash program erase key: used with FLASH_PEKEY2 to unlock the write access to the FLASH_PECR register and data EEPROM */ #define FLASH_PRGKEY1 ((uint32_t)0x8C9DAEBF) /*!< Flash program memory key1 */ #define FLASH_PRGKEY2 ((uint32_t)0x13141516) /*!< Flash program memory key2: used with FLASH_PRGKEY2 to unlock the program memory */ #define FLASH_OPTKEY1 ((uint32_t)0xFBEAD9C8) /*!< Flash option key1 */ #define FLASH_OPTKEY2 ((uint32_t)0x24252627) /*!< Flash option key2: used with FLASH_OPTKEY1 to unlock the write access to the option byte block */ /** * @} */ /** @defgroup Timeout_definition * @{ */ #define FLASH_ER_PRG_TIMEOUT ((uint32_t)0x8000) /** * @} */ /** @defgroup CMSIS_Legacy * @{ */ #if defined ( __ICCARM__ ) #define InterruptType_ACTLR_DISMCYCINT_Msk IntType_ACTLR_DISMCYCINT_Msk #endif /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /** * @brief FLASH memory functions that can be executed from FLASH. */ /* FLASH Interface configuration functions ************************************/ void FLASH_SetLatency(uint32_t FLASH_Latency); void FLASH_PrefetchBufferCmd(FunctionalState NewState); void FLASH_ReadAccess64Cmd(FunctionalState NewState); void FLASH_SLEEPPowerDownCmd(FunctionalState NewState); /* FLASH Memory Programming functions *****************************************/ void FLASH_Unlock(void); void FLASH_Lock(void); FLASH_Status FLASH_ErasePage(uint32_t Page_Address); FLASH_Status FLASH_FastProgramWord(uint32_t Address, uint32_t Data); /* DATA EEPROM Programming functions ******************************************/ void DATA_EEPROM_Unlock(void); void DATA_EEPROM_Lock(void); void DATA_EEPROM_FixedTimeProgramCmd(FunctionalState NewState); FLASH_Status DATA_EEPROM_EraseByte(uint32_t Address); FLASH_Status DATA_EEPROM_EraseHalfWord(uint32_t Address); FLASH_Status DATA_EEPROM_EraseWord(uint32_t Address); FLASH_Status DATA_EEPROM_FastProgramByte(uint32_t Address, uint8_t Data); FLASH_Status DATA_EEPROM_FastProgramHalfWord(uint32_t Address, uint16_t Data); FLASH_Status DATA_EEPROM_FastProgramWord(uint32_t Address, uint32_t Data); FLASH_Status DATA_EEPROM_ProgramByte(uint32_t Address, uint8_t Data); FLASH_Status DATA_EEPROM_ProgramHalfWord(uint32_t Address, uint16_t Data); FLASH_Status DATA_EEPROM_ProgramWord(uint32_t Address, uint32_t Data); /* Option Bytes Programming functions *****************************************/ void FLASH_OB_Unlock(void); void FLASH_OB_Lock(void); void FLASH_OB_Launch(void); FLASH_Status FLASH_OB_WRPConfig(uint32_t OB_WRP, FunctionalState NewState); FLASH_Status FLASH_OB_WRP1Config(uint32_t OB_WRP1, FunctionalState NewState); FLASH_Status FLASH_OB_WRP2Config(uint32_t OB_WRP2, FunctionalState NewState); FLASH_Status FLASH_OB_RDPConfig(uint8_t OB_RDP); FLASH_Status FLASH_OB_UserConfig(uint8_t OB_IWDG, uint8_t OB_STOP, uint8_t OB_STDBY); FLASH_Status FLASH_OB_BORConfig(uint8_t OB_BOR); FLASH_Status FLASH_OB_BootConfig(uint8_t OB_BOOT); uint8_t FLASH_OB_GetUser(void); uint32_t FLASH_OB_GetWRP(void); uint32_t FLASH_OB_GetWRP1(void); uint32_t FLASH_OB_GetWRP2(void); FlagStatus FLASH_OB_GetRDP(void); uint8_t FLASH_OB_GetBOR(void); /* Interrupts and flags management functions **********************************/ void FLASH_ITConfig(uint32_t FLASH_IT, FunctionalState NewState); FlagStatus FLASH_GetFlagStatus(uint32_t FLASH_FLAG); void FLASH_ClearFlag(uint32_t FLASH_FLAG); FLASH_Status FLASH_GetStatus(void); FLASH_Status FLASH_WaitForLastOperation(uint32_t Timeout); /** * @brief FLASH memory functions that should be executed from internal SRAM. * These functions are defined inside the "stm32l1xx_flash_ramfunc.c" * file. */ __RAM_FUNC FLASH_RUNPowerDownCmd(FunctionalState NewState); __RAM_FUNC FLASH_EraseParallelPage(uint32_t Page_Address1, uint32_t Page_Address2); __RAM_FUNC FLASH_ProgramHalfPage(uint32_t Address, uint32_t* pBuffer); __RAM_FUNC FLASH_ProgramParallelHalfPage(uint32_t Address1, uint32_t* pBuffer1, uint32_t Address2, uint32_t* pBuffer2); __RAM_FUNC DATA_EEPROM_EraseDoubleWord(uint32_t Address); __RAM_FUNC DATA_EEPROM_ProgramDoubleWord(uint32_t Address, uint64_t Data); #ifdef __cplusplus } #endif #endif /* __STM32L1xx_FLASH_H */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2012 STMicroelectronics *****END OF FILE****/
jmahler/EECE344-Digital_System_Design
empty_project/Libraries/STM32L1xx_StdPeriph_Driver/inc/stm32l1xx_flash.h
C
gpl-3.0
23,131
#include <Sensoria.h> #include <SensoriaCore/Communicator.h> #include <SensoriaCore/common.h> #include <SensoriaCore/utils.h> #include <SensoriaCore/debug.h> class ByteAddress: public SensoriaAddress { public: byte addr; // 0 = Broadcast, 1-255 = Valid client addresses boolean inUse; char* toString (char* buf, byte size) const override { if (size >= 4) utoa ((unsigned int) addr, buf, 10); else buf[0] = '\0'; return buf; } protected: virtual bool equalTo (const SensoriaAddress& otherBase) const override { const ByteAddress& other = static_cast<const ByteAddress&> (otherBase); return addr == other.addr; } virtual void clone (const SensoriaAddress& otherBase) override { const ByteAddress& other = static_cast<const ByteAddress&> (otherBase); addr = other.addr; } // Default copy/assignment operators should be fine }; /******************************************************************************/ class SensoriaSerialCommunicator: public SensoriaCommunicator { private: static const byte N_ADDRESSES = 6; ByteAddress addressPool[N_ADDRESSES]; static const byte BUF_SIZE = 64; Stream *serial; byte myAddr; static const byte BROADCAST_ADDRESS = 0; char *readSerialString () { static char buf[BUF_SIZE]; static int i = 0; char *ret = NULL; while (serial -> available ()) { char c = serial -> read (); switch (c) { case '\r': // Ignore break; case '\n': // End of string, process buf[i] = '\0'; // This will always be possible ret = buf; i = 0; break; case -1: // No char available to read break; default: // Got new char, append if (i < BUF_SIZE - 1) buf[i++] = c; break; } } return ret; } boolean receiveGeneric (char*& str, byte& senderAddr, byte& destAddr) { // Assume we'll receive nothing boolean ret = false; if ((str = readSerialString ())) { char *p[3]; if (splitString (str, p, 3) == 3) { int n = atoi (p[0]); if (n > 0 && n <= 255) { // Sender cannot be broadcast address senderAddr = n; n = atoi (p[1]); if (n >= 0 && n <= 255) { destAddr = n; str = p[2]; #if 0 DPRINT (F("Received packet of size ")); DPRINT (packetSize); DPRINT (F(" from ")); DPRINT (senderAddr); DPRINT (F(" to ")); DPRINT (destAddr); DPRINT (F(": \"")); DPRINT (str); DPRINTLN (F("\"")); #endif ret = true; } else { DPRINTLN (F("Invalid destination address")); } } else { DPRINTLN (F("Invalid source address")); } } else { DPRINTLN (F("Received malformed message")); } } return ret; } boolean sendGeneric (const char *str, byte destAddr) { return serial -> print (myAddr) && serial -> print (' ') && serial -> print (destAddr) && serial -> print (' ') && serial -> print (str); } public: SensoriaSerialCommunicator () { } bool begin (Stream& _serial, byte addr) { serial = &_serial; myAddr = addr; return myAddr != BROADCAST_ADDRESS; } virtual SensoriaAddress* getAddress () override { SensoriaAddress* ret = NULL; #if 0 byte cnt = 0; for (byte i = 0; i < N_ADDRESSES && !ret; i++) { if (!addressPool[i].inUse) ++cnt; } DPRINT (F("Addresses not in use: ")); DPRINTLN (cnt); #endif for (byte i = 0; i < N_ADDRESSES && !ret; i++) { if (!addressPool[i].inUse) { addressPool[i].inUse = true; ret = &(addressPool[i]); } } return ret; } virtual void releaseAddress (SensoriaAddress* addr) override { for (byte i = 0; i < N_ADDRESSES; i++) { if (&(addressPool[i]) == addr) { addressPool[i].inUse = false; } } } #ifdef ENABLE_NOTIFICATIONS virtual SensoriaAddress* getNotificationAddress (const SensoriaAddress* client) { ByteAddress* bAddr = reinterpret_cast<ByteAddress*> (getAddress ()); if (bAddr) { const ByteAddress& clientBAddr = *reinterpret_cast<const ByteAddress*> (client); bAddr -> addr = clientBAddr.addr; } return bAddr; } #endif virtual boolean receiveCmd (char*& cmd, SensoriaAddress* client) override { ByteAddress& bAddr = *const_cast<ByteAddress*> (reinterpret_cast<const ByteAddress*> (client)); byte destAddr; return receiveGeneric (cmd, bAddr.addr, destAddr) && bAddr.addr != myAddr && (destAddr == myAddr || destAddr == BROADCAST_ADDRESS); } virtual SendResult reply (const char* reply, const SensoriaAddress* client) override { ByteAddress& bAddr = *const_cast<ByteAddress*> (reinterpret_cast<const ByteAddress*> (client)); return sendGeneric (reply, bAddr.addr) ? SEND_OK : SEND_ERR; } virtual boolean notify (const char* notification, const SensoriaAddress* client) override { ByteAddress& bAddr = *const_cast<ByteAddress*> (reinterpret_cast<const ByteAddress*> (client)); return sendGeneric (notification, bAddr.addr) ? SEND_OK : SEND_ERR; } SendResult sendCmd (const char* cmd, const SensoriaAddress* server, char*& reply) override { ByteAddress& bAddr = *const_cast<ByteAddress*> (reinterpret_cast<const ByteAddress*> (server)); SendResult res = sendGeneric (cmd, bAddr.addr) ? SEND_OK : SEND_ERR; if (res > 0) { unsigned long start = millis (); while (millis () - start < CLIENT_TIMEOUT) { byte srcAddr, destAddr; if (receiveGeneric (reply, srcAddr, destAddr) && srcAddr == bAddr.addr && destAddr == myAddr) { // Got something break; } } if (millis () - start >= CLIENT_TIMEOUT) res = SEND_TIMEOUT; } return res; } virtual SendResult broadcast (const char* cmd) override { (void) cmd; return SEND_ERR; } virtual boolean receiveBroadcastReply (char*& reply, SensoriaAddress*& sender, unsigned int timeout) override { (void) reply; (void) sender; (void) timeout; return false; } #ifdef ENABLE_NOTIFICATIONS virtual boolean receiveNotification (char*& notification) override { (void) notification; return false; } #endif };
SukkoPera/Arduino-Sensoria
arduino/src/SensoriaCommunicators/Serial.h
C
gpl-3.0
6,127
///////////////////////////////////////////////////////////////////////////// // Name: pen.h // Purpose: interface of wxPen* classes // Author: wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// /** The possible styles for a wxPen. Note that hatched pen styles are not supported by X11-based ports, including wxGTK. */ enum wxPenStyle { wxPENSTYLE_INVALID = -1, wxPENSTYLE_SOLID, /**< Solid style. */ wxPENSTYLE_DOT, /**< Dotted style. */ wxPENSTYLE_LONG_DASH, /**< Long dashed style. */ wxPENSTYLE_SHORT_DASH, /**< Short dashed style. */ wxPENSTYLE_DOT_DASH, /**< Dot and dash style. */ wxPENSTYLE_USER_DASH, /**< Use the user dashes: see wxPen::SetDashes. */ wxPENSTYLE_TRANSPARENT, /**< No pen is used. */ wxPENSTYLE_STIPPLE_MASK_OPAQUE, /**< @todo WHAT's this? */ wxPENSTYLE_STIPPLE_MASK, /**< @todo WHAT's this? */ wxPENSTYLE_STIPPLE, /**< Use the stipple bitmap. */ wxPENSTYLE_BDIAGONAL_HATCH, /**< Backward diagonal hatch. */ wxPENSTYLE_CROSSDIAG_HATCH, /**< Cross-diagonal hatch. */ wxPENSTYLE_FDIAGONAL_HATCH, /**< Forward diagonal hatch. */ wxPENSTYLE_CROSS_HATCH, /**< Cross hatch. */ wxPENSTYLE_HORIZONTAL_HATCH, /**< Horizontal hatch. */ wxPENSTYLE_VERTICAL_HATCH, /**< Vertical hatch. */ wxPENSTYLE_FIRST_HATCH, /**< First of the hatch styles (inclusive). */ wxPENSTYLE_LAST_HATCH /**< Last of the hatch styles (inclusive). */ }; /** The possible join values of a wxPen. @todo use wxPENJOIN_ prefix */ enum wxPenJoin { wxJOIN_INVALID = -1, wxJOIN_BEVEL = 120, wxJOIN_MITER, wxJOIN_ROUND, }; /** The possible cap values of a wxPen. @todo use wxPENCAP_ prefix */ enum wxPenCap { wxCAP_INVALID = -1, wxCAP_ROUND = 130, wxCAP_PROJECTING, wxCAP_BUTT }; /** @class wxPenInfo This class is a helper used for wxPen creation using named parameter idiom: it allows specifying various wxPen attributes using the chained calls to its clearly named methods instead of passing them in the fixed order to wxPen constructors. For instance, to create a dotted blue pen with the given join style you could do @code wxPen pen(wxPenInfo(*wxBLUE).Style(wxPENSTYLE_DOT).Join(wxJOIN_BEVEL)); @endcode @since 3.1.1 */ class wxPenInfo { public: explicit wxPenInfo(const wxColour& colour = wxColour(), int width = 1, wxPenStyle style = wxPENSTYLE_SOLID); wxPenInfo& Colour(const wxColour& col); wxPenInfo& Width(int width); wxPenInfo& Style(wxPenStyle style); wxPenInfo& Stipple(const wxBitmap& stipple); wxPenInfo& Dashes(int nb_dashes, const wxDash *dash); wxPenInfo& Join(wxPenJoin join); wxPenInfo& Cap(wxPenCap cap); wxColour GetColour() const; wxBitmap GetStipple() const; wxPenStyle GetStyle() const; wxPenJoin GetJoin() const; wxPenCap GetCap() const; int GetDashes(wxDash **ptr); int GetDashCount() const; wxDash* GetDash() const; bool IsTransparent() const; int GetWidth() const; }; /** @class wxPen A pen is a drawing tool for drawing outlines. It is used for drawing lines and painting the outline of rectangles, ellipses, etc. It has a colour, a width and a style. @note On a monochrome display, wxWidgets shows all non-white pens as black. Do not initialize objects on the stack before the program commences, since other required structures may not have been set up yet. Instead, define global pointers to objects and create them in wxApp::OnInit() or when required. An application may wish to dynamically create pens with different characteristics, and there is the consequent danger that a large number of duplicate pens will be created. Therefore an application may wish to get a pointer to a pen by using the global list of pens ::wxThePenList, and calling the member function wxPenList::FindOrCreatePen(). See wxPenList for more info. This class uses @ref overview_refcount "reference counting and copy-on-write" internally so that assignments between two instances of this class are very cheap. You can therefore use actual objects instead of pointers without efficiency problems. If an instance of this class is changed it will create its own data internally so that other instances, which previously shared the data using the reference counting, are not affected. @library{wxcore} @category{gdi} @stdobjects @li ::wxNullPen @li ::wxBLACK_DASHED_PEN @li ::wxBLACK_PEN @li ::wxBLUE_PEN @li ::wxCYAN_PEN @li ::wxGREEN_PEN @li ::wxYELLOW_PEN @li ::wxGREY_PEN @li ::wxLIGHT_GREY_PEN @li ::wxMEDIUM_GREY_PEN @li ::wxRED_PEN @li ::wxTRANSPARENT_PEN @li ::wxWHITE_PEN @see wxPenList, wxDC, wxDC::SetPen() */ class wxPen : public wxGDIObject { public: /** Default constructor. The pen will be uninitialised, and IsOk() will return @false. */ wxPen(); /** Creates a pen object using the specified pen description. */ wxPen(const wxPenInfo& info); /** Constructs a pen from a colour object, pen width and style. @param colour A colour object. @param width Pen width. Under Windows, the pen width cannot be greater than 1 if the style is @c wxPENSTYLE_DOT, @c wxPENSTYLE_LONG_DASH, @c wxPENSTYLE_SHORT_DASH, @c wxPENSTYLE_DOT_DASH, or @c wxPENSTYLE_USER_DASH. @param style The style may be one of the ::wxPenStyle values. @remarks Different versions of Windows and different versions of other platforms support very different subsets of the styles above so handle with care. @see SetStyle(), SetColour(), SetWidth() */ wxPen(const wxColour& colour, int width = 1, wxPenStyle style = wxPENSTYLE_SOLID); /** Constructs a stippled pen from a stipple bitmap and a width. @param width Pen width. Under Windows, the pen width cannot be greater than 1 if the style is @c wxPENSTYLE_DOT, @c wxPENSTYLE_LONG_DASH, @c wxPENSTYLE_SHORT_DASH, @c wxPENSTYLE_DOT_DASH, or @c wxPENSTYLE_USER_DASH. @param stipple A stipple bitmap. @onlyfor{wxmsw,wxosx} @see SetWidth(), SetStipple() */ wxPen(const wxBitmap& stipple, int width); /** Copy constructor, uses @ref overview_refcount. @param pen A pointer or reference to a pen to copy. */ wxPen(const wxPen& pen); /** Destructor. @see @ref overview_refcount_destruct "reference-counted object destruction" @remarks Although all remaining pens are deleted when the application exits, the application should try to clean up all pens itself. This is because wxWidgets cannot know if a pointer to the pen object is stored in an application data structure, and there is a risk of double deletion. */ virtual ~wxPen(); /** Returns the pen cap style, which may be one of @c wxCAP_ROUND, @c wxCAP_PROJECTING and @c wxCAP_BUTT. The default is @c wxCAP_ROUND. @see SetCap() */ virtual wxPenCap GetCap() const; /** Returns a reference to the pen colour. @see SetColour() */ virtual wxColour GetColour() const; /** Gets an array of dashes (defined as @c char in X, @c DWORD under Windows). @a dashes is a pointer to the internal array. Do not deallocate or store this pointer. @return The number of dashes associated with this pen. @see SetDashes() */ virtual int GetDashes(wxDash** dashes) const; /** Returns the pen join style, which may be one of @c wxJOIN_BEVEL, @c wxJOIN_ROUND and @c wxJOIN_MITER. The default is @c wxJOIN_ROUND. @see SetJoin() */ virtual wxPenJoin GetJoin() const; /** Gets a pointer to the stipple bitmap. @see SetStipple() */ virtual wxBitmap* GetStipple() const; /** Returns the pen style. @see wxPen(), SetStyle() */ virtual wxPenStyle GetStyle() const; /** Returns the pen width. @see SetWidth() */ virtual int GetWidth() const; /** Returns @true if the pen is initialised. Notice that an uninitialized pen object can't be queried for any pen properties and all calls to the accessor methods on it will result in an assert failure. */ virtual bool IsOk() const; /** Returns @true if the pen is a valid non-transparent pen. This method returns @true if the pen object is initialized and has a non-transparent style. Notice that this should be used instead of simply testing whether GetStyle() returns a style different from wxPENSTYLE_TRANSPARENT if the pen may be invalid as GetStyle() would assert in this case. @see IsTransparent() @since 2.9.2. */ bool IsNonTransparent() const; /** Returns @true if the pen is transparent. A transparent pen is simply a pen with wxPENSTYLE_TRANSPARENT style. Notice that this function works even for non-initialized pens (for which it returns @false) unlike tests of the form <code>GetStyle() == wxPENSTYLE_TRANSPARENT</code> which would assert if the pen is invalid. @see IsNonTransparent() @since 2.9.2. */ bool IsTransparent() const; /** Sets the pen cap style, which may be one of @c wxCAP_ROUND, @c wxCAP_PROJECTING and @c wxCAP_BUTT. The default is @c wxCAP_ROUND. @see GetCap() */ virtual void SetCap(wxPenCap capStyle); //@{ /** The pen's colour is changed to the given colour. @see GetColour() */ virtual void SetColour(wxColour& colour); virtual void SetColour(unsigned char red, unsigned char green, unsigned char blue); //@} /** Associates an array of dash values (defined as @c char in X, @c DWORD under Windows) with the pen. The array is not deallocated by wxPen, but neither must it be deallocated by the calling application until the pen is deleted or this function is called with a @NULL array. @see GetDashes() */ virtual void SetDashes(int n, const wxDash* dash); /** Sets the pen join style, which may be one of @c wxJOIN_BEVEL, @c wxJOIN_ROUND and @c wxJOIN_MITER. The default is @c wxJOIN_ROUND. @see GetJoin() */ virtual void SetJoin(wxPenJoin join_style); /** Sets the bitmap for stippling. @see GetStipple() */ virtual void SetStipple(const wxBitmap& stipple); /** Set the pen style. @see wxPen() */ virtual void SetStyle(wxPenStyle style); /** Sets the pen width. @see GetWidth() */ virtual void SetWidth(int width); /** Inequality operator. See @ref overview_refcount_equality "reference-counted object comparison" for more info. */ bool operator!=(const wxPen& pen) const; /** Assignment operator, using @ref overview_refcount. */ wxPen& operator=(const wxPen& pen); /** Equality operator. See @ref overview_refcount_equality "reference-counted object comparison" for more info. */ bool operator==(const wxPen& pen) const; }; /** An empty pen. wxPen::IsOk() always returns @false for this object. */ wxPen wxNullPen; /** Red pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxRED_PEN; /** Blue pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxBLUE_PEN; /** Cyan pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxCYAN_PEN; /** Green pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxGREEN_PEN; /** Yellow pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxYELLOW_PEN; /** Black pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxBLACK_PEN; /** White pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxWHITE_PEN; /** Transparent pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxTRANSPARENT_PEN; /** Black dashed pen. Except for the color and for the @c wxPENSTYLE_SHORT_DASH it has all standard attributes (1-pixel width, @c wxCAP_ROUND style, etc...). */ wxPen* wxBLACK_DASHED_PEN; /** Grey pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxGREY_PEN; /** Medium-grey pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxMEDIUM_GREY_PEN; /** Light-grey pen. Except for the color it has all standard attributes (1-pixel width, @c wxPENSTYLE_SOLID and @c wxCAP_ROUND styles, etc...). */ wxPen* wxLIGHT_GREY_PEN; /** @class wxPenList There is only one instance of this class: ::wxThePenList. Use this object to search for a previously created pen of the desired type and create it if not already found. In some windowing systems, the pen may be a scarce resource, so it can pay to reuse old resources if possible. When an application finishes, all pens will be deleted and their resources freed, eliminating the possibility of 'memory leaks'. However, it is best not to rely on this automatic cleanup because it can lead to double deletion in some circumstances. There are two mechanisms in recent versions of wxWidgets which make the pen list less useful than it once was. Under Windows, scarce resources are cleaned up internally if they are not being used. Also, a referencing counting mechanism applied to all GDI objects means that some sharing of underlying resources is possible. You don't have to keep track of pointers, working out when it is safe delete a pen, because the referencing counting does it for you. For example, you can set a pen in a device context, and then immediately delete the pen you passed, because the pen is 'copied'. So you may find it easier to ignore the pen list, and instead create and copy pens as you see fit. If your Windows resource meter suggests your application is using too many resources, you can resort to using GDI lists to share objects explicitly. The only compelling use for the pen list is for wxWidgets to keep track of pens in order to clean them up on exit. It is also kept for backward compatibility with earlier versions of wxWidgets. @library{wxcore} @category{gdi} @stdobjects ::wxThePenList @see wxPen */ class wxPenList { public: /** Constructor. The application should not construct its own pen list: use the object pointer ::wxThePenList. */ wxPenList(); /** Finds a pen with the specified attributes and returns it, else creates a new pen, adds it to the pen list, and returns it. @param colour Colour object. @param width Width of pen. @param style Pen style. See ::wxPenStyle for a list of styles. */ wxPen* FindOrCreatePen(const wxColour& colour, int width = 1, wxPenStyle style = wxPENSTYLE_SOLID); }; /** The global list of wxPen objects ready to be re-used (for better performances). */ wxPenList* wxThePenList;
CarlosManuelRodr/wxChaos
libs/wxMSW-3.1.4/interface/wx/pen.h
C
gpl-3.0
16,804
<?php class cronCumpleanoTask extends sfBaseTask { protected function configure() { // // add your own arguments here // $this->addArguments(array( // new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'), // )); $this->addOptions(array( new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'), new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'), new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'), // add your own options here )); $this->namespace = 'diario'; $this->name = 'cumpleano'; $this->briefDescription = 'Genera notificaciones siglas para usuarios que cumplan aรฑos, tambien a los miembros de su grupo'; $this->detailedDescription = ''; } protected function execute($arguments = array(), $options = array()) { require_once(sfConfig::get("sf_root_dir") . '/config/ProjectConfiguration.class.php'); $configuration = ProjectConfiguration::getApplicationConfiguration('correspondencia', 'dev', true); sfContext::createInstance($configuration); // initialize the database connection $databaseManager = new sfDatabaseManager($this->configuration); $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); $fechas_actuales= Array(); $rango_max= date('Y')- 17; $rango_min= date('Y')- 80; for($rango_min; $rango_min <= $rango_max; $rango_min++) $fechas_actuales[]= $rango_min.'-'.date('m-d'); $usuarios = Doctrine_Query::create() ->select('f.id') ->from('Funcionarios_Funcionario f') ->whereIn("f.f_nacimiento", $fechas_actuales) ->execute(); foreach($usuarios as $val) { $this->notifyDesk($val->getId()); //incluir otras notificaciones } } public function notifyDesk($funcionario_afectado) { $datos_func= Doctrine::getTable('Funcionarios_FuncionarioCargo')->unidadDelCargoDelFuncionario($funcionario_afectado); $adicionales= FALSE; if(count($datos_func)> 0) { $otros_func= Doctrine::getTable('Funcionarios_FuncionarioCargo')->funcionariosPorUnidad($datos_func[0]['unidad_id']); $adicionales= TRUE; } $datos_funcio_afectado= Doctrine::getTable('Funcionarios_Funcionario')->busquedaFuncionarioCargoUnidad($funcionario_afectado); if(file_exists(sfConfig::get("sf_root_dir").'/web/images/fotos_personal/'.$datos_funcio_afectado[0]['ci'].'.jpg')){ $route_personal= '/images/fotos_personal/'.$datos_funcio_afectado[0]['ci'].'.jpg'; } else { $route_personal= '/images/other/siglas_photo_small_'.$datos_funcio_afectado[0]['sexo'].substr($datos_funcio_afectado[0]['ci'], -1).'.png'; } $mensaje= $this->randomMessage(); $html= ' <table width="100%"> <tr> <td rowspan="3" width="65"><img style="border-radius: 7px; border: 1px solid #a6a6a6" src="' . $route_personal . '" width="60"/></td> <td class="f11n">' . date('d-m-Y h:i A', strtotime($datos_funcio_afectado[0]['created_at'])) . '</td> </tr> <tr> <td><font style="font-size: 19px">ยก<b>'. $datos_funcio_afectado[0]['primer_nombre'] .'</b> el d&iacute;a de hoy, SIGLAS y todo su equipo te desean FELIZ CUMPLEAร‘O!</font></td> </tr> <tr> <td class="f16n"> <em>'. $mensaje .'</em> </td> </tr> </table>'; $comunicaciones_notificacion = new Comunicaciones_Notificacion(); $comunicaciones_notificacion->setFuncionarioId($funcionario_afectado); $comunicaciones_notificacion->setAplicacionId(6); //funcionarios $comunicaciones_notificacion->setFormaEntrega('desk'); $comunicaciones_notificacion->setMetodoId(5); //cumpleano $comunicaciones_notificacion->setFEntrega(date('Y-m-d H:i:s')); $comunicaciones_notificacion->setMensaje($html); $comunicaciones_notificacion->setStatus('A'); $comunicaciones_notificacion->setIdUpdate("000"); $comunicaciones_notificacion->save(); //ADICIONALES. MIEMBROS DE SU GRUPO if($adicionales) { foreach($otros_func as $value) { if($value->getId() != $funcionario_afectado) { $html= ' <table width="100%"> <tr> <td rowspan="3" width="65"><img style="border-radius: 7px; border: 1px solid #a6a6a6" src="' . $route_personal . '" width="60"/></td> <td class="f11n">' . date('d-m-Y h:i A', strtotime($datos_funcio_afectado[0]['created_at'])) . '</td> </tr> <tr> <td><font style="font-size: 17px">ยฟSab&iacute;as que...? Hoy, <b>'. $datos_funcio_afectado[0]['primer_nombre'] .' '. $datos_funcio_afectado[0]['primer_apellido'] .'</b> esta cumpliendo a&ntilde;os!</font></td> </tr> <tr> <td class="f16n"> <em>Nosotros ya '. (($datos_funcio_afectado[0]['sexo']== 'M') ? 'lo' : 'la') .' felicitamos en su d&iacute;a, solo faltas t&uacute;... ;)</em> </td> </tr> </table>'; $comunicaciones_notificacion = new Comunicaciones_Notificacion(); $comunicaciones_notificacion->setFuncionarioId($value->getId()); $comunicaciones_notificacion->setAplicacionId(6); //funcionarios $comunicaciones_notificacion->setFormaEntrega('desk'); $comunicaciones_notificacion->setMetodoId(5); //cumpleano $comunicaciones_notificacion->setFEntrega(date('Y-m-d H:i:s')); $comunicaciones_notificacion->setMensaje($html); $comunicaciones_notificacion->setStatus('A'); $comunicaciones_notificacion->setIdUpdate("000"); $comunicaciones_notificacion->save(); } } } } public function randomMessage() { $mensaje= Array( 'Hacerse mayor es comprender que, a pesar de cerrar ciclos, quedan muchos por abrir. ยกFeliz cumplea&ntilde;os!', 'Esperamos que hoy sea un buen dรญa para que la felicidad dibuje una sonrisa en tu cara. No eres mรกs viej@: ยกeres mรกs sabi@!. ยกFeliz cumplea&ntilde;os!', 'Deseamos que cumplas muchos a&ntilde;os mรกs lleno de bendiciรณn y felicidad. ยกFeliz cumplea&ntilde;os!', 'Hoy y siempre el amor, la felicidad y los exitos te acompa&ntilde;en. ยกFeliz cumplea&ntilde;os!', 'Esperamos que el dรญa de hoy sea un dรญa llenos de sorpresas y que dios te ilumine y te llene de bendiciones hoy y todos los dรญas de tu vida. ยกFeliz cumplea&ntilde;os!', 'Que pases un dรญa feliz al lado de tus personas amadas y que Dios derrame en ti una enredadera de bendiciones. ยกFeliz cumplea&ntilde;os!', 'Hola!!!! esperamos estรฉs pasando muy feliz el Dรญa de tu Cumplea&ntilde;os y deseamos que cumplas muchรญsimos a&ntilde;os mรกs que puedas disfrutar a plenitud, un gran abrazo. ยกFeliz cumplea&ntilde;os!', 'Que dios te de salud y muchos a&ntilde;os de vida, que en el dรญa de hoy te colme de felicidad al lado de tus seres mas queridos. ยกFeliz cumplea&ntilde;os!', 'Que desde hoy la magia sea tu mejor traje, tu sonrisa el mejor regalo, tus ojos el mejor destino y tu felicidad mi mejor deseo. ยกFeliz cumplea&ntilde;os!', 'Que en este dรญa y el resto de tus dรญas te ilumine y te de toda la felicidad que te mereces. ยกFeliz cumplea&ntilde;os!', 'Que Dios te colme de muchas bendiciones, te proteja y te de mucha salud y prosperidad. ยกFeliz cumplea&ntilde;os!', 'Esperamos que el dรญa de tu cumplea&ntilde;os pases un dรญa muy feliz, que dios te ilumine siempre. ยกFeliz cumplea&ntilde;os!', 'Felicidades!!!! Esperamos que tengas un dรญa maravilloso, lleno de amor de todos los que te rodean, que dios te bendiga hoy y siempre. ยกFeliz cumplea&ntilde;os!', 'Te deseamos una luz para tu camino, un รกngel para tu destino, felicidad para tu vida y la bendiciรณn de dios en cada minuto de tu vida. ยกFeliz cumplea&ntilde;os!', 'Esperamos que tengas un feliz y hermoso dรญa y que la pases genial en tu cumplea&ntilde;os.', 'Feliz cumplea&ntilde;os a ti, Feliz cumplea&ntilde;os a ti, Feliz cumplea&ntilde;osโ€ฆโ€ฆ.., Feliz cumplea&ntilde;os a ti!!!! Esperamos que cumplas muchos a&ntilde;os mรกs.', 'La vida se resume en 4 palabras: Dios, salud, amor y esperanza. Que el primero siempre te cuide y que el resto nunca te falte. ยกFeliz cumplea&ntilde;os!', 'Que las bendiciones del buen dios te inunde con mucho amor, felicidad, salud y prosperidad. ยกFeliz cumplea&ntilde;os!', 'Que todos tus sue&ntilde;os se hagan realidad y que dios siempre ilumine tu caminar y te colme de bendiciones. ยกFeliz cumplea&ntilde;os!', 'Hola!!!! No podรญa dejar de pasar a desearte un Feliz Cumplea&ntilde;os, espero que la estรฉs pasando super bien.', 'Hoy celebramos que eres un a&ntilde;o mayor... pero no te preocupes que estรกs mucho mejor. FELIZ CUMPLEA&Ntilde;OS!!!', 'Las palabras no pueden sustituรญr un abrazo... pero sirven para hacerte llegar nuestros mejores deseos. ยกFeliz cumplea&ntilde;os!', ); $index= rand(0, count($mensaje)-1); return $mensaje[$index]; } public function notifySms() { //Notificiones con formato para envio de sms de texto } public function notifyEmail() { //Notificiones con formato para envio de correo electronico } }
mwveliz/siglas-mppp
lib/task/cronCumpleanoTask.class.php
PHP
gpl-3.0
9,924
## DamageType __enum__ >io.wolfscript.api.DamageType --- ### Enum Overview DamageType enum Item | Type --- | :--- ANVIL: <br> _Damage cause by an anvil_ | DamageType ARROW: <br> _Damage cause by an arrow_ | DamageType CACTUS: <br> _Damage caused by cactus (1)_ | DamageType ENCHANTMENT: <br> _Damage caused by an enchantment_ | DamageType EXPLOSION: <br> _Damage caused by explosion_ | DamageType FALL: <br> _Damage caused from falling (fall distance - 3.0)_ | DamageType FALLING_BLOCK: <br> _Damage caused from a falling block_ | DamageType FIRE: <br> _Damage caused by fire (1)_ | DamageType FIREBALL: <br> _Damage cause by a Fireball (Assuming Ghast Fireball)_ | DamageType FIRE_TICK: <br> _Low periodic damage caused by burning (1)_ | DamageType GENERIC: <br> _GENERIC DamageType_ | DamageType LAVA: <br> _Damage caused from lava (4)_ | DamageType LIGHTNINGBOLT: <br> _Damage caused from a lightning bolt_ | DamageType MOB: <br> _Damage dealt by a Mob_ | DamageType PLAYER: <br> _Damage caused by a Player_ | DamageType POTION: <br> _Damage caused by poison (1) (Potions, Poison)_ | DamageType STARVATION: <br> _Damage caused by starvation (1)_ | DamageType SUFFOCATION: <br> _Damage caused by suffocating(1)_ | DamageType THROWN: <br> _Damage caused by a thrown item (like a snowball)_ | DamageType VOID: <br> _Damage caused from falling into the void_ | DamageType WATER: <br> _Damage caused from drowning (2)_ | DamageType WITHER: <br> _Damage caused from a Wither_ | DamageType THORNS: <br> _Damage caused from thorns magic_ | DamageType static function __fromDamageSource__(source) <br> _Gets the type from the [`DamageSource`](DamageSource.md)_ | [`DamageType`](DamageType.md) --- ### Public Methods for [`DamageType`](DamageType.md) ##### <a id='fromdamagesource'></a>public static function __fromDamageSource__(source) _Gets the type from the [`DamageSource`](DamageSource.md)_ Argument | Type | Description --- | --- | --- source | [`DamageSource`](DamageSource.md) | the [`DamageSource`](DamageSource.md) to get the type for Returns | Description --- | --- [`DamageType`](DamageType.md) | the type of the [`DamageSource`](DamageSource.md) if valid; `null` if not --- ##### This file was system generated using custom scripts copyright (c) 2015 Mining Wolf.
miningwolf/docs
docs/wolfcanary/io/wolfscript/api/DamageType.md
Markdown
gpl-3.0
2,300
// src_hydrology/post_change_longitude_latitude.js // ----------------------------------------------- function post_change_longitude_latitude( element ) { var degrees; var minutes; var seconds; var seconds_integer; var floating_point; var string_array; var seconds_array; var delimiter; var minus_sign; var element_name_array; var local_element_name; delimiter = timlib_get_non_minus_delimiter( element.value ); if ( delimiter == '' ) { alert( 'ERROR: invalid value. Resetting...' ); element.value = element.defaultValue; return true; } if ( element.name.substr( 0, 9 ) == 'longitude' ) minus_sign = '-'; else minus_sign = ''; if ( delimiter == '.' ) { string_array = element.value.split( delimiter ); if ( string_array.length == 2 ) { degrees = string_array[ 0 ]; if ( degrees.charAt( 0 ) == '-' ) { degrees = degrees.substr( 1 ); } if ( degrees.length == 1 ) { degrees = "0" + degrees; } if ( degrees.length != 2 ) { alert( 'ERROR: invalid value. Resetting...' ); element.value = element.defaultValue; return true; } floating_point = string_array[ 1 ]; if ( floating_point.length < 0 || floating_point.length > 5 ) { alert( 'ERROR: float must be 5 digits. Resetting...' ); element.value = element.defaultValue; return true; } else if ( floating_point.length == 1 ) floating_point = floating_point + "0000"; else if ( floating_point.length == 2 ) floating_point = floating_point + "000"; else if ( floating_point.length == 3 ) floating_point = floating_point + "00"; else if ( floating_point.length == 4 ) floating_point = floating_point + "0"; element.value = minus_sign + degrees + '.' + floating_point; return true; } } string_array = element.value.split( delimiter ); if ( string_array.length != 3 && ( string_array.length == 4 && delimiter != '.' ) ) { alert( 'ERROR: invalid value. Resetting...' ); element.value = element.defaultValue; return true; } degrees = string_array[ 0 ]; if ( degrees.charAt( 0 ) == '-' ) { degrees = degrees.substr( 1 ); } if ( degrees.length == 1 ) { degrees = "0" + degrees; } minutes = string_array[ 1 ]; if ( minutes.length == 1 ) { minutes = "0" + minutes; } if ( delimiter != '.' ) { seconds = string_array[ 2 ]; seconds_array = seconds.split( '.' ); if ( seconds_array.length != 2 ) { seconds = seconds + '.00'; seconds_array = seconds.split( '.' ); } seconds_integer = seconds_array[ 0 ]; if ( seconds_integer.length == 1 ) { seconds_integer = "0" + seconds_integer; } floating_point = seconds_array[ 1 ]; } else { seconds_integer = string_array[ 2 ]; if ( seconds_integer.length == 0 ) { seconds_integer = "00" + seconds_integer; } else if ( seconds_integer.length == 1 ) { seconds_integer = "0" + seconds_integer; } floating_point = string_array[ 3 ]; } if ( floating_point.length == 0 ) { floating_point = "00" + floating_point; } else if ( floating_point.length == 1 ) { floating_point = "0" + floating_point; } else if ( floating_point.length != 2 ) { alert( 'ERROR: seconds float must be two digits. Resetting...' ); element.value = element.defaultValue; return true; } element.value = minus_sign + degrees + ':' + minutes + ':' + seconds_integer + '.' + floating_point; return true; } // post_change_longitude_latitude()
timhriley/appaserver
src_hydrology/post_change_longitude_latitude.js
JavaScript
gpl-3.0
3,492
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #ifndef JUCE_COMBOBOX_H_INCLUDED #define JUCE_COMBOBOX_H_INCLUDED //============================================================================== /** A component that lets the user choose from a drop-down list of choices. The combo-box has a list of text strings, each with an associated id number, that will be shown in the drop-down list when the user clicks on the component. The currently selected choice is displayed in the combo-box, and this can either be read-only text, or editable. To find out when the user selects a different item or edits the text, you can register a ComboBox::Listener to receive callbacks. @see ComboBox::Listener */ class JUCE_API ComboBox : public Component, public SettableTooltipClient, public LabelListener, // (can't use Label::Listener due to idiotic VC2005 bug) public ValueListener, private AsyncUpdater { public: //============================================================================== /** Creates a combo-box. On construction, the text field will be empty, so you should call the setSelectedId() or setText() method to choose the initial value before displaying it. @param componentName the name to set for the component (see Component::setName()) */ explicit ComboBox (const String& componentName = String::empty); /** Destructor. */ ~ComboBox(); //============================================================================== /** Sets whether the test in the combo-box is editable. The default state for a new ComboBox is non-editable, and can only be changed by choosing from the drop-down list. */ void setEditableText (bool isEditable); /** Returns true if the text is directly editable. @see setEditableText */ bool isTextEditable() const noexcept; /** Sets the style of justification to be used for positioning the text. The default is Justification::centredLeft. The text is displayed using a Label component inside the ComboBox. */ void setJustificationType (Justification justification); /** Returns the current justification for the text box. @see setJustificationType */ Justification getJustificationType() const noexcept; //============================================================================== /** Adds an item to be shown in the drop-down list. @param newItemText the text of the item to show in the list @param newItemId an associated ID number that can be set or retrieved - see getSelectedId() and setSelectedId(). Note that this value can not be 0! @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId */ void addItem (const String& newItemText, int newItemId); /** Adds an array of items to the drop-down list. The item ID of each item will be its index in the StringArray + firstItemIdOffset. */ void addItemList (const StringArray& items, int firstItemIdOffset); /** Adds a separator line to the drop-down list. This is like adding a separator to a popup menu. See PopupMenu::addSeparator(). */ void addSeparator(); /** Adds a heading to the drop-down list, so that you can group the items into different sections. The headings are indented slightly differently to set them apart from the items on the list, and obviously can't be selected. You might want to add separators between your sections too. @see addItem, addSeparator */ void addSectionHeading (const String& headingName); /** This allows items in the drop-down list to be selectively disabled. When you add an item, it's enabled by default, but you can call this method to change its status. If you disable an item which is already selected, this won't change the current selection - it just stops the user choosing that item from the list. */ void setItemEnabled (int itemId, bool shouldBeEnabled); /** Returns true if the given item is enabled. */ bool isItemEnabled (int itemId) const noexcept; /** Changes the text for an existing item. */ void changeItemText (int itemId, const String& newText); /** Removes all the items from the drop-down list. If this call causes the content to be cleared, and a change-message will be broadcast according to the notification parameter. @see addItem, removeItem, getNumItems */ void clear (NotificationType notification = sendNotificationAsync); /** Returns the number of items that have been added to the list. Note that this doesn't include headers or separators. */ int getNumItems() const noexcept; /** Returns the text for one of the items in the list. Note that this doesn't include headers or separators. @param index the item's index from 0 to (getNumItems() - 1) */ String getItemText (int index) const; /** Returns the ID for one of the items in the list. Note that this doesn't include headers or separators. @param index the item's index from 0 to (getNumItems() - 1) */ int getItemId (int index) const noexcept; /** Returns the index in the list of a particular item ID. If no such ID is found, this will return -1. */ int indexOfItemId (int itemId) const noexcept; //============================================================================== /** Returns the ID of the item that's currently shown in the box. If no item is selected, or if the text is editable and the user has entered something which isn't one of the items in the list, then this will return 0. @see setSelectedId, getSelectedItemIndex, getText */ int getSelectedId() const noexcept; /** Returns a Value object that can be used to get or set the selected item's ID. You can call Value::referTo() on this object to make the combo box control another Value object. */ Value& getSelectedIdAsValue() { return currentId; } /** Sets one of the items to be the current selection. This will set the ComboBox's text to that of the item that matches this ID. @param newItemId the new item to select @param notification determines the type of change notification that will be sent to listeners if the value changes @see getSelectedId, setSelectedItemIndex, setText */ void setSelectedId (int newItemId, NotificationType notification = sendNotificationAsync); //============================================================================== /** Returns the index of the item that's currently shown in the box. If no item is selected, or if the text is editable and the user has entered something which isn't one of the items in the list, then this will return -1. @see setSelectedItemIndex, getSelectedId, getText */ int getSelectedItemIndex() const; /** Sets one of the items to be the current selection. This will set the ComboBox's text to that of the item at the given index in the list. @param newItemIndex the new item to select @param notification determines the type of change notification that will be sent to listeners if the value changes @see getSelectedItemIndex, setSelectedId, setText */ void setSelectedItemIndex (int newItemIndex, NotificationType notification = sendNotificationAsync); //============================================================================== /** Returns the text that is currently shown in the combo-box's text field. If the ComboBox has editable text, then this text may have been edited by the user; otherwise it will be one of the items from the list, or possibly an empty string if nothing was selected. @see setText, getSelectedId, getSelectedItemIndex */ String getText() const; /** Sets the contents of the combo-box's text field. The text passed-in will be set as the current text regardless of whether it is one of the items in the list. If the current text isn't one of the items, then getSelectedId() will return -1, otherwise it wil return the approriate ID. @param newText the text to select @param notification determines the type of change notification that will be sent to listeners if the text changes @see getText */ void setText (const String& newText, NotificationType notification = sendNotificationAsync); /** Programmatically opens the text editor to allow the user to edit the current item. This is the same effect as when the box is clicked-on. @see Label::showEditor(); */ void showEditor(); /** Pops up the combo box's list. */ void showPopup(); //============================================================================== /** A class for receiving events from a ComboBox. You can register a ComboBox::Listener with a ComboBox using the ComboBox::addListener() method, and it will be called when the selected item in the box changes. @see ComboBox::addListener, ComboBox::removeListener */ class JUCE_API Listener { public: /** Destructor. */ virtual ~Listener() {} /** Called when a ComboBox has its selected item changed. */ virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0; }; /** Registers a listener that will be called when the box's content changes. */ void addListener (Listener* listener); /** Deregisters a previously-registered listener. */ void removeListener (Listener* listener); //============================================================================== /** Sets a message to display when there is no item currently selected. @see getTextWhenNothingSelected */ void setTextWhenNothingSelected (const String& newMessage); /** Returns the text that is shown when no item is selected. @see setTextWhenNothingSelected */ String getTextWhenNothingSelected() const; /** Sets the message to show when there are no items in the list, and the user clicks on the drop-down box. By default it just says "no choices", but this lets you change it to something more meaningful. */ void setTextWhenNoChoicesAvailable (const String& newMessage); /** Returns the text shown when no items have been added to the list. @see setTextWhenNoChoicesAvailable */ String getTextWhenNoChoicesAvailable() const; //============================================================================== /** Gives the ComboBox a tooltip. */ void setTooltip (const String& newTooltip) override; //============================================================================== /** A set of colour IDs to use to change the colour of various aspects of the combo box. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour() methods. To change the colours of the menu that pops up @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour */ enum ColourIds { backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */ textColourId = 0x1000a00, /**< The colour for the text in the box. */ outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */ buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */ arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */ }; //============================================================================== /** @internal */ void labelTextChanged (Label*) override; /** @internal */ void enablementChanged() override; /** @internal */ void colourChanged() override; /** @internal */ void focusGained (Component::FocusChangeType) override; /** @internal */ void focusLost (Component::FocusChangeType) override; /** @internal */ void handleAsyncUpdate() override; /** @internal */ String getTooltip() override { return label->getTooltip(); } /** @internal */ void mouseDown (const MouseEvent&) override; /** @internal */ void mouseDrag (const MouseEvent&) override; /** @internal */ void mouseUp (const MouseEvent&) override; /** @internal */ void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override; /** @internal */ void lookAndFeelChanged() override; /** @internal */ void paint (Graphics&) override; /** @internal */ void resized() override; /** @internal */ bool keyStateChanged (bool) override; /** @internal */ bool keyPressed (const KeyPress&) override; /** @internal */ void valueChanged (Value&) override; // These methods' bool parameters have changed: see their new method signatures. JUCE_DEPRECATED (void clear (bool)); JUCE_DEPRECATED (void setSelectedId (int, bool)); JUCE_DEPRECATED (void setSelectedItemIndex (int, bool)); JUCE_DEPRECATED (void setText (const String&, bool)); private: //============================================================================== struct ItemInfo { ItemInfo (const String& name, int itemId, bool isEnabled, bool isHeading); bool isSeparator() const noexcept; bool isRealItem() const noexcept; String name; int itemId; bool isEnabled : 1, isHeading : 1; }; OwnedArray <ItemInfo> items; Value currentId; int lastCurrentId; bool isButtonDown, separatorPending, menuActive; ListenerList <Listener> listeners; ScopedPointer<Label> label; String textWhenNothingSelected, noChoicesMessage; ItemInfo* getItemForId (int itemId) const noexcept; ItemInfo* getItemForIndex (int index) const noexcept; bool selectIfEnabled (int index); bool nudgeSelectedItem (int delta); void sendChange (NotificationType); static void popupMenuFinishedCallback (int, ComboBox*); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBox) }; /** This typedef is just for compatibility with old code - newer code should use the ComboBox::Listener class directly. */ typedef ComboBox::Listener ComboBoxListener; #endif // JUCE_COMBOBOX_H_INCLUDED
alessandrostone/KlangFalter
JuceLibraryCode/modules/juce_gui_basics/widgets/juce_ComboBox.h
C
gpl-3.0
16,529
package addonDread.models; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.model.ModelZombie; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ModelDeath extends ModelZombie { public ModelDeath() { this(0.0F); } public ModelDeath(float par1) { super(par1, 0.0F, 64, 32); this.bipedRightArm = new ModelRenderer(this, 40, 16); this.bipedRightArm.addBox(-1.0F, -2.0F, -1.0F, 2, 12, 2, par1); this.bipedRightArm.setRotationPoint(-5.0F, 2.0F, 0.0F); this.bipedLeftArm = new ModelRenderer(this, 40, 16); this.bipedLeftArm.mirror = true; this.bipedLeftArm.addBox(-1.0F, -2.0F, -1.0F, 2, 12, 2, par1); this.bipedLeftArm.setRotationPoint(5.0F, 2.0F, 0.0F); this.bipedRightLeg = new ModelRenderer(this, 0, 16); this.bipedRightLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 12, 2, par1); this.bipedRightLeg.setRotationPoint(-2.0F, 12.0F, 0.0F); this.bipedLeftLeg = new ModelRenderer(this, 0, 16); this.bipedLeftLeg.mirror = true; this.bipedLeftLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 12, 2, par1); this.bipedLeftLeg.setRotationPoint(2.0F, 12.0F, 0.0F); } /** * Used for easily adding entity-dependent animations. The second and third * float params here are the same second and third as in the * setRotationAngles method. */ public void setLivingAnimations(EntityLiving par1EntityLiving, float par2, float par3, float par4) { this.aimedBow = true; super.setLivingAnimations(par1EntityLiving, par2, par3, par4); } /** * Sets the model's various rotation angles. For bipeds, par1 and par2 are * used for animating the movement of arms and legs, where par1 represents * the time(so that arms and legs swing back and forth) and par2 represents * how "far" arms and legs can swing at most. */ @Override public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity par7Entity) { super.setRotationAngles(par1, par2, par3, par4, par5, par6, par7Entity); } }
ArtixAllMighty/rpginventory
addonDread/models/ModelDeath.java
Java
gpl-3.0
2,118
// // HYCarouselViewCell.h // iOSAppFrame // // Created by chyrain on 2017/7/1. // Copyright ยฉ 2017ๅนด Chyrain. All rights reserved. // #import <UIKit/UIKit.h> @interface HYCarouselViewCell : UICollectionViewCell @property (nonatomic, weak) UIImageView *iconView; @end
Chyrain/iOSAppFrame
iOSAppFrame/iOSAppFrame/Classes/Views/ViewPager/HYCarouselViewCell.h
C
gpl-3.0
276
package com.personal.xiri.only.utils; import java.io.Closeable; import java.io.IOException; import java.net.Socket; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/10/9 * desc : ๅ…ณ้—ญ็›ธๅ…ณๅทฅๅ…ท็ฑป * </pre> */ public class CloseUtils { private CloseUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * ๅ…ณ้—ญIO * * @param closeables closeable */ public static void closeIO(Closeable... closeables) { if (closeables == null) return; try { for (Closeable closeable : closeables) { if (closeable != null) { closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } } /** * ๅฎ‰้™ๅ…ณ้—ญIO * * @param closeables closeable */ public static void closeIOQuietly(Closeable... closeables) { if (closeables == null) return; try { for (Closeable closeable : closeables) { if (closeable != null) { closeable.close(); } } } catch (IOException e) { // e.printStackTrace(); } } }
gaojianyang/only
Only/app/src/main/java/com/personal/xiri/only/utils/CloseUtils.java
Java
gpl-3.0
1,287
# Simple Page/Notes system, will grow into a full Wiki once I get the time.. class PagesController < ApplicationController def index @pages = current_user.pages.all(:select => 'projects.name, pages.id, pages.name', :order => 'projects.name, pages.position', :include => :project).group_by { |p| p.project.name } end def show @page = Page.find(params[:id], :conditions => ["company_id = ?", current_user.company.id] ) end def new @page = Page.new end def create @page = Page.new(params[:page]) @page.user = current_user @page.company = current_user.company if((@page.project_id.to_i > 0) && @page.save ) flash['notice'] = _('Note was successfully created.') redirect_to :action => 'show', :id => @page.id else render :action => 'new' end end def edit @page = Page.find(params[:id], :conditions => ["company_id = ?", current_user.company.id] ) end def update @page = Page.find(params[:id], :conditions => ["company_id = ?", current_user.company.id] ) old_name = @page.name old_body = @page.body old_project = @page.project_id if @page.update_attributes(params[:page]) flash['notice'] = _('Note was successfully updated.') redirect_to :action => 'show', :id => @page else render :action => 'edit' end end def destroy @page = Page.find(params[:id], :conditions => ["company_id = ?", current_user.company.id] ) @page.destroy redirect_to :controller => 'tasks', :action => 'list' end end
libeo/tiktak
app/controllers/pages_controller.rb
Ruby
gpl-3.0
1,541
'use strict'; //const Path = require('path'); import test from './test'; test('Babel is working!'); //import _ from 'lodash'; const Hapi = require('hapi'); const Hoek = require('hoek'); // Load Neo4j DB Driver const neo4j = require('neo4j-driver').v1; const server = new Hapi.Server(); server.connection({port: 3000, host: 'localhost'}); // Vision controls view templates and handlebars is the templating engine server.register(require('vision'), (err) => { Hoek.assert(!err, err); server.views({ engines: { html: require('handlebars') }, relativeTo: __dirname, // Use templates folder for view templates path: 'templates' }); server.route({ method: 'GET', path: '/', handler: function(request, reply) { reply.view('index'); } }); }); server.start(); // Connect to Neo4j DB //new config(); //config.db = "bolt://35.165.107.226"; //var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "d1c4b9f0f6d88eddfdc028d97105d8fa6eddf322db5fa628c1c08c5b8c7e8b03")); var driver = neo4j.driver("bolt://35.165.107.226", neo4j.auth.basic("neo4j", "enthusiastsneodev")); driver.onCompleted = function() { // proceed with using the driver, it was successfully instantiated }; driver.onError = function(error) { console.log('Driver instantiation failed', error); }; var session = driver.session(); // Run a Cypher statement, reading the result in a streaming manner as records arrive: session.run("MATCH (n:Enthusiast{ email: {email} }) RETURN n AS Enthusiast", { email: 'adam.mackintosh@enthusiasts.com' }) //.run("MERGE (alice:Person {name : {nameParam} }) RETURN alice.name", { nameParam:'Alice' }) .subscribe({ onNext: function(record) { //console.log(record._fields); const foundNode = JSON.stringify(record.get('Enthusiast')); console.log("Found Enthusiast: " + foundNode); console.log("Postal Code: " + foundNode['postal_code']); Object.entries(foundNode).forEach( ([key, value]) => console.log(key, value) ); }, onCompleted: function() { console.log("Done."); session.close(); driver.close(); }, onError: function(error) { console.log(error); driver.close(); } });
agm1984/neo4j-chartist
app.js
JavaScript
gpl-3.0
2,340
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>until</title> <link rel="stylesheet" type="text/css" href="csound.css" /> <link rel="stylesheet" type="text/css" href="syntax-highlighting.css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /> <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" /> <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" /> <link rel="prev" href="unirand.html" title="unirand" /> <link rel="next" href="unwrap.html" title="unwrap" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">until</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="unirand.html">Prev</a>ย </td> <th width="60%" align="center">Orchestra Opcodes and Operators</th> <td width="20%" align="right">ย <a accesskey="n" href="unwrap.html">Next</a></td> </tr> </table> <hr /> </div> <div class="refentry"> <a id="until"></a> <div class="titlepage"></div> <a id="IndexUntil" class="indexterm"></a> <div class="refnamediv"> <h2> <span class="refentrytitle">until</span> </h2> <p>until โ€” A syntactic looping construction. </p> </div> <div class="refsect1"> <a id="idm431443735568"></a> <h2>Description</h2> <p> A syntactic looping construction. </p> </div> <div class="refsect1"> <a id="idm431443734352"></a> <h2>Syntax</h2> <pre class="synopsis"><span class="command"><strong>until</strong></span> condition <span class="command"><strong>do</strong></span> ... <span class="command"><strong>od</strong></span></pre> </div> <div class="refsect1"> <a id="idm431443731280"></a> <h2>Performance</h2> <p> The statements between the <span class="emphasis"><em>do</em></span> and <span class="emphasis"><em>od</em></span> form the body of a loop which is obeyed until the conditional becomes true. </p> </div> <div class="refsect1"> <a id="idm431443729184"></a> <h2>Examples</h2> <p> Here is an example of the until construction. It uses the file <a class="ulink" href="examples/until.csd" target="_top"><em class="citetitle">until.csd</em></a>. </p> <div class="example"> <a id="idm431443727392"></a> <p class="title"> <strong>Exampleย 1057.ย Example of the until opcode.</strong> </p> <div class="example-contents"> <p>See the sections <a class="link" href="UsingRealTime.html" title="Real-Time Audio"><em class="citetitle">Real-time Audio</em></a> and <a class="link" href="CommandFlags.html" title="Csound command line"><em class="citetitle">Command Line Flags</em></a> for more information on using command line flags.</p> <div class="refsect1"> <a id="idm431809524144"></a> <pre class="programlisting"> <span class="nt">&lt;CsoundSynthesizer&gt;</span> <span class="nt">&lt;CsOptions&gt;</span> <span class="c1">; Select audio/midi flags here according to platform</span> <span class="c1">; Audio out Audio in</span> -odac -iadc <span class="c1">;;;RT audio I/O</span> <span class="c1">; For Non-realtime ouput leave only the line below:</span> <span class="c1">; -o ifthen.wav -W ;;; for file output any platform</span> <span class="nt">&lt;/CsOptions&gt;</span> <span class="nt">&lt;CsInstruments&gt;</span> <span class="vg">sr</span> <span class="o">=</span> <span class="mi">44100</span> <span class="vg">kr</span> <span class="o">=</span> <span class="mi">4410</span> <span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">10</span> <span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">1</span> <span class="kd">instr</span> <span class="nf">1</span> <span class="nl">lab99</span><span class="p">:</span> <span class="k">if</span> <span class="nb">p4</span><span class="o">&lt;</span><span class="mi">0</span> <span class="k">goto</span> <span class="nl">lab100</span> <span class="nb">p4</span> <span class="o">=</span> <span class="nb">p4</span><span class="o">-</span><span class="mi">1</span> <span class="nb">print</span> <span class="nb">p4</span> <span class="k">goto</span> <span class="nl">lab99</span> <span class="nl">lab100</span><span class="p">:</span> <span class="kd">endin</span> <span class="kd">instr</span> <span class="nf">2</span> <span class="k">until</span> <span class="nb">p4</span><span class="o">&lt;</span><span class="mi">0</span> <span class="k">do</span> <span class="nb">p4</span> <span class="o">=</span> <span class="nb">p4</span><span class="o">-</span><span class="mi">1</span> <span class="nb">print</span> <span class="nb">p4</span> <span class="k">od</span> <span class="kd">endin</span> <span class="nt">&lt;/CsInstruments&gt;</span> <span class="nt">&lt;CsScore&gt;</span> <span class="nb">i</span> <span class="mi">1</span> <span class="mi">1</span> <span class="mi">1</span> <span class="mi">4</span> <span class="nb">i</span> <span class="mi">2</span> <span class="mi">2</span> <span class="mi">1</span> <span class="mi">4</span> <span class="nb">e</span> <span class="nt">&lt;/CsScore&gt;</span> <span class="nt">&lt;/CsoundSynthesizer&gt;</span> </pre> </div> </div> </div> <p><br class="example-break" /> Its output should include lines like this: </p> <pre class="screen"> B 0.000 .. 1.000 T 1.000 TT 1.000 M: 0.0 new alloc for instr 1: instr 1: p4 = 3.000 instr 1: p4 = 2.000 instr 1: p4 = 1.000 instr 1: p4 = 0.000 instr 1: p4 = -1.000 B 1.000 .. 2.000 T 2.000 TT 2.000 M: 0.0 new alloc for instr 2: instr 2: p4 = 3.000 instr 2: p4 = 2.000 instr 2: p4 = 1.000 instr 2: p4 = 0.000 instr 2: p4 = -1.000 B 2.000 .. 3.000 T 3.000 TT 3.000 M: 0.0 </pre> <p> </p> </div> <div class="refsect1"> <a id="idm431443722304"></a> <h2>See Also</h2> <p> <a class="link" href="loop_ge.html" title="loop_ge"><em class="citetitle">loop_ge</em></a>, <a class="link" href="loop_gt.html" title="loop_gt"><em class="citetitle">loop_gt</em></a> and <a class="link" href="loop_le.html" title="loop_le"><em class="citetitle">loop_le</em></a>. <a class="link" href="loop_lt.html" title="loop_lt"><em class="citetitle">loop_lt</em></a>. <a class="link" href="while.html" title="while"><em class="citetitle">while</em></a>. </p> </div> <div class="refsect1"> <a id="idm431443716736"></a> <h2>Credits</h2> <p>John ffitch.</p> <p>New in Csound version 5.14 with new parser</p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="unirand.html">Prev</a>ย </td> <td width="20%" align="center"> <a accesskey="u" href="OpcodesTop.html">Up</a> </td> <td width="40%" align="right">ย <a accesskey="n" href="unwrap.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">unirandย </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top">ย unwrap</td> </tr> </table> </div> </body> </html>
belangeo/cecilia4csound
Resources/html/until.html
HTML
gpl-3.0
8,012
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> </head> <body> <h2>We have resetted your password</h2> <div> Your new password is: {{ $newPassword }} </div> </body> </html>
rubenvanassche/Programming-Project-Databases
app/views/user/emails/passwordforgot.blade.php
PHP
gpl-3.0
206
--- name: Feature request about: Suggest an idea for this project title: "[Feature Request]" labels: enhancement assignees: GreaterFire --- - [ ] I certify that I have read the contributing guidelines and I acknowledge if I don't follow the format below or I don't check this box, my issue will be closed immediately without any notice. **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Is this problem relevant to what trojan should care about?** Trojan is a protocol implementation, not a full-fledged proxy client. Features such as custom routing will not be accepted. **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
GreaterFire/trojan
.github/ISSUE_TEMPLATE/feature_request.md
Markdown
gpl-3.0
1,016
/******************************************************************** ** Copyright (c) 2018-2020 Guan Wenliang ** This file is part of the Berry default interpreter. ** skiars@qq.com, https://github.com/Skiars/berry ** See Copyright Notice in the LICENSE file or at ** https://github.com/Skiars/berry/blob/master/LICENSE ********************************************************************/ #ifndef BE_MAP_H #define BE_MAP_H #include "be_object.h" typedef struct bmapkey { union bvaldata v; uint32_t type:8; uint32_t next:24; } bmapkey; typedef struct bmapnode { bmapkey key; bvalue value; } bmapnode; struct bmap { bcommon_header; bgcobject *gray; /* for gc gray list */ bmapnode *slots; bmapnode *lastfree; int size; int count; #ifdef __cplusplus BE_CONSTEXPR bmap(bmapnode *s, int n) : next(0), type(BE_MAP), marked(GC_CONST), gray(0), slots(s), lastfree(0), size(n), count(n) {} #endif }; typedef bmapnode *bmapiter; #define be_map_iter() NULL #define be_map_count(map) ((map)->count) #define be_map_size(map) (map->size) #define be_map_key2value(dst, node) do { \ (dst)->type = (node)->key.type; \ (dst)->v = (node)->key.v; \ } while (0); bmap* be_map_new(bvm *vm); void be_map_delete(bvm *vm, bmap *map); bvalue* be_map_find(bvm *vm, bmap *map, bvalue *key); bvalue* be_map_insert(bvm *vm, bmap *map, bvalue *key, bvalue *value); int be_map_remove(bvm *vm, bmap *map, bvalue *key); bvalue* be_map_findstr(bvm *vm, bmap *map, bstring *key); bvalue* be_map_insertstr(bvm *vm, bmap *map, bstring *key, bvalue *value); void be_map_removestr(bvm *vm, bmap *map, bstring *key); bmapnode* be_map_next(bmap *map, bmapiter *iter); bmapnode* be_map_val2node(bvalue *value); void be_map_compact(bvm *vm, bmap *map); #endif
stefanbode/Sonoff-Tasmota
lib/libesp32/Berry/src/be_map.h
C
gpl-3.0
1,826
#include <stdio.h> /* * Copied from include/linux/... */ #undef offsetof #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) /** * container_of - cast a member of a structure out to the containing structure * @ptr: the pointer to the member. * @type: the type of the container struct this is embedded in. * @member: the name of the member within the struct. * */ #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) int main(int argc, char* argv[]){ /* statement, the x result is 5*/ int x = ({1; 2;}) + 3; printf("%d\n", x); x = 5; typeof(x) y = 6; printf("%d %d\n", x, y); struct s { char j1; char j2; }s_t; char *m1, *m2; m1 = &(s_t.j1); m2 = &(s_t.j2); /* This will print 1 */ printf("m1 %d\n", &((struct s*)0)->j1); printf("m2 %d\n", &((struct s*)0)->j2); printf("s addr:0x%08x\n", &s_t); printf("m1 addr:0x%08x\n", m1); printf("m2 addr:0x%08x\n", m2); printf("m1 addr:0x%08x\n", container_of(m1, struct s, j1)); printf("m2 addr:0x%08x\n", container_of(m2, struct s, j2)); return 0; }
YuchengWang/linux-self-code
c/container_of.c
C
gpl-3.0
1,196
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Mon Nov 05 16:19:57 GMT 2012 --> <TITLE> ObjectField (db4o - database for objects - documentation) </TITLE> <META NAME="date" CONTENT="2012-11-05"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ObjectField (db4o - database for objects - documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> db4o 8.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../com/db4o/config/ObjectConstructor.html" title="interface in com.db4o.config"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../com/db4o/config/ObjectTranslator.html" title="interface in com.db4o.config"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/db4o/config/ObjectField.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ObjectField.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.db4o.config</FONT> <BR> Interface ObjectField</H2> <HR> <DL> <DT><PRE>public interface <B>ObjectField</B></DL> </PRE> <P> configuration interface for fields of classes. <br/><br/> Use <A HREF="../../../com/db4o/config/ObjectClass.html#objectField(java.lang.String)"><CODE>ObjectClass.objectField(String)</CODE></A> to access this setting.<br/><br/> <P> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/ObjectField.html#cascadeOnActivate(boolean)">cascadeOnActivate</A></B>(boolean&nbsp;flag)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sets cascaded activation behaviour.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/ObjectField.html#cascadeOnDelete(boolean)">cascadeOnDelete</A></B>(boolean&nbsp;flag)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sets cascaded delete behaviour.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/ObjectField.html#cascadeOnUpdate(boolean)">cascadeOnUpdate</A></B>(boolean&nbsp;flag)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sets cascaded update behaviour.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/ObjectField.html#indexed(boolean)">indexed</A></B>(boolean&nbsp;flag)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;turns indexing on or off.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/ObjectField.html#rename(java.lang.String)">rename</A></B>(java.lang.String&nbsp;newName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;renames a field of a stored class.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="cascadeOnActivate(boolean)"><!-- --></A><H3> cascadeOnActivate</H3> <PRE> void <B>cascadeOnActivate</B>(boolean&nbsp;flag)</PRE> <DL> <DD>sets cascaded activation behaviour. <br/><br/> Setting cascadeOnActivate to true will result in the activation of the object attribute stored in this field if the parent object is activated. <br/><br/> The default setting is <b>false</b>.<br/><br/> In client-server environment this setting should be used on both client and server. <br/><br/> This setting can be applied to an open object container. <br/><br/> <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>flag</CODE> - whether activation is to be cascaded to the member object.<DT><B>See Also:</B><DD><A HREF="../../../com/db4o/config/Configuration.html#activationDepth(int)"><CODE>Why activation?</CODE></A>, <A HREF="../../../com/db4o/config/ObjectClass.html#cascadeOnActivate(boolean)"><CODE>ObjectClass.cascadeOnActivate(boolean)</CODE></A>, <A HREF="../../../com/db4o/ObjectContainer.html#activate(java.lang.Object, int)"><CODE>ObjectContainer.activate(java.lang.Object, int)</CODE></A>, <A HREF="../../../com/db4o/ext/ObjectCallbacks.html" title="interface in com.db4o.ext"><CODE>Using callbacks</CODE></A></DL> </DD> </DL> <HR> <A NAME="cascadeOnDelete(boolean)"><!-- --></A><H3> cascadeOnDelete</H3> <PRE> void <B>cascadeOnDelete</B>(boolean&nbsp;flag)</PRE> <DL> <DD>sets cascaded delete behaviour. <br/><br/> Setting cascadeOnDelete to true will result in the deletion of the object attribute stored in this field on the parent object if the parent object is passed to <A HREF="../../../com/db4o/ObjectContainer.html#delete(java.lang.Object)"><CODE>ObjectContainer.delete(java.lang.Object)</CODE></A>. <br/><br/> <b>Caution !</b><br/> This setting will also trigger deletion of the old member object, on calls to <A HREF="../../../com/db4o/ObjectContainer.html#store(java.lang.Object)"><CODE>ObjectContainer.store(Object)</CODE></A>. An example of the behaviour can be found in <A HREF="../../../com/db4o/config/ObjectClass.html#cascadeOnDelete(boolean)"><CODE>ObjectClass.cascadeOnDelete(boolean)</CODE></A> <br/><br/> The default setting is <b>false</b>.<br/><br/> In client-server environment this setting should be used on both client and server. <br/><br/> This setting can be applied to an open object container. <br/><br/> <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>flag</CODE> - whether deletes are to be cascaded to the member object.<DT><B>See Also:</B><DD><A HREF="../../../com/db4o/config/ObjectClass.html#cascadeOnDelete(boolean)"><CODE>ObjectClass.cascadeOnDelete(boolean)</CODE></A>, <A HREF="../../../com/db4o/ObjectContainer.html#delete(java.lang.Object)"><CODE>ObjectContainer.delete(java.lang.Object)</CODE></A>, <A HREF="../../../com/db4o/ext/ObjectCallbacks.html" title="interface in com.db4o.ext"><CODE>Using callbacks</CODE></A></DL> </DD> </DL> <HR> <A NAME="cascadeOnUpdate(boolean)"><!-- --></A><H3> cascadeOnUpdate</H3> <PRE> void <B>cascadeOnUpdate</B>(boolean&nbsp;flag)</PRE> <DL> <DD>sets cascaded update behaviour. <br/><br/> Setting cascadeOnUpdate to true will result in the update of the object attribute stored in this field if the parent object is passed to <A HREF="../../../com/db4o/ObjectContainer.html#store(java.lang.Object)"><CODE>ObjectContainer.store(Object)</CODE></A>. <br/><br/> The default setting is <b>false</b>.<br/><br/> In client-server environment this setting should be used on both client and server. <br/><br/> This setting can be applied to an open object container. <br/><br/> <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>flag</CODE> - whether updates are to be cascaded to the member object.<DT><B>See Also:</B><DD><CODE>com.db4o.ObjectContainer#set</CODE>, <A HREF="../../../com/db4o/config/ObjectClass.html#cascadeOnUpdate(boolean)"><CODE>ObjectClass.cascadeOnUpdate(boolean)</CODE></A>, <A HREF="../../../com/db4o/config/ObjectClass.html#updateDepth(int)"><CODE>ObjectClass.updateDepth(int)</CODE></A>, <A HREF="../../../com/db4o/ext/ObjectCallbacks.html" title="interface in com.db4o.ext"><CODE>Using callbacks</CODE></A></DL> </DD> </DL> <HR> <A NAME="indexed(boolean)"><!-- --></A><H3> indexed</H3> <PRE> void <B>indexed</B>(boolean&nbsp;flag)</PRE> <DL> <DD>turns indexing on or off. <br/><br/>Field indices dramatically improve query performance but they may considerably reduce storage and update performance.<br/>The best benchmark whether or not an index on a field achieves the desired result is the completed application - with a data load that is typical for it's use.<br/><br/>This configuration setting is only checked when the <A HREF="../../../com/db4o/ObjectContainer.html" title="interface in com.db4o"><CODE>ObjectContainer</CODE></A> is opened. If the setting is set to <code>true</code> and an index does not exist, the index will be created. If the setting is set to <code>false</code> and an index does exist the index will be dropped.<br/><br/> In client-server environment this setting should be used on both client and server. <br/><br/> If this setting is applied to an open ObjectContainer it will take an effect on the next time ObjectContainer is opened.<br/><br/> <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>flag</CODE> - specify <code>true</code> or <code>false</code> to turn indexing on for this field</DL> </DD> </DL> <HR> <A NAME="rename(java.lang.String)"><!-- --></A><H3> rename</H3> <PRE> void <B>rename</B>(java.lang.String&nbsp;newName)</PRE> <DL> <DD>renames a field of a stored class. <br/><br/>Use this method to refactor classes. <br/><br/> In client-server environment this setting should be used on both client and server. <br/><br/> This setting can NOT be applied to an open object container. <br/><br/> <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>newName</CODE> - the new field name.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> db4o 8.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../com/db4o/config/ObjectConstructor.html" title="interface in com.db4o.config"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../com/db4o/config/ObjectTranslator.html" title="interface in com.db4o.config"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/db4o/config/ObjectField.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ObjectField.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2009 Versant Corporation. All rights reserved.</i> </BODY> </HTML>
potty-dzmeia/db4o
doc/api/com/db4o/config/ObjectField.html
HTML
gpl-3.0
15,627
/** * * Copyright (c) 2014, Openflexo * * This file is part of Gina-core, a component of the software infrastructure * developed at Openflexo. * * * Openflexo is dual-licensed under the European Union Public License (EUPL, either * version 1.1 of the License, or any later version ), which is available at * https://joinup.ec.europa.eu/software/page/eupl/licence-eupl * and the GNU General Public License (GPL, either version 3 of the License, or any * later version), which is available at http://www.gnu.org/licenses/gpl.html . * * You can redistribute it and/or modify under the terms of either of these licenses * * If you choose to redistribute it and/or modify under the terms of the GNU GPL, you * must include the following additional permission. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with software containing parts covered by the terms * of EPL 1.0, the licensors of this Program grant you additional permission * to convey the resulting work. * * * This software 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 http://www.openflexo.org/license.html for details. * * * Please contact Openflexo (openflexo-contacts@openflexo.org) * or visit www.openflexo.org if you need additional information. * */ package org.openflexo.gina.model.widget; import java.io.File; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.util.List; import java.util.Vector; import java.util.logging.Logger; import org.openflexo.connie.BindingModel; import org.openflexo.connie.DataBinding; import org.openflexo.gina.controller.FIBController; import org.openflexo.gina.model.FIBComponent; import org.openflexo.gina.model.FIBModelObject; import org.openflexo.gina.model.FIBPropertyNotification; import org.openflexo.gina.model.FIBWidget; import org.openflexo.pamela.annotations.Adder; import org.openflexo.pamela.annotations.CloningStrategy; import org.openflexo.pamela.annotations.DeserializationFinalizer; import org.openflexo.pamela.annotations.Getter; import org.openflexo.pamela.annotations.ImplementationClass; import org.openflexo.pamela.annotations.ModelEntity; import org.openflexo.pamela.annotations.PropertyIdentifier; import org.openflexo.pamela.annotations.Remover; import org.openflexo.pamela.annotations.Setter; import org.openflexo.pamela.annotations.XMLAttribute; import org.openflexo.pamela.annotations.XMLElement; import org.openflexo.pamela.annotations.CloningStrategy.StrategyType; import org.openflexo.pamela.annotations.Getter.Cardinality; import org.openflexo.rm.BasicResourceImpl.LocatorNotFoundException; import org.openflexo.rm.FileResourceImpl; import org.openflexo.rm.Resource; @ModelEntity @ImplementationClass(FIBReferencedComponent.FIBReferencedComponentImpl.class) @XMLElement(xmlTag = "FIBReferencedComponent") public interface FIBReferencedComponent extends FIBWidget { @PropertyIdentifier(type = Resource.class) public static final String COMPONENT_FILE_KEY = "componentFile"; @PropertyIdentifier(type = DataBinding.class) public static final String DYNAMIC_COMPONENT_FILE_KEY = "dynamicComponentFile"; @PropertyIdentifier(type = DataBinding.class) public static final String DYNAMIC_COMPONENT_KEY = "dynamicComponent"; @PropertyIdentifier(type = DataBinding.class) public static final String CONTROLLER_FACTORY_KEY = "controllerFactory"; @PropertyIdentifier(type = Vector.class) public static final String ASSIGNMENTS_KEY = "assignments"; @PropertyIdentifier(type = String.class) public static final String INVALID_COMPONENT_LABEL_KEY = "invalidComponentLabel"; @Getter(value = COMPONENT_FILE_KEY, isStringConvertable = true) @XMLAttribute public Resource getComponentFile(); @Setter(COMPONENT_FILE_KEY) public void setComponentFile(Resource componentFile); // TODO : this is a Workaround for Fib File selector...It has to be fixed in a more efficient way public File getComponentActualFile(); public void setComponentActualFile(File file) throws MalformedURLException, LocatorNotFoundException; @Getter(value = DYNAMIC_COMPONENT_FILE_KEY) @XMLAttribute public DataBinding<Resource> getDynamicComponentFile(); @Setter(DYNAMIC_COMPONENT_FILE_KEY) public void setDynamicComponentFile(DataBinding<Resource> dynamicComponentFile); @Getter(value = DYNAMIC_COMPONENT_KEY) @XMLAttribute public DataBinding<FIBComponent> getDynamicComponent(); @Setter(DYNAMIC_COMPONENT_KEY) public void setDynamicComponent(DataBinding<FIBComponent> dynamicComponent); @Getter(value = CONTROLLER_FACTORY_KEY) @XMLAttribute public DataBinding<FIBController> getControllerFactory(); @Setter(CONTROLLER_FACTORY_KEY) public void setControllerFactory(DataBinding<FIBController> controllerFactory); @Getter(value = ASSIGNMENTS_KEY, cardinality = Cardinality.LIST, inverse = FIBReferenceAssignment.OWNER_KEY) @XMLElement @CloningStrategy(StrategyType.CLONE) public List<FIBReferenceAssignment> getAssignments(); @Setter(ASSIGNMENTS_KEY) public void setAssignments(List<FIBReferenceAssignment> assignments); @Adder(ASSIGNMENTS_KEY) public void addToAssignments(FIBReferenceAssignment aAssignment); @Remover(ASSIGNMENTS_KEY) public void removeFromAssignments(FIBReferenceAssignment aAssignment); public FIBReferenceAssignment createAssignment(); public FIBReferenceAssignment deleteAssignment(FIBReferenceAssignment assignment); @Getter(INVALID_COMPONENT_LABEL_KEY) @XMLAttribute public String getInvalidComponentLabel(); @Setter(INVALID_COMPONENT_LABEL_KEY) public void setInvalidComponentLabel(String invalidComponentLabel); public static abstract class FIBReferencedComponentImpl extends FIBWidgetImpl implements FIBReferencedComponent { private static final Logger logger = Logger.getLogger(FIBReferencedComponent.class.getPackage().getName()); private Resource componentFile; private DataBinding<Resource> dynamicComponentFile; private DataBinding<FIBComponent> dynamicComponent; private DataBinding<FIBController> controllerFactory; // TODO: Should be moved to FIBReferencedComponent widget // private FIBComponent referencedComponent; // private Vector<FIBReferenceAssignment> assignments; public FIBReferencedComponentImpl() { // assignments = new Vector<FIBReferenceAssignment>(); } @Override public String getBaseName() { return "ReferencedComponent"; } @Override public Type getDefaultDataType() { /*if (referencedComponent != null) { return referencedComponent.getDataType(); }*/ return Object.class; } @Override public Resource getComponentFile() { return componentFile; } @Override public void setComponentFile(Resource componentFile) { FIBPropertyNotification<Resource> notification = requireChange(COMPONENT_FILE_KEY, componentFile); if (notification != null) { this.componentFile = componentFile; // component = null; notify(notification); } } // TODO : this is a Workaround for Fib File selector...It has to be fixed in a more efficient way @Override public File getComponentActualFile() { if (componentFile instanceof FileResourceImpl) { return ((FileResourceImpl) componentFile).getFile(); } else return null; } @Override public void setComponentActualFile(File file) throws MalformedURLException, LocatorNotFoundException { this.setComponentFile(new FileResourceImpl(file)); } @Override public DataBinding<Resource> getDynamicComponentFile() { if (dynamicComponentFile == null) { dynamicComponentFile = new DataBinding<>(this, Resource.class, DataBinding.BindingDefinitionType.GET); dynamicComponentFile.setBindingName("dynamicComponentFile"); // dynamicComponentFile.setCacheable(true); } return dynamicComponentFile; } @Override public void setDynamicComponentFile(DataBinding<Resource> dynamicComponentFile) { FIBPropertyNotification<DataBinding<Resource>> notification = requireChange(DYNAMIC_COMPONENT_FILE_KEY, dynamicComponentFile); if (notification != null) { if (dynamicComponentFile != null) { dynamicComponentFile.setOwner(this); dynamicComponentFile.setDeclaredType(Resource.class); dynamicComponentFile.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); dynamicComponentFile.setBindingName("dynamicComponentFile"); // dynamicComponentFile.setCacheable(true); } this.dynamicComponentFile = dynamicComponentFile; // referencedComponent = null; notify(notification); } } @Override public DataBinding<FIBComponent> getDynamicComponent() { if (dynamicComponent == null) { dynamicComponent = new DataBinding<>(this, FIBComponent.class, DataBinding.BindingDefinitionType.GET); dynamicComponent.setBindingName("dynamicComponent"); // dynamicComponentFile.setCacheable(true); } return dynamicComponent; } @Override public void setDynamicComponent(DataBinding<FIBComponent> dynamicComponent) { FIBPropertyNotification<DataBinding<FIBComponent>> notification = requireChange(DYNAMIC_COMPONENT_KEY, dynamicComponent); if (notification != null) { if (dynamicComponent != null) { dynamicComponent.setOwner(this); dynamicComponent.setDeclaredType(FIBComponent.class); dynamicComponent.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); dynamicComponent.setBindingName("dynamicComponent"); // dynamicComponent.setCacheable(true); } this.dynamicComponent = dynamicComponent; // referencedComponent = null; notify(notification); } } @Override public DataBinding<FIBController> getControllerFactory() { if (controllerFactory == null) { controllerFactory = new DataBinding<>(this, FIBController.class, DataBinding.BindingDefinitionType.GET); controllerFactory.setBindingName("controllerFactory"); } return controllerFactory; } @Override public void setControllerFactory(DataBinding<FIBController> controllerFactory) { FIBPropertyNotification<DataBinding<FIBController>> notification = requireChange(CONTROLLER_FACTORY_KEY, controllerFactory); if (notification != null) { if (controllerFactory != null) { controllerFactory.setOwner(this); controllerFactory.setDeclaredType(FIBController.class); controllerFactory.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); controllerFactory.setBindingName("controllerFactory"); } this.controllerFactory = controllerFactory; // referencedComponent = null; notify(notification); } } @Override public Type getDataType() { /*if (referencedComponent != null) { return referencedComponent.getDataType(); }*/ return super.getDataType(); } public boolean hasAssignment(String variableName) { return getAssignment(variableName) != null; } public FIBReferenceAssignment getAssignment(String variableName) { for (FIBReferenceAssignment a : getAssignments()) { if (variableName != null && variableName.equals(a.getVariable().toString())) { return a; } } return null; } @Override public void revalidateBindings() { super.revalidateBindings(); for (FIBReferenceAssignment assign : getAssignments()) { assign.revalidateBindings(); } } @Override public void finalizeDeserialization() { super.finalizeDeserialization(); for (FIBReferenceAssignment assign : getAssignments()) { assign.finalizeDeserialization(); } } /** * Return a list of all bindings declared in the context of this component * * @return */ @Override public List<DataBinding<?>> getDeclaredBindings() { List<DataBinding<?>> returned = super.getDeclaredBindings(); returned.add(getDynamicComponentFile()); return returned; } /* @Override public Boolean getManageDynamicModel() { return true; } */ @Override public FIBReferenceAssignment createAssignment() { logger.info("Called createAssignment()"); FIBReferenceAssignment newAssignment = getModelFactory().newInstance(FIBReferenceAssignment.class); addToAssignments(newAssignment); return newAssignment; } @Override public FIBReferenceAssignment deleteAssignment(FIBReferenceAssignment assignment) { logger.info("Called deleteAssignment() with " + assignment); removeFromAssignments(assignment); return assignment; } } @ModelEntity @ImplementationClass(FIBReferenceAssignment.FIBReferenceAssignmentImpl.class) @XMLElement(xmlTag = "ReferenceAssignment") public static interface FIBReferenceAssignment extends FIBModelObject { @PropertyIdentifier(type = FIBReferencedComponent.class) public static final String OWNER_KEY = "owner"; @PropertyIdentifier(type = DataBinding.class) public static final String VARIABLE_KEY = "variable"; @PropertyIdentifier(type = DataBinding.class) public static final String VALUE_KEY = "value"; @PropertyIdentifier(type = Boolean.class) public static final String MANDATORY_KEY = "mandatory"; @Getter(value = OWNER_KEY /*, inverse = FIBReferencedComponent.ASSIGNMENTS_KEY*/) @CloningStrategy(StrategyType.IGNORE) public FIBReferencedComponent getOwner(); @Setter(OWNER_KEY) public void setOwner(FIBReferencedComponent customColumn); @Getter(value = VARIABLE_KEY) @XMLAttribute public DataBinding<Object> getVariable(); @Setter(VARIABLE_KEY) public void setVariable(DataBinding<Object> variable); @Getter(value = VALUE_KEY) @XMLAttribute public DataBinding<Object> getValue(); @Setter(VALUE_KEY) public void setValue(DataBinding<Object> value); @Getter(value = MANDATORY_KEY, defaultValue = "false") @XMLAttribute public boolean isMandatory(); @Setter(MANDATORY_KEY) public void setMandatory(boolean mandatory); @DeserializationFinalizer public void finalizeDeserialization(); public void revalidateBindings(); public static abstract class FIBReferenceAssignmentImpl extends FIBModelObjectImpl implements FIBReferenceAssignment { private DataBinding<Object> variable; private DataBinding<Object> value; private final boolean mandatory = true; @Override public boolean isMandatory() { return mandatory; } @Override public void setOwner(FIBReferencedComponent referencedComponent) { performSuperSetter(OWNER_KEY, referencedComponent); if (value != null) { value.setOwner(referencedComponent); } } @Override public FIBComponent getComponent() { if (getOwner() != null) { return getOwner().getComponent(); } return null; } @Override public DataBinding<Object> getVariable() { if (variable == null) { variable = new DataBinding<>(this, Object.class, DataBinding.BindingDefinitionType.GET_SET); } return variable; } @Override public void setVariable(DataBinding<Object> variable) { if (variable != null) { variable.setOwner(this); variable.setDeclaredType(Object.class); variable.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET_SET); } this.variable = variable; if (getOwner() != null && variable != null) { variable.decode(); } } @Override public DataBinding<Object> getValue() { if (value == null) { value = new DataBinding<>(getOwner(), Object.class, DataBinding.BindingDefinitionType.GET); } return value; } @Override public void setValue(DataBinding<Object> value) { if (value != null) { value.setOwner(getOwner()); // Warning, still null while deserializing value.setDeclaredType(Object.class); value.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET); this.value = value; } else { getValue(); } } @Override public void revalidateBindings() { if (variable != null) { variable.forceRevalidate(); } if (value != null) { value.setOwner(getOwner()); value.forceRevalidate(); } } @Override public void finalizeDeserialization() { if (variable != null) { variable.decode(); } if (value != null) { value.setOwner(getOwner()); value.decode(); } } @Override public BindingModel getBindingModel() { if (getOwner() != null) { return getOwner().getBindingModel(); } return null; } } } public static class DynamicComponentFileBindingMustBeValid extends BindingMustBeValid<FIBReferencedComponent> { public DynamicComponentFileBindingMustBeValid() { super("'dynamic_componentFile'_binding_is_not_valid", FIBReferencedComponent.class); } @Override public DataBinding<Resource> getBinding(FIBReferencedComponent object) { return object.getDynamicComponentFile(); } } }
openflexo-team/gina
gina-api/src/main/java/org/openflexo/gina/model/widget/FIBReferencedComponent.java
Java
gpl-3.0
16,971
package org.obiba.magma.datasource.fs; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Writer; import javax.validation.constraints.NotNull; import org.obiba.magma.Value; import org.obiba.magma.ValueTableWriter; import org.obiba.magma.Variable; import org.obiba.magma.VariableEntity; import org.obiba.magma.xstream.XStreamValueSet; import com.thoughtworks.xstream.XStream; class FsValueTableWriter implements ValueTableWriter { private final FsValueTable valueTable; private final XStream xstream; FsValueTableWriter(FsValueTable valueTable, XStream xstream) { this.valueTable = valueTable; this.xstream = xstream; } @NotNull @Override public ValueSetWriter writeValueSet(@NotNull VariableEntity entity) { String entry = valueTable.getVariableEntityProvider().addEntity(entity); try { return new XStreamValueSetWriter(valueTable.createWriter(entry), new XStreamValueSet(valueTable.getName(), entity)); } catch(IOException e) { throw new RuntimeException(e); } } @Override public VariableWriter writeVariables() { try { return new XStreamVariableWriter(valueTable.createWriter("variables.xml")); } catch(IOException e) { throw new RuntimeException(e); } } @Override public void close() { } private class XStreamVariableWriter implements VariableWriter { ObjectOutputStream oos; XStreamVariableWriter(Writer os) throws IOException { oos = xstream.createObjectOutputStream(os, "variables"); } @Override public void close() { try { oos.close(); } catch(IOException e) { throw new RuntimeException(e); } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DMI_NONSERIALIZABLE_OBJECT_WRITTEN", justification = "XStream implementation of ObjectOutputStream does not expect or require objects to implement the Serializable marker interface. http://xstream.codehaus.org/faq.html#Serialization") @Override public void writeVariable(@NotNull Variable variable) { try { oos.writeObject(variable); } catch(IOException e) { throw new RuntimeException(e); } } @Override public void removeVariable(@NotNull Variable variable) { throw new UnsupportedOperationException("Variable cannot be removed from a XML file"); } } private class XStreamValueSetWriter implements ValueSetWriter { private final Writer os; private final XStreamValueSet valueSet; private XStreamValueSetWriter(Writer os, XStreamValueSet valueSet) throws IOException { this.os = os; this.valueSet = valueSet; } @Override public void close() { try { xstream.toXML(valueSet, os); } finally { try { os.close(); } catch(IOException ignored) { } } } @Override public void writeValue(@NotNull Variable variable, Value value) { valueSet.setValue(variable, value); } @Override public void remove() { throw new UnsupportedOperationException(); } } }
apruden/magma
magma-datasource-fs/src/main/java/org/obiba/magma/datasource/fs/FsValueTableWriter.java
Java
gpl-3.0
3,136
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <title>All Containers for Bootstrap</title> <!-- Bootstrap Core CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!--<link href="http://bootswatch.com/sandstone/bootstrap.min.css" rel="stylesheet">--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css"> <link rel="stylesheet" href="../dist/css/bootstrap-essentials.css"> <link href="https://cdn.jsdelivr.net/animatecss/3.5.1/animate.min.css" rel="stylesheet"> <!-- Custom CSS --> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body class="well b-0 p-xs-0 mb-xs-0"> <!-- Fixed navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div> <!--/.nav-collapse --> </div> </nav> <div class="container panel"> <h1 class="text-center fs-sm-4-0">Simple Container<br/><small><code>.container</code></small></h1> </div> <div class="container-fluid panel"> <h1 class="text-center fs-sm-4-0">Fluid Container<br/><small><code>.container-fluid</code></small></h1> </div> <div class="container container-smooth panel"> <h1 class="text-center fs-sm-4-0">Smooth Container<br/><small><code>.container-smooth</code></small></h1> </div> <div class="container-login panel"> <h1 class="text-center fs-sm-4-0">Login Container<br/><small><code>.container-login</code></small></h1> </div> <div class="container-login-2 panel"> <h1 class="text-center fs-sm-4-0">2 Column Login Container<br/><small><code>.container-login-2</code></small></h1> </div> <div class="container panel"> <h1 class="text-center fs-sm-4-0">Table Container<br/><small><code>.container-table</code></small></h1> <div class="container-table mb-xs-4"> <div class="row vertical-middle text-center row-split"> <div class="col-sm-4"> <p>Some content</p> <p>Some content</p> <p>Some content</p> </div> <div class="col-sm-4"> <p>Some content</p> <p>Some content</p> </div> <div class="col-sm-4"> <p>Some content</p> <p>Some content</p> <p>Some content</p> <p>Some content</p> </div> </div> </div> </div> <div class="container panel"> <h1 class="text-center fs-sm-4-0">Flex Container<br/><small><code>.container-flex</code></small></h1> <div class="container-flex"> <div class="row gutter-20 gutter-justified"> <div class="col-sm-6 col-md-3"> <div class="panel panel-default flex-col"> <div class="panel-heading">Title flex-col</div> <div class="panel-body flex-grow">Content here -- div with .flex-grow</div> <div class="panel-footer">Footer</div> </div> </div> <div class="col-sm-6 col-md-3"> <div class="panel panel-default"> <div class="panel-heading">Title</div> <div class="panel-body">Content here -- div with no footer</div> </div> </div> <div class="col-sm-6 col-md-3"> <div class="thumbnail"> Duis pharetra varius quam sit amet vulputate. </div> </div> <div class="col-sm-6 col-md-3"> <div class="well"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra varius quam sit amet vulputate. Quisque mauris augue, molestie tincidunt condimentum vitae, gravida a libero. Aenean sit amet felis dolor, in sagittis nisi. </div> </div> </div> </div> </div> <div class="container container-xs container-smooth"> <div class="page-header"> <h1>Different size Containers (for reading text)</h1> </div> </div> <div class="container panel" style="max-width:480px"> <h1 class="text-center">Container XS<br/><small><code>.container-xs</code></small></h1> <p> Occaecat fugiat et dolore culpa nulla Lorem. Ea voluptate nisi anim laboris irure reprehenderit. Aliquip in aute amet aute ex fugiat consectetur. Enim nisi velit eu nostrud dolore ullamco consequat. </p> <p> Aliquip ad ut voluptate nostrud adipisicing ut. Et mollit exercitation do ea nisi. Labore occaecat aute qui sunt nisi mollit culpa voluptate ea reprehenderit est magna sint. Sunt aute enim duis non ea nulla amet consectetur. Culpa minim eiusmod eiusmod mollit. Enim incididunt irure reprehenderit quis sint aliquip aliqua reprehenderit amet. </p> </div> <div class="container container-sm panel" style="max-width:750px"> <h1 class="text-center">Container SM<br/><small><code>.container-sm</code></small></h1> <div class="row"> <div class="col-sm-6"> <p> Incididunt irure quis culpa aliqua amet exercitation irure excepteur irure magna deserunt in anim. Minim et dolor nulla quis ut incididunt enim. Nisi magna do nostrud sint do officia ullamco veniam eiusmod cillum exercitation aute labore. </p> <p> Cillum nostrud dolor eu anim qui culpa duis enim eu nostrud cillum aute id. Duis proident nostrud cillum deserunt dolor proident. Ad est sit id mollit exercitation. </p> </div> <div class="col-sm-6"> <p> Nostrud do reprehenderit consequat in labore incididunt qui deserunt elit. Id non ea sint veniam quis ipsum ea ea cupidatat ipsum dolor. Amet nisi cupidatat deserunt enim aute do ea veniam irure adipisicing fugiat. </p> <p> Sunt in aliqua cupidatat excepteur non eiusmod et dolor sint. Laborum eiusmod minim adipisicing in incididunt culpa eiusmod cillum qui do amet consequat. Aute laboris veniam dolor cillum mollit irure cillum excepteur enim occaecat anim esse Lorem eiusmod. Esse non ut sit laborum dolore. </p> </div> </div> </div> <div class="container container-md panel"> <h1 class="text-center">Container MD<br/><small><code>.container-md</code></small></h1> <div class="row"> <div class="col-sm-6 col-md-4"> <p> Incididunt irure quis culpa aliqua amet exercitation irure excepteur irure magna deserunt in anim. Minim et dolor nulla quis ut incididunt enim. Nisi magna do nostrud sint do officia ullamco veniam eiusmod cillum exercitation aute labore. </p> <p> Cillum nostrud dolor eu anim qui culpa duis enim eu nostrud cillum aute id. Duis proident nostrud cillum deserunt dolor proident. Ad est sit id mollit exercitation. </p> </div> <div class="col-sm-6 col-md-4"> <p> Nostrud do reprehenderit consequat in labore incididunt qui deserunt elit. Id non ea sint veniam quis ipsum ea ea cupidatat ipsum dolor. Amet nisi cupidatat deserunt enim aute do ea veniam irure adipisicing fugiat. </p> <p> Sunt in aliqua cupidatat excepteur non eiusmod et dolor sint. Laborum eiusmod minim adipisicing in incididunt culpa eiusmod cillum qui do amet consequat. Aute laboris veniam dolor cillum mollit irure cillum excepteur enim occaecat anim esse Lorem eiusmod. Esse non ut sit laborum dolore. </p> </div> <div class="col-sm-6 col-md-4"> <p> Labore aute ut fugiat fugiat culpa elit do commodo ut velit id incididunt Lorem ipsum. Dolore cillum eiusmod qui sit culpa duis consequat dolore. Pariatur labore aliqua reprehenderit cupidatat tempor dolor mollit. Id est enim commodo ut eu amet non. Sit eu Lorem magna velit. Velit eu est qui Lorem tempor do consequat cillum ipsum. </p> <p> Aute laboris veniam dolor cillum mollit irure cillum excepteur enim occaecat anim esse Lorem eiusmod. Esse non ut sit laborum dolore. </p> </div> </div> </div> <div class="container panel"> <h1 class="text-center">Container (LG)<br/><small><code>.container</code></small></h1> </div> <div class="container container-smooth"> <div class="page-header"> <h1>Smooth MD size Container</h1> </div> </div> <div class="container panel container-smooth container-md"> <h1 class="text-center">Container MD with smooth<br/><small><code>.container-md</code></small></h1> <div class="row"> <div class="col-sm-6 col-md-4"> <p> Incididunt irure quis culpa aliqua amet exercitation irure excepteur irure magna deserunt in anim. Minim et dolor nulla quis ut incididunt enim. Nisi magna do nostrud sint do officia ullamco veniam eiusmod cillum exercitation aute labore. </p> <p> Cillum nostrud dolor eu anim qui culpa duis enim eu nostrud cillum aute id. Duis proident nostrud cillum deserunt dolor proident. Ad est sit id mollit exercitation. </p> </div> <div class="col-sm-6 col-md-4"> <p> Nostrud do reprehenderit consequat in labore incididunt qui deserunt elit. Id non ea sint veniam quis ipsum ea ea cupidatat ipsum dolor. Amet nisi cupidatat deserunt enim aute do ea veniam irure adipisicing fugiat. </p> <p> Sunt in aliqua cupidatat excepteur non eiusmod et dolor sint. Laborum eiusmod minim adipisicing in incididunt culpa eiusmod cillum qui do amet consequat. Aute laboris veniam dolor cillum mollit irure cillum excepteur enim occaecat anim esse Lorem eiusmod. Esse non ut sit laborum dolore. </p> </div> <div class="col-sm-6 col-md-4"> <p> Labore aute ut fugiat fugiat culpa elit do commodo ut velit id incididunt Lorem ipsum. Dolore cillum eiusmod qui sit culpa duis consequat dolore. Pariatur labore aliqua reprehenderit cupidatat tempor dolor mollit. Id est enim commodo ut eu amet non. Sit eu Lorem magna velit. Velit eu est qui Lorem tempor do consequat cillum ipsum. </p> <p> Aute laboris veniam dolor cillum mollit irure cillum excepteur enim occaecat anim esse Lorem eiusmod. Esse non ut sit laborum dolore. </p> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="../dist/js/bootstrap-essentials.js"></script> </body> </html>
grvpanchal/bootstrap-essentials
docs/examples/containers.html
HTML
gpl-3.0
14,351
DROP TABLE IF EXISTS `powb_toc`; CREATE TABLE `powb_toc` ( `id` bigint(20) NOT NULL AUTO_INCREMENT , `toc_overall` text NULL , `toc_file_id` bigint(20) NULL , `powb_synthesis_id` bigint(20) NOT NULL , `is_active` tinyint(1) NOT NULL , `created_by` bigint(20) NULL , `modified_by` bigint(20) NULL , `active_since` timestamp NULL , `modification_justification` text NULL , PRIMARY KEY (`id`), CONSTRAINT `powb_toc_synthesis_id_fk` FOREIGN KEY (`powb_synthesis_id`) REFERENCES `powb_synthesis` (`id`), CONSTRAINT `powb_toc_file_id_fk` FOREIGN KEY (`toc_file_id`) REFERENCES `files` (`id`), CONSTRAINT `powb_toc_created_by_fk` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`), CONSTRAINT `powb_toc_modified_by_fk` FOREIGN KEY (`modified_by`) REFERENCES `users` (`id`) ) ;
CCAFS/MARLO
marlo-web/src/main/resources/database/migrations/V2_5_0_20180201_1500__PowbToC.sql
SQL
gpl-3.0
780
๏ปฟ// Copyright (c) Clickberry, Inc. All rights reserved. // Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See License.txt in the project root for license information. namespace Portal.DTO.Projects { /// <summary> /// External video entity. /// </summary> public sealed class ExternalVideo { /// <summary> /// External video provider name. /// </summary> public string ProductName { get; set; } /// <summary> /// External video source URL. /// </summary> public string VideoUri { get; set; } /// <summary> /// Gets or sets an ACS namespace. /// </summary> public string AcsNamespace { get; set; } } }
clickberry/video-portal
Source/Entities/Portal.DTO/Projects/ExternalVideo.cs
C#
gpl-3.0
750
<?php /** * TrcIMPLAN รndice Bรกsico de Colonias * * Copyright (C) 2016 Guillermo Valdes Lozano * * 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, see <http://www.gnu.org/licenses/>. * * @package TrcIMPLAN */ namespace IBCTorreon; /** * Clase ElCampanario */ class ElCampanario extends \IBCBase\PublicacionWeb { /** * Constructor */ public function __construct() { // Tรญtulo, autor y fecha $this->nombre = 'El Campanario'; $this->autor = 'IMPLAN Torreรณn Staff'; $this->fecha = '2016-09-02 12:55:35'; // El nombre del archivo a crear (obligatorio) y rutas relativas a las imรกgenes $this->archivo = 'el-campanario'; $this->imagen = '../imagenes/imagen.jpg'; $this->imagen_previa = '../imagenes/imagen-previa.jpg'; // La descripciรณn y claves dan informaciรณn a los buscadores y redes sociales $this->descripcion = 'Colonia El Campanario de IBC Torreรณn.'; $this->claves = 'IMPLAN, Torreon, Desagregaciรณn'; // El directorio en la raรญz donde se guardarรก el archivo HTML $this->directorio = 'ibc-torreon'; // Opciรณn del menรบ Navegaciรณn a poner como activa cuando vea esta publicaciรณn $this->nombre_menu = 'IBC > IBC Torreรณn'; // Para el Organizador $this->categorias = array(); $this->fuentes = array(); $this->regiones = array(); } // constructor /** * Datos * * @return array Arreglo asociativo */ public function datos() { return array( 'Demografรญa' => array( 'Poblaciรณn total' => '0' ), 'Educaciรณn' => array( ), 'Caracterรญsticas Econรณmicas' => array( ), 'Viviendas' => array( 'Hogares' => '0' ), 'Unidades Econรณmicas' => array( 'Total Actividades Econรณmicas' => '0' ) ); } // datos } // Clase ElCampanario ?>
TRCIMPLAN/beta
lib/IBCTorreon/ElCampanario.php
PHP
gpl-3.0
2,701
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.sip.ch16; /** * BoxEigenstate defines the eigenfuntions and eigenvalues for a quantum mechanical particle in a box. * * @author Wolfgang Christian, Jan Tobochnik, Harvey Gould * @version 1.0 revised 03/23/05 */ public class BoxEigenstate { static double a = 1; // length of box private BoxEigenstate() { // prohibit instantiation because all methods are static } static double[] getEigenstate(int n, int numberOfPoints) { double[] phi = new double[numberOfPoints]; n++; // quantum number double norm = Math.sqrt(2/a); for(int i = 0;i<numberOfPoints;i++) { phi[i] = norm*Math.sin((n*Math.PI*i)/(numberOfPoints-1)); } return phi; } static double getEigenvalue(int n) { n++; return(n*n*Math.PI*Math.PI)/2/a/a; // hbar = 1, mass = 1 } } /* * Open Source Physics software is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public License (GPL) as * published by the Free Software Foundation; either version 2 of the License, * or(at your option) any later version. * Code that uses any portion of the code in the org.opensourcephysics package * or any subpackage (subdirectory) of this package must must also be be released * under the GNU GPL license. * * This software 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; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307 USA * or view the license online at http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2007 The Open Source Physics project * http://www.opensourcephysics.org */
OpenSourcePhysics/csm
src/org/opensourcephysics/sip/ch16/BoxEigenstate.java
Java
gpl-3.0
2,169
package net.thevpc.upa.impl.persistence.shared.marshallers; import java.io.ByteArrayInputStream; import net.thevpc.upa.exceptions.IllegalUPAArgumentException; import net.thevpc.upa.impl.persistence.MarshallManager; import net.thevpc.upa.impl.persistence.SimpleTypeMarshaller; import java.sql.Types; import net.thevpc.upa.impl.util.IOUtils; import net.thevpc.upa.persistence.NativeResult; import net.thevpc.upa.persistence.NativeStatement; import net.thevpc.upa.types.Blob; /** * @author Taha BEN SALAH <taha.bensalah@gmail.com> * @creationdate 12/20/12 2:48 AM */ public class ByteRefArrayToBlobMarshaller extends SimpleTypeMarshaller { @Override public Object read(int index, NativeResult resultSet) { /** * @PortabilityHint(target = "C#",name = "todo") * */ if (true) { byte[] t = resultSet.getBytes(index); if (t == null) { return null; } return IOUtils.toByteRefArray(t); } return null; } @Override public void write(Object object, int i, NativeResult updatableResultSet) { /** * @PortabilityHint(target = "C#",name = "todo") */ if (object == null) { updatableResultSet.updateBlob(i, (Blob) null); } else { updatableResultSet.updateBlob(i, new ByteArrayInputStream(IOUtils.toByteArray((Byte[]) object))); } } @Override public String toSQLLiteral(Object object) { if (object == null) { return super.toSQLLiteral(object); } throw new IllegalUPAArgumentException("Unsupported"); } public void write(Object object, int i, NativeStatement preparedStatement) { /** * @PortabilityHint(target = "C#",name = "todo") */ if (object == null) { preparedStatement.setNull(i, Types.BLOB); } else { preparedStatement.setBlob(i, new ByteArrayInputStream((byte[]) object)); } } public ByteRefArrayToBlobMarshaller(MarshallManager marshallManager) { super(marshallManager); } }
thevpc/upa
upa-impl-core/src/main/java/net/thevpc/upa/impl/persistence/shared/marshallers/ByteRefArrayToBlobMarshaller.java
Java
gpl-3.0
2,151
<!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Unity - Scripting API: Light.intensity</title> <meta name="description" content="Develop once, publish everywhere! Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations - publish to the web, Windows, OS X, Wii, Xbox 360, and iPhone with many more platforms to come." /> <meta name="author" content="Unity Technologies" /> <link rel="shortcut icon" href="../StaticFiles/images/favicons/favicon.ico" /> <link rel="icon" type="image/png" href="../StaticFiles/images/favicons/favicon.png" /> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../StaticFiles/images/favicons/apple-touch-icon-152x152.png" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../StaticFiles/images/favicons/apple-touch-icon-144x144.png" /> <link rel="apple-touch-icon-precomposed" sizes="120x120" href="../StaticFiles/images/favicons/apple-touch-icon-120x120.png" /> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../StaticFiles/images/favicons/apple-touch-icon-114x114.png" /> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../StaticFiles/images/favicons/apple-touch-icon-72x72.png" /> <link rel="apple-touch-icon-precomposed" href="../StaticFiles/images/favicons/apple-touch-icon.png" /> <meta name="msapplication-TileColor" content="#222c37" /> <meta name="msapplication-TileImage" content="../StaticFiles/images/favicons/tileicon-144x144.png" /> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-2854981-1']); _gaq.push(['_setDomainName', 'unity3d.com']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript" src="../StaticFiles/js/jquery.js"> </script> <script type="text/javascript" src="docdata/toc.js">//toc</script> <!--local TOC--> <script type="text/javascript" src="docdata/global_toc.js">//toc</script> <!--global TOC, including other platforms--> <script type="text/javascript" src="../StaticFiles/js/core.js"> </script> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../StaticFiles/css/core.css" /> </head> <body> <div class="header-wrapper"> <div id="header" class="header"> <div class="content"> <div class="spacer"> <div class="menu"> <div class="logo"> <a href="http://docs.unity3d.com"> </a> </div> <div class="search-form"> <form action="30_search.html" method="get" class="apisearch"> <input type="text" name="q" placeholder="Search scripting..." autosave="Unity Reference" results="5" class="sbox field" id="q"> </input> <input type="submit" class="submit"> </input> </form> </div> <ul> <li> <a href="http://docs.unity3d.com">Overview</a> </li> <li> <a href="../Manual/index.html">Manual</a> </li> <li> <a href="../ScriptReference/index.html" class="selected">Scripting API</a> </li> </ul> </div> </div> <div class="more"> <div class="filler"> </div> <ul> <li> <a href="http://unity3d.com/">unity3d.com</a> </li> </ul> </div> </div> </div> <div class="toolbar"> <div class="content clear"> <div class="lang-switcher hide"> <div class="current toggle" data-target=".lang-list"> <div class="lbl">Language: <span class="b">English</span></div> <div class="arrow"> </div> </div> <div class="lang-list" style="display:none;"> <ul> <li> <a href="">English</a> </li> </ul> </div> </div> <div class="script-lang"> <ul> <li class="selected" data-lang="CS">C#</li> <li data-lang="JS">JS</li> </ul> <div id="script-lang-dialog" class="dialog hide"> <div class="dialog-content clear"> <h2>Script language</h2> <div class="close"> </div> <p class="clear">Select your preferred scripting language. All code snippets will be displayed in this language.</p> </div> </div> </div> </div> </div> </div> <div id="master-wrapper" class="master-wrapper clear"> <div id="sidebar" class="sidebar"> <div class="sidebar-wrap"> <div class="content"> <div class="sidebar-menu"> <div class="toc"> <h2>Scripting API</h2> </div> </div> <p> <a href="40_history.html" class="cw">History</a> </p> </div> </div> </div> <div id="content-wrap" class="content-wrap"> <div class="content-block"> <div class="content"> <div class="section"> <div class="mb20 clear"> <h1 class="heading inherit"> <a href="Light.html">Light</a>.intensity</h1> <div class="clear"> </div> <div class="clear"> </div> <div class="suggest"> <a class="blue-btn sbtn">Suggest a change</a> <div class="suggest-wrap rel hide"> <div class="loading hide"> <div> </div> <div> </div> <div> </div> </div> <div class="suggest-success hide"> <h2>Success!</h2> <p>Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.</p> <a class="gray-btn sbtn close">Close</a> </div> <div class="suggest-failed hide"> <h2>Sumbission failed</h2> <p>For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.</p> <a class="gray-btn sbtn close">Close</a> </div> <div class="suggest-form clear"> <label for="suggest_name">Your name</label> <input id="suggest_name" type="text"> </input> <label for="suggest_email">Your email</label> <input id="suggest_email" type="email"> </input> <label for="suggest_body" class="clear">Suggestion <span class="r">*</span></label> <textarea id="suggest_body" class="req"> </textarea> <button id="suggest_submit" class="blue-btn mr10">Submit suggestion</button> <p class="mb0"> <a class="cancel left lh42 cn">Cancel</a> </p> </div> </div> </div> <a href='../Manual/class-Light.html' title='Go to Light Component in the Manual' class='switch-link gray-btn sbtn left show'>Switch to Manual</a> <div class="clear"> </div> </div> <div class="subsection"> <div class="signature"> <div class="signature-JS sig-block">public var <span class="sig-kw">intensity</span>: float; </div> <div class="signature-CS sig-block">public float <span class="sig-kw">intensity</span>; </div> </div> </div> <div class="subsection"> <h2>Description</h2> <p>The Intensity of a light is multiplied with the Light color.</p> </div> <div class="subsection"> <p>The value can be between 0 and 8. This allows you to create over bright lights.</p> </div> <div class="subsection"> <pre class="codeExampleJS">// Pulse light's intensity over time. var duration : float= 1.0;<br /><br />var lt: <a href="Light.html">Light</a>;<br /><br /> function Start() { lt = GetComponent.&lt;Light&gt;(); }<br /><br /> function Update() { // Argument for cosine. var phi: float = <a href="Time-time.html">Time.time</a> / duration * 2 * <a href="Mathf.PI.html">Mathf.PI</a>; // Get cosine and transform from -1..1 to 0..1 range. var amplitude: float = <a href="Mathf.Cos.html">Mathf.Cos</a>(phi) * 0.5 + 0.5; // Set light color. lt.intensity = amplitude; }</pre> <pre class="codeExampleCS">using UnityEngine; using System.Collections;<br /><br />public class ExampleClass : <a href="MonoBehaviour.html">MonoBehaviour</a> { public float duration = 1.0F; public <a href="Light.html">Light</a> lt; void Start() { lt = GetComponent&lt;Light&gt;(); } void Update() { float phi = <a href="Time-time.html">Time.time</a> / duration * 2 * <a href="Mathf.PI.html">Mathf.PI</a>; float amplitude = <a href="Mathf.Cos.html">Mathf.Cos</a>(phi) * 0.5F + 0.5F; lt.intensity = amplitude; } } </pre> </div> </div> <div class="footer-wrapper"> <div class="footer clear"> <div class="copy">Copyright ยฉ 2014 Unity Technologies</div> <div class="menu"> <a href="http://unity3d.com/learn">Learn</a> <a href="http://unity3d.com/community">Community</a> <a href="http://unity3d.com/asset-store">Asset Store</a> <a href="https://store.unity3d.com">Buy</a> <a href="http://unity3d.com/unity/download">Download</a> </div> </div> </div> </div> </div> </div> </div> </body> </html>
rakuten/Uinty3D-Docs-zhcn
ScriptReference/Light-intensity.html
HTML
gpl-3.0
11,511
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy 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. | // | | // | System Syzygy 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 details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ use std::rc::Rc; use super::scenes; use crate::elements::{FadeStyle, PuzzleCmd, PuzzleCore, PuzzleView}; use crate::gui::{ Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources, Sound, }; use crate::modes::SOLVED_INFO_TEXT; use crate::save::{Game, LineState, PuzzleState}; // ========================================================================= // pub struct View { core: PuzzleCore<()>, grid1: LetterGrid, grid2: LetterGrid, answers: AnswersDisplay, delay: i32, } impl View { pub fn new( resources: &mut Resources, visible: Rect, state: &LineState, ) -> View { let mut core = { let fade = (FadeStyle::LeftToRight, FadeStyle::LeftToRight); let intro = scenes::compile_intro_scene(resources); let outro = scenes::compile_outro_scene(resources); PuzzleCore::new(resources, visible, state, fade, intro, outro) }; core.add_extra_scene(scenes::compile_ugrent_midscene(resources)); View { core, grid1: LetterGrid::new(resources, 80, 48, false), grid2: LetterGrid::new(resources, 320, 48, true), answers: AnswersDisplay::new(resources, 168, 272), delay: 0, } } } impl Element<Game, PuzzleCmd> for View { fn draw(&self, game: &Game, canvas: &mut Canvas) { let state = &game.cross_the_line; self.core.draw_back_layer(canvas); self.grid1.draw(state, canvas); self.grid2.draw(state, canvas); self.answers.draw(state, canvas); self.core.draw_middle_layer(canvas); self.core.draw_front_layer(canvas, state); } fn handle_event( &mut self, event: &Event, game: &mut Game, ) -> Action<PuzzleCmd> { let state = &mut game.cross_the_line; let mut action = self.core.handle_event(event, state); if !action.should_stop() && event == &Event::ClockTick { if self.delay > 0 { self.delay -= 1; if self.delay == 0 { self.grid1.reset(); self.grid2.reset(); if state.is_solved() { self.core.begin_outro_scene(); action = action.and_return(PuzzleCmd::Save); } action.also_redraw(); } } } if !action.should_stop() && self.delay == 0 { let mut subaction = self.grid1.handle_event(event, state); if !subaction.should_stop() { subaction.merge(self.grid2.handle_event(event, state)); } if let Some(&()) = subaction.value() { if let Some(index1) = self.grid1.selected { if let Some(index2) = self.grid2.selected { self.grid1.override_grid = Some((state.num_cols(), state.grid1().to_vec())); self.grid2.override_grid = Some((state.num_cols(), state.grid2().to_vec())); self.delay = 20; if state.pick_chars(index1, index2) { action.also_play_sound(Sound::mid_puzzle_chime()); } else { self.grid1.error = true; self.grid2.error = true; action.also_play_sound(Sound::talk_annoyed_hi()); } } } } action.merge(subaction.but_no_value()); } if !action.should_stop() && self.delay == 0 { let subaction = self.answers.handle_event(event, state); action.merge(subaction.but_no_value()); } if !action.should_stop() && self.delay == 0 { self.core.begin_character_scene_on_click(event); } action } } impl PuzzleView for View { fn info_text(&self, game: &Game) -> &'static str { if game.cross_the_line.is_solved() { SOLVED_INFO_TEXT } else { INFO_BOX_TEXT } } fn undo(&mut self, _: &mut Game) {} fn redo(&mut self, _: &mut Game) {} fn reset(&mut self, game: &mut Game) { self.core.clear_undo_redo(); game.cross_the_line.reset(); } fn solve(&mut self, game: &mut Game) { game.cross_the_line.solve(); self.core.begin_outro_scene(); } fn drain_queue(&mut self) { for entry in self.core.drain_queue() { match entry { (0, -1) => { self.grid1.override_grid = Some((1, Vec::new())); self.grid2.override_grid = Some((1, Vec::new())); } (0, 0) => { self.grid1.override_grid = None; self.grid2.override_grid = None; } (0, 1) => { self.grid1.override_grid = Some((4, "SAFE".chars().collect())); self.grid2.override_grid = Some((4, "FACE".chars().collect())); } (1, index) => { if index >= 0 { self.grid1.selected = Some(index as usize); } else { self.grid1.selected = None; } } (2, index) => { if index >= 0 { self.grid2.selected = Some(index as usize); } else { self.grid2.selected = None; } } (3, hide) => { self.answers.filtered = hide != 0; } _ => {} } } } } // ========================================================================= // const BOX_USIZE: u32 = 24; const BOX_SIZE: i32 = BOX_USIZE as i32; const MAX_GRID_WIDTH: u32 = 176; const MAX_GRID_HEIGHT: u32 = 144; struct LetterGrid { left: i32, top: i32, is_grid_2: bool, font: Rc<Font>, selected: Option<usize>, override_grid: Option<(i32, Vec<char>)>, error: bool, } impl LetterGrid { fn new( resources: &mut Resources, left: i32, top: i32, is_grid_2: bool, ) -> LetterGrid { LetterGrid { left, top, is_grid_2, font: resources.get_font("block"), selected: None, override_grid: None, error: false, } } fn reset(&mut self) { self.selected = None; self.override_grid = None; self.error = false; } fn max_rect(&self) -> Rect { Rect::new(self.left, self.top, MAX_GRID_WIDTH, MAX_GRID_HEIGHT) } fn grid_rect(&self, num_cols: i32, num_chars: usize) -> Rect { let num_rows = (num_chars as i32 + num_cols - 1) / num_cols; let width = num_cols * BOX_SIZE; let height = num_rows * BOX_SIZE; let left = self.left + (MAX_GRID_WIDTH as i32 - width) / 2; let top = self.top + (MAX_GRID_HEIGHT as i32 - height) / 2; Rect::new(left, top, width as u32, height as u32) } } impl Element<LineState, ()> for LetterGrid { fn draw(&self, state: &LineState, canvas: &mut Canvas) { let (num_cols, grid) = if let Some((num_cols, ref grid)) = self.override_grid { (num_cols, grid.as_slice()) } else if self.is_grid_2 { (state.num_cols(), state.grid2()) } else { (state.num_cols(), state.grid1()) }; let grid_rect = self.grid_rect(num_cols, grid.len()); let mut col = 0; let mut row = 0; for (index, &chr) in grid.iter().enumerate() { let box_left = grid_rect.left() + col * BOX_SIZE; let box_top = grid_rect.top() + row * BOX_SIZE; if self.selected == Some(index) { let rect = Rect::new(box_left, box_top, BOX_USIZE, BOX_USIZE); let color = if self.error { (128, 64, 64) } else { (255, 255, 128) }; canvas.fill_rect(color, rect); } let pt = Point::new(box_left + BOX_SIZE / 2, box_top + BOX_SIZE - 3); canvas.draw_char(&self.font, Align::Center, pt, chr); col += 1; if col >= num_cols { col = 0; row += 1; } } } fn handle_event( &mut self, event: &Event, state: &mut LineState, ) -> Action<()> { match event { &Event::MouseDown(pt) => { let num_cols = state.num_cols(); let num_chars = if self.is_grid_2 { state.grid2().len() } else { state.grid1().len() }; let rect = self.grid_rect(num_cols, num_chars); let mut new_selected = self.selected; if rect.contains_point(pt) { let col = (pt.x() - rect.left()) / BOX_SIZE; let row = (pt.y() - rect.top()) / BOX_SIZE; let index = (row * num_cols + col) as usize; if index >= num_chars || self.selected == Some(index) { new_selected = None; } else { new_selected = Some(index); } } else if self.max_rect().contains_point(pt) { new_selected = None; } if new_selected != self.selected { self.selected = new_selected; return Action::redraw().and_return(()); } } _ => {} } Action::ignore() } } // ========================================================================= // const FILTER: &[(bool, bool)] = &[ (true, false), (false, false), (true, false), (false, true), (true, true), (false, false), (false, true), (false, false), (true, false), (false, true), ]; struct AnswersDisplay { left: i32, top: i32, font: Rc<Font>, filtered: bool, } impl AnswersDisplay { fn new(resources: &mut Resources, left: i32, top: i32) -> AnswersDisplay { AnswersDisplay { left, top, font: resources.get_font("block"), filtered: false, } } } impl Element<LineState, ()> for AnswersDisplay { fn draw(&self, state: &LineState, canvas: &mut Canvas) { for stage in 0..state.current_stage() { let (chr1, chr2) = state.stage_letters(stage); let cx = self.left + stage * BOX_SIZE + BOX_SIZE / 2; if !self.filtered || FILTER[stage as usize].0 { let pt1 = Point::new(cx, self.top + BOX_SIZE - 3); canvas.draw_char(&self.font, Align::Center, pt1, chr1); } if !self.filtered || FILTER[stage as usize].1 { let pt2 = Point::new(cx, self.top + 2 * BOX_SIZE - 3); canvas.draw_char(&self.font, Align::Center, pt2, chr2); } } } fn handle_event( &mut self, event: &Event, _state: &mut LineState, ) -> Action<()> { match event { _ => Action::ignore(), } } } // ========================================================================= // const INFO_BOX_TEXT: &str = "\ Your goal is to find the discrepancy between the two upper grids. Each of the two upper grids contains a character that does not appear in the other. $M{Tap}{Click} each of those two characters to proceed. If you choose incorrectly, the grids will rescramble and you will have to try again. $M{Tap}{Click} on a character in the scene to hear their words of wisdom."; // ========================================================================= //
mdsteele/syzygy
src/modes/line/view.rs
Rust
gpl-3.0
13,630
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Golden T Studios - GTGE Tutorial 12</title> <meta name="keywords" content="small and fast java game engine, 2D game engine, java game library, games, game tutorial, sprite library, game development, game tools, game utilities" /> <!-- css, javascript --> <link rel="stylesheet" type="text/css" href="webstyle/tutorial.css" /> <link rel="shortcut icon" href="webstyle/favicon.ico" /> </head> <body> <table width="100%" style="padding: 0px; margin: 0px" cellpadding="0" cellspacing="0" bgcolor="#ffcccc" border="0"><tr><td background="webstyle/top_left.gif" width="20" height="18"></td><td background="webstyle/top.gif" height="18"></td><td background="webstyle/top_right.gif" width="20" height="18"></td></tr><tr><td background="webstyle/left.gif" width="20"></td><td bgcolor="#ffffff" style="padding: 15px" valign="top"> <!-- CONTENTS --> <h3>Tutorial 12</h3> <h1 style="margin-top: 0px">END OF TUTORIAL??</h1> <blockquote>This chapter explains other important things for game development.<br /> Objective : Understand other GTGE components.</blockquote> <script type="text/javascript" language="Javascript"><!-- function showContent() { if (document.getElementById('content').style.display == 'none') { document.getElementById('content').style.display = 'block'; } else { document.getElementById('content').style.display = 'none'; } } // --></script> <div align="right"><small><a href="javascript:showContent()">collapse/expand</a></small></div> <div id="content"> <hr /> <h3>Game Distribution</h3> <p><b>Before distributing the game</b>, make sure this code has been added to the <code>Game</code> class <b><code>{ distribute = true; }</code></b> : <pre> file :: YourGame.java <span class="comment">// JFC</span> <span class="keyword">import</span> java.awt.Graphics2D; <span class="comment">// GTGE</span> <span class="keyword">import</span> com.golden.gamedev.Game; <span class="keyword">public class</span> YourGame <span class="keyword">extends</span> Game { <b>{ distribute = true; }</b> <span class="keyword">public</span> <span class="primitive">void</span><span class="method"> initResources</span>() { } <span class="keyword">public</span> <span class="primitive">void</span><span class="method"> update</span>(<span class="primitive">long</span> elapsedTime) { } <span class="keyword">public</span> <span class="primitive">void</span><span class="method"> render</span>(Graphics2D g) { } } </pre> <code>{ distribute = true; }</code> mark the game that the game is ready to distribute, thus GTGE will <b>remove fps counter</b>, and also <b>catch any unexpected error/bugs</b> from your game (if any) and <b>show it to the player</b> in GUI form and ask them to send it to your email.</p> <p>And for the usual way to distribute the game is by packing the game in <b>compressed JAR form</b> (similar like ZIP file format), and later can be processed in <b>Webstart</b>, <b>Applet</b>, etc. Use <a target="_blank" href="http://goldenstudios.or.id/products/utilities/jarmaker/">Jar Maker</a> utility to pack your game in JAR, Webstart, or Applet.</p> <h3>End of GTGE Tutorial</h3> <p>GTGE Tutorial has ended, but GTGE still has lots features that you could dig deeper in <b><a target="_blank" href="../docs/index.html">GTGE API Documentation</a></b>, such as : <ul> <li>Bitmap font (font that using images).</li> <li>Image manipulation.</li> <li>Sprite rendering based on position/z-depth/etc.</li> <li>Separate game entities (separate game title, option logic, from the real game logic).</li> <li>ETC.</li> </ul> </p> <p>The GTGE API Documentation is easy to understand because in the header of <b>each class and package</b>, there is a <b>brief description</b> of what is the class or the package about and how to use it.</p> <p>Besides of developing GTGE library as the main engine to create games, we also develop <b>game tools to make your game development even easier</b> and develop some <b>add-ons to extend GTGE functional</b> (like add-ons for playing MP3 and OGG audio format) that you can download freely at <b><a target="_blank" href="http://goldenstudios.or.id/products/utilities/">game development utilities</a></b> section in our site.</p> <p>To make you more understand of <b>how GTGE game is actually created</b>, you could see <b>source code of games we made</b> with GTGE at <b><a target="_blank" href="http://goldenstudios.or.id/products/games/">game</a></b> section in our site (generally source code of games we made is available for public).</p> <p>For <b>*any* questions/troubles/features request/bugs report</b> that related with Java, GTGE, or even specific to your game, <b>can be asked in our <a target="_blank" href="http://goldenstudios.or.id/forum/">dedicated forum</a></b>, we will do our best to answer any questions!<br /> And there are also some <b>articles and tutorials of making game</b> that come from us or other GTGE user in the forum, so be sure to visit it!</p> <p>Finally, we want this tutorial <b>as simple as possible!</b> easy to understand by novice and expert Java programmer. So if you feel this tutorial is hard or confusing, <b>drop me a line at <a href="mailto:pauwui@yahoo.com">pauwui@yahoo.com</a></b> and tell which part that confusing you, or which part that you feel difficult so we can simplify it a bit.<br /> Or if you have other technique to make this tutorial even simpler, don't hesitate to contact us.<br /> And note that English is not our primary language (hope you not recognized this much in this tutorial), if you find wrong vocab, grammar, structure, etc, please be kind by correcting it and send it to us.<br /> <b><u>Thank you</u></b></p> <p>Till we meet again.......<br /> &nbsp;&nbsp;&nbsp;Thank you for using Golden T Game Engine (GTGE) Frame Work</p> <p>Happy Coding! :-)</p> <p>&nbsp;</p> <p>Written by,<br /> <br /> <b>Paulus Tuerah<br /> Golden T Game Engine Developer<br /> <a href="http://goldenstudios.or.id">http://www.goldenstudios.or.id/</a></b></p> <hr /> <h3>Very Important Note</h3> <p><b>Golden T Game Engine (GTGE)</b> is <b>freeware library!</b><br /> You can <b>download</b>, <b>distribute</b>, and <b>sell any game</b> produced with GTGE commercially, <b>free of charge!</b> And even if you like to, you could put your game in our site Game Showcase and order us to sell it!</p> <p>There is only <b>one thing that you must remember to do</b>, you should <b>mention</b> that the game is <b>made using GTGE</b> and <b>provide direct link to GTGE official site</b> (www.goldenstudios.or.id). You could write it inside the game or in the web page where the game directly download / played, or other place that you think more appropriate. In other words <b>credits to us, Golden T Studios, must stay intact!</b></p> <p>If you feel GTGE is great and help you a lots, you could also <b>help us</b> to keep working on it and improve GTGE feature and quality in many way, from not cost you any penny to direct donation. Some of what you can do to help us are : <ul> <li><b>Spread words</b> about GTGE to your friends, classmate, forum you visit, family :-) etc.</li> <li>Actively in our <b><a target="_blank" href="http://goldenstudios.or.id/forum/">forum</a></b>.</li> <li>Visit our <b>sponsor</b>.</li> <li><b>Buy books or merchandise</b> from our sponsor (<a target="_blank" href="http://www.amazon.com/exec/obidos/redirect-home/goldentstudio-20">amazon affiliate site</a>).</li> <li>Directly <b><a target="_blank" href="https://www.bitpass.com/donation/000007E3/donate/">donate</a></b> to our account, you could donate as small as $0.01.</li> <li><b>Share your sales a bit for us</b>, whether you success selling game you made by GTGE.</li> <li>ETC.</li> </ul> <b>Thanks for your support!</b></p> <div align="right"><small><a href="javascript:showContent()">collapse/expand</a></small></div> </div> <hr /> <p><b><u>Summary</u> :</b> <ul> <li>There are still <b>lots features of GTGE</b> that haven't covered in this tutorial, for complete things you can do with GTGE, please read <b>GTGE API Documentation</b>.</li> <li>Add this code <b><code>{ distribute = true; }</code></b> in your game class, right when your game is ready to distribute.</li> <li>Always <b>distribute</b> your game in <b>JAR form</b> (similar like ZIP format), use <b>JAR tool</b> that has been included in Java standard tool.</li> <li><b>Visit our forum</b> to ask <b>*any* problems</b> with Java, GTGE, and your game.</li> <li><b>GTGE</b> is <b>freeware library!</b> There are many ways you could do to help us, from not cost you any penny to direct donation. Please see our site FAQ section or in our forum for how you could help us to keep working and improving GTGE. (thanks!)</li> </ul> </p> <p> <script type="text/javascript"><!-- google_ad_client = "pub-8240742718872820"; google_alternate_ad_url = "http://goldenstudios.or.id/products/games/bin/amazonads.php"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_channel ="7844728614"; google_color_border = "084079"; google_color_bg = "FFFFFF"; google_color_link = "000000"; google_color_url = "FFFFFE"; google_color_text = "000000"; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </p> <p>Reference : <a target="_blank" href="../docs/index.html">GTGE API Documentation</a>, <a target="_blank" href="http://goldenstudios.or.id/forum/">GTGE Forum</a>, <a target="_blank" href="http://goldenstudios.or.id/products/utilities/">Game Development Utilities</a></p> <table width="96%" class="navpage" align="center" summary=""> <tr> <td style="padding-bottom: 8px"> <a href="tutorial1.html" onmouseover="window.status='Preface';return true" onmouseout="window.status=''">1</a> <a href="tutorial2.html" onmouseover="window.status='Installation';return true" onmouseout="window.status=''">2</a> <a href="tutorial3.html" onmouseover="window.status='GTGE API Overview';return true" onmouseout="window.status=''">3</a> <a href="tutorial4.html" onmouseover="window.status='Starting the Game';return true" onmouseout="window.status=''">4</a> <a href="tutorial5.html" onmouseover="window.status='Choosing Game Environment';return true" onmouseout="window.status=''">5</a> <a href="tutorial6.html" onmouseover="window.status='Revealing the Engines Ability';return true" onmouseout="window.status=''">6</a> <a href="tutorial7.html" onmouseover="window.status='Sprite';return true" onmouseout="window.status=''">7</a> <a href="tutorial8.html" onmouseover="window.status='Background';return true" onmouseout="window.status=''">8</a> <a href="tutorial9.html" onmouseover="window.status='Grouping Your Sprites';return true" onmouseout="window.status=''">9</a> <a href="tutorial10.html" onmouseover="window.status='Missing Some Collisions!?';return true" onmouseout="window.status=''">10</a> <a href="tutorial11.html" onmouseover="window.status='Its Play Time!';return true" onmouseout="window.status=''">11</a> <a href="tutorial12.html" onmouseover="window.status='End of Tutorial??';return true" onmouseout="window.status=''">12</a> </td> </tr> <tr> <td><a class="nextpage" href="tutorial11.html" onmouseover="window.status='Its Play Time!';return true" onmouseout="window.status=''">ยซ Previous Page</a></td> </tr> </table> <!-- END-CONTENTS --> </div> <!-- FOOTER --> </td><td background="webstyle/right.gif" width="20"></td></tr><tr><td background="webstyle/bottom_left.gif" width="20" height="20"></td><td background="webstyle/bottom.gif" height="20"></td><td background="webstyle/bottom_right.gif" width="20" height="20"></td></tr></table> <table width="100%"> <tr> <td align="left" style="padding-left: 10px"> <small class="copyright">Copyright ยฉ 2003-2005 Golden T Studios. All rights reserved. Use is subject to <a target="_blank" href="http://creativecommons.org/licenses/by/2.0/">license terms</a>.<br /> <a class="copyright" target="_blank" href="http://www.goldenstudios.or.id/">GoldenStudios.or.id</a></small> </td> <td align="right" valign="top" style="padding-right: 5px"> <span style="color: #666666">Page 12 of 12</span> </td> </tr> </table> <!-- END OF FOOTER --> </body> </html> <!-- END -->
idega/com.idega.games
docs/GTGE/tutorials/tutorial12.html
HTML
gpl-3.0
12,740
/*! * \file * * Copyright (c) 2010 Johann A. Briffa * * This file is part of SimCommSys. * * SimCommSys 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. * * SimCommSys 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 SimCommSys. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __repacc_h #define __repacc_h #include "config.h" #include "codec_softout.h" #include "memoryless.h" #include "fsm.h" #include "interleaver.h" #include "safe_bcjr.h" namespace libcomm { /*! * \brief Repeat-Accumulate (RA) codes. * \author Johann Briffa * * These codes are decoded using the MAP decoder, rather than the * sum-product algorithm. * * \todo Avoid divisions when computing extrinsic information * * \todo Implement accumulator as mapcc * * \todo Generalize repeater and accumulator */ template <class real, class dbl = double> class repacc : public codec_softout<libbase::vector, dbl> { private: // Shorthand for class hierarchy typedef repacc<real, dbl> This; public: /*! \name Type definitions */ typedef libbase::vector<int> array1i_t; typedef libbase::vector<dbl> array1d_t; typedef libbase::matrix<dbl> array2d_t; typedef libbase::vector<array1d_t> array1vd_t; // @} private: /*! \name User-defined parameters */ //! Interleaver between repeater and accumulator boost::shared_ptr<interleaver<dbl> > inter; //! Memoryless codec representation of repetition code memoryless<dbl> rep; boost::shared_ptr<fsm> acc; //!< Encoder representation of accumulator int iter; //!< Number of iterations to perform bool endatzero; //!< Flag to indicate that trellises are terminated dbl limitlo; //!< Lower clipping threshold // @} protected: /*! \name Internal object representation */ safe_bcjr<real, dbl> BCJR; //!< BCJR algorithm implementation bool initialised; //!< Flag to indicate when memory is initialised array1vd_t rp; //!< Intrinsic source statistics (natural) array2d_t ra; //!< Extrinsic accumulator-input statistics (natural) array2d_t R; //!< Intrinsic accumulator-output statistics (interleaved) // @} protected: /*! \name Internal functions */ void init(); void reset(); //! Memory allocator (for internal use only) void allocate(); //! Determine the number of timesteps for the accumulator int acc_timesteps() const { // Inherit sizes const int Nr = rep.output_block_size(); const int k = acc->num_inputs(); const int nu = endatzero ? acc->mem_order() : 0; return Nr / k + nu; } // @} // Internal codec operations void resetpriors(); void setpriors(const array1vd_t& ptable); void setreceiver(const array1vd_t& ptable); // Interface with derived classes void advance() const { // Advance interleaver to the next block inter->advance(); } void do_encode(const array1i_t& source, array1i_t& encoded); void do_init_decoder(const array1vd_t& ptable) { setreceiver(ptable); resetpriors(); } void do_init_decoder(const array1vd_t& ptable, const array1vd_t& app) { setreceiver(ptable); setpriors(app); } public: /*! \name Constructors / Destructors */ repacc() { } ~repacc() { } // @} // Codec operations void seedfrom(libbase::random& r) { // Call base method first codec_softout<libbase::vector, dbl>::seedfrom(r); // Seed interleaver inter->seedfrom(r); } void softdecode(array1vd_t& ri); void softdecode(array1vd_t& ri, array1vd_t& ro); // Codec information functions - fundamental libbase::size_type<libbase::vector> input_block_size() const { // Inherit sizes const int N = rep.input_block_size(); return libbase::size_type<libbase::vector>(N); } libbase::size_type<libbase::vector> output_block_size() const { // Inherit sizes const int k = acc->num_inputs(); const int n = acc->num_outputs(); const int tau = acc_timesteps(); // Calculate internal sizes const int p = n - k; return libbase::size_type<libbase::vector>(tau * p); } int num_inputs() const { return acc->num_symbols(); } int num_outputs() const { return acc->num_symbols(); } int num_iter() const { return iter; } /*! \name Codec information functions - internal */ int num_repeats() const { return int(round(log(rep.num_outputs()) / log(rep.num_inputs()))); } const boost::shared_ptr<interleaver<dbl> > get_inter() const { return inter; } // @} // Description std::string description() const; // Serialization Support DECLARE_SERIALIZER(repacc) }; } // end namespace #endif
jbresearch/simcommsys
Libraries/Libcomm/codec/repacc.h
C
gpl-3.0
5,275
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>main.cpp Example File | Qt Data Visualization 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtdatavisualization-index.html">Qt Data Visualization</a></td><td ><a href="qtdatavisualization-qmlscatter-example.html">Qt Quick 2 Scatter Example</a></td><td >main.cpp Example File</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"><div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">main.cpp Example File</h1> <span class="subtitle">qmlscatter/main.cpp</span> <!-- $$$qmlscatter/main.cpp-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> <span class="comment">/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Data Visualization module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/</span> <span class="preprocessor">#include &lt;QtGui/QGuiApplication&gt;</span> <span class="preprocessor">#include &lt;QtCore/QDir&gt;</span> <span class="preprocessor">#include &lt;QtQuick/QQuickView&gt;</span> <span class="preprocessor">#include &lt;QtQml/QQmlEngine&gt;</span> <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>) { <span class="type"><a href="../qtgui/qguiapplication.html">QGuiApplication</a></span> app(argc<span class="operator">,</span> argv); <span class="type"><a href="../qtquick/qquickview.html">QQuickView</a></span> viewer; <span class="comment">// The following are needed to make examples run without having to install the module</span> <span class="comment">// in desktop environments.</span> <span class="preprocessor">#ifdef Q_OS_WIN</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> extraImportPath(<span class="type"><a href="../qtcore/qstring.html#QStringLiteral">QStringLiteral</a></span>(<span class="string">&quot;%1/../../../../%2&quot;</span>)); <span class="preprocessor">#else</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> extraImportPath(<span class="type"><a href="../qtcore/qstring.html#QStringLiteral">QStringLiteral</a></span>(<span class="string">&quot;%1/../../../%2&quot;</span>)); <span class="preprocessor">#endif</span> viewer<span class="operator">.</span>engine()<span class="operator">-</span><span class="operator">&gt;</span>addImportPath(extraImportPath<span class="operator">.</span>arg(<span class="type"><a href="../qtgui/qguiapplication.html">QGuiApplication</a></span><span class="operator">::</span>applicationDirPath()<span class="operator">,</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span><span class="operator">::</span>fromLatin1(<span class="string">&quot;qml&quot;</span>))); <span class="type"><a href="../qtcore/qobject.html">QObject</a></span><span class="operator">::</span>connect(viewer<span class="operator">.</span>engine()<span class="operator">,</span> <span class="operator">&amp;</span><span class="type"><a href="../qtqml/qqmlengine.html">QQmlEngine</a></span><span class="operator">::</span>quit<span class="operator">,</span> <span class="operator">&amp;</span>viewer<span class="operator">,</span> <span class="operator">&amp;</span><span class="type"><a href="../qtgui/qwindow.html">QWindow</a></span><span class="operator">::</span>close); viewer<span class="operator">.</span>setTitle(<span class="type"><a href="../qtcore/qstring.html#QStringLiteral">QStringLiteral</a></span>(<span class="string">&quot;QML scatter example&quot;</span>)); viewer<span class="operator">.</span>setSource(<span class="type"><a href="../qtcore/qurl.html">QUrl</a></span>(<span class="string">&quot;qrc:/qml/qmlscatter/main.qml&quot;</span>)); viewer<span class="operator">.</span>setResizeMode(<span class="type"><a href="../qtquick/qquickview.html">QQuickView</a></span><span class="operator">::</span>SizeRootObjectToView); viewer<span class="operator">.</span>showMaximized(); <span class="keyword">return</span> app<span class="operator">.</span>exec(); } </pre> </div> <!-- @@@qmlscatter/main.cpp --> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
angeloprudentino/QtNets
Doc/qtdatavisualization/qtdatavisualization-qmlscatter-main-cpp.html
HTML
gpl-3.0
7,071
#include <QUuid> #include <QString> #include "ientity.h" SOFT_BEGIN_NAMESPACE class IEntity::Private { friend class IEntity; Private(std::string const &id) : uuid(id.c_str()) {} Private() : uuid(QUuid::createUuid()) {} QUuid uuid; }; /*! Constructs a new entity (A new \em uuid will generated and assigned) */ IEntity :: IEntity() :d (new IEntity::Private()) {} /*! Constructs an entity with a given \a uuid */ IEntity :: IEntity(std::string const &uuid) : d(new IEntity::Private(uuid)) {} /*! Construct entity from another entity */ IEntity :: IEntity(IEntity const *other) : d(other != nullptr ? new IEntity::Private(other->id()) : new IEntity::Private()) {} /*! Destroy the entity */ IEntity :: ~IEntity() { delete d; } /*! */ IEntity* create (const std::string &uuid) { return nullptr; } /*! Get the entity unique identitier */ std::string IEntity :: id() const { return d->uuid.toString().toStdString(); } /*! Set the entity unique identitier \warning Do not use this unless you really know what you are doing!!! */ void IEntity :: setId(const std::string &id) { d->uuid = QUuid(id.c_str()); } SOFT_END_NAMESPACE
NanoSim/Porto
core/src/kernel/ientity.cpp
C++
gpl-3.0
1,192
<?php /* * Copyright 2014-2021 GPLv3, Open Crypto Portfolio Tracker by Mike Kilday: http://DragonFrugal.com */ error_reporting(0); // Turn off all error reporting (0), or enable (1) $runtime_mode = 'download'; // Flag as CSV export BEFORE config.php (to run minimized logic from init.php) if ( $_GET['csv_export'] == 1 ) { $is_csv_export = true; } // Flag as notes download BEFORE config.php (to run minimized logic from init.php) else if ( $_GET['notes'] == 1 ) { $is_notes = true; } require("config.php"); // Backups download if ( $_GET['backup'] != null ) { require_once( $base_dir . "/app-lib/php/other/downloads/backups.php"); } // NO LOGS / DEBUGGING / MESSAGE SENDING AT RUNTIME END HERE // (WE ALWAYS EXIT BEFORE HERE IN EACH REQUIRED FILE, OR WE SKIP IT FOR MINIMIZED RUNTIME LOGIC ETC) ?>
taoteh1221/DFD_Cryptocoin_Values
download.php
PHP
gpl-3.0
814
// // DHHBannerView.h // AntiqueCatalog // // Created by Cangmin on 16/1/4. // Copyright ยฉ 2016ๅนด Cangmin. All rights reserved. // #import <UIKit/UIKit.h> @class DHHBannerView; @protocol DHHBannerViewDelegate <NSObject> @optional - (void)bannerView:(DHHBannerView *)bannerView didClickedImageIndex:(NSInteger)index; @end @interface DHHBannerView : UIView #pragma mark - Class methods /** * init a LCBannerView object from local * * @param frame frame * @param delegate delegate * @param imageName image name. eg: `banner_01@2x.png`, `banner_02@2x.png`... you should set it `banner` * @param count images count * @param timeInterval time interval * @param currentPageIndicatorTintColor current page indicator tint color * @param pageIndicatorTintColor other page indicator tint color * * @return a LCBannerView object */ + (instancetype)bannerViewWithFrame:(CGRect)frame delegate:(id<DHHBannerViewDelegate>)delegate imageName:(NSString *)imageName count:(NSInteger)count timerInterval:(NSInteger)timeInterval currentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor pageIndicatorTintColor:(UIColor *)pageIndicatorTintColor; /** * init a LCBannerView object from internet * * @param frame frame * @param delegate delegate * @param imageURLs image's URLs * @param placeholderImage placeholder image * @param timeInterval time interval * @param currentPageIndicatorTintColor current page indicator tint color * @param pageIndicatorTintColor other page indicator tint color * * @return a LCBannerView object */ + (instancetype)bannerViewWithFrame:(CGRect)frame delegate:(id<DHHBannerViewDelegate>)delegate imageURLs:(NSArray *)imageURLs placeholderImage:(NSString *)placeholderImage timerInterval:(NSInteger)timeInterval currentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor pageIndicatorTintColor:(UIColor *)pageIndicatorTintColor; #pragma mark - Instance methods /** * init a LCBannerView object from local * * @param frame frame * @param delegate delegate * @param imageName image name. eg: `banner_01@2x.png`, `banner_02@2x.png`... you should set it `banner` * @param count images count * @param timeInterval time interval * @param currentPageIndicatorTintColor current page indicator tint color * @param pageIndicatorTintColor other page indicator tint color * * @return a LCBannerView object */ - (instancetype)initWithFrame:(CGRect)frame delegate:(id<DHHBannerViewDelegate>)delegate imageName:(NSString *)imageName count:(NSInteger)count timerInterval:(NSInteger)timeInterval currentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor pageIndicatorTintColor:(UIColor *)pageIndicatorTintColor; /** * init a LCBannerView object from internet * * @param frame frame * @param delegate delegate * @param imageURLs image's URLs * @param placeholderImage placeholder image * @param timeInterval time interval * @param currentPageIndicatorTintColor current page indicator tint color * @param pageIndicatorTintColor other page indicator tint color * * @return a LCBannerView object */ - (instancetype)initWithFrame:(CGRect)frame delegate:(id<DHHBannerViewDelegate>)delegate imageURLs:(NSArray *)imageURLs placeholderImage:(NSString *)placeholderImage timerInterval:(NSInteger)timeInterval currentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor pageIndicatorTintColor:(UIColor *)pageIndicatorTintColor; @end
xiaohe2014/AntiqueCatalog
AntiqueCatalog/AntiqueCatalog/First(้ฆ–้กต)/View/DHHBannerView.h
C
gpl-3.0
4,301
package creOrthologs; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.List; import parsers.FastaSequence; public class ExtractOne { public static void main(String[] args) throws Exception { List<FastaSequence> list = FastaSequence.readFastaFile( "/nobackup/afodor_research/af_broad/carolina/klebsiella_pneumoniae_chs_11.0.scaffolds.fasta"); String toFind = "7000000220927531"; BufferedWriter writer = new BufferedWriter(new FileWriter(new File( "/projects/afodor_research/af_broad/individualBlastRuns/contig_" + toFind + File.separator + toFind + ".fasta"))); for(FastaSequence fs : list) { if(fs.getFirstTokenOfHeader().equals(toFind)) { writer.write(fs.getHeader() + "\n"); writer.write(fs.getSequence().substring(2482, 4032) + "\n"); } } writer.flush(); writer.close(); } }
afodor/clusterstuff
src/creOrthologs/ExtractOne.java
Java
gpl-3.0
933
# Copyright (C) 2005 - 2021 Settlers Freaks <sf-team at siedler25.org> # # SPDX-License-Identifier: GPL-2.0-or-later option(RTTR_ENABLE_WERROR "Build with warnings turned into errors" ON) function(enable_warnings target) get_target_property(targetType ${target} TYPE) if(targetType STREQUAL "INTERFACE_LIBRARY") set(visibility INTERFACE) else() set(visibility PUBLIC) endif() if(MSVC) target_compile_options(${target} ${visibility} /W3 /MP # parallel compilation /w34062 # Enum not handled in switch /w34388 # Signed/Unsigned operations (undocumented) /w34389 # Signed/Unsigned operations /wd4127 # conditional expr is constant /wd4250 # 'class1' : inherits 'class2::member' via dominance (virtual inheritance related) /wd4267 # 'var' : conversion from 'size_t' to 'type', possible loss of data /wd4373 # override where const in parameters differs handled differently in pre VS2008 /wd4512 # assignment operator could not be created ) target_compile_definitions(${target} ${visibility} _CRT_SECURE_NO_WARNINGS _SCL_SECURE_NO_WARNINGS # disable "use secure function" _CRT_NONSTDC_NO_DEPRECATE # disable MSVC posix functions -D_WINSOCK_DEPRECATED_NO_WARNINGS ) if(RTTR_ENABLE_WERROR) target_compile_options(${target} ${visibility} /WX) # warning = error endif() else() target_compile_options(${target} ${visibility} -Wall -pedantic -Wextra) if(RTTR_ENABLE_WERROR) target_compile_options(${target} ${visibility} -Werror) endif() include(CheckAndAddWarnings) # Additional options besides -Wall, -Wextra, -pedantic # Keep those sorted to check for uniqueness check_and_add_warnings(TARGET ${target} VISIBILITY ${visibility} ALL -Wno-unused-command-line-argument CXX -fno-strict-aliasing -pedantic-errors -Qunused-arguments -Wcast-qual #-Wconversion -Wdisabled-optimization -Wfloat-conversion -Wformat-nonliteral -Wformat-security -Wformat=2 -Wimport -Winit-self #-Winline -Wlogical-op -Wmissing-declarations -Wmissing-field-initializers -Wmissing-format-attribute -Wmissing-include-dirs -Wmissing-noreturn #-Wold-style-cast -Wpacked -Wparentheses -Wpedantic -Wpointer-arith #-Wshadow #-Wsign-conversion # Lot's of work, maybe later? -Wstrict-aliasing=2 -Wundef -Wunused -Wunused-parameter -Wwrite-strings -Wno-unknown-pragmas -Wctor-dtor-privacy -Wnoexcept -Woverloaded-virtual -Wstrict-null-sentinel -Wno-maybe-uninitialized # False positives e.g. with variant/optional -Wno-error=inconsistent-missing-override ) if(NOT WIN32) # Lot's of false-positives on windows. # E.g. __builtin_ia32_crc32qi on MinGW and SDL check_and_add_warnings(TARGET ${target} VISIBILITY ${visibility} CXX -Wredundant-decls) endif() # Prior to 9.2 "final" was not considered "override" if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 9.2) target_compile_options(${target} ${visibility} $<$<COMPILE_LANGUAGE:CXX>:-Wsuggest-override -Wno-error=suggest-override>) endif() if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") # Lot's of false-positives on for e.g. strcmp check_and_add_warnings(TARGET ${target} VISIBILITY ${visibility} CXX -Wunreachable-code) elseif(CMAKE_CXX_COMPILER_VERSION VERSION_LESS "6" OR CMAKE_CXX_COMPILER_ID MATCHES "AppleClang") # Wrong warnings for std::array until clang 6 target_compile_options(${target} ${visibility} -Wno-missing-braces) endif() if(CMAKE_CXX_COMPILER_ID MATCHES "AppleClang" OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10.0)) # To many false positives until clang 10 fixed them check_and_add_warnings(TARGET ${target} VISIBILITY ${visibility} CXX -Wno-range-loop-analysis) endif() # Not used: #-Wpadded #-Wstack-protector #-Wswitch-default #-Wswitch-enum #-Wfloat-equal #-Wcast-align #-Wstrict-overflow=2 # To many false positives #-Wsign-promo # std::to_string(uint8_t{42}) should work endif() endfunction()
Return-To-The-Roots/libutil
cmake/EnableWarnings.cmake
CMake
gpl-3.0
4,455
#include <gtest/gtest.h> #include <stdint.h> #include <zmq.h> #include <algorithm> #include <array> #include <atomic> #include <chrono> #include <cstddef> #include <cstring> #include <future> #include <iterator> #include <memory> #include <thread> #include <type_traits> #include <utility> #include <vector> #include "SimpleLogger/logger.hpp" #include "byteMessage.hpp" #include "config.hpp" #include "crypto.hpp" #include "helper.hpp" #include "server.hpp" #include "simpleMsgQueue.hpp" using namespace std::chrono_literals; constexpr int CLIENT_TIMEOUT = 1000; // timeout in ms class TestServer: public server::Server { private: std::size_t _counter; public: TestServer(const TestServer&) = delete; TestServer& operator=(const TestServer&) = delete; TestServer(port_t port, std::shared_ptr<server::IMsgQueue> queue): Server(port, queue), _counter(0) { } virtual ~TestServer() = default; void sleep() override { std::this_thread::sleep_for(100ms); } bool process(server::IMsgQueue::Messages&& popped) override { _counter += 1; Log::debug("Server processes message #%d", _counter); return server::Server::process(std::move(popped)); } }; class Server: public ::testing::Test { public: std::shared_ptr<server::SimpleMsgQueue> msgQueue; TestServer server; std::thread serverThread; void *clientContext; void *clientSocket; Server() : msgQueue(std::make_shared<server::SimpleMsgQueue>()), server(8888, msgQueue), serverThread([this]() { this->server.run(); }), clientContext(zmq_ctx_new()), clientSocket(zmq_socket(clientContext, ZMQ_SUB)) { /* * Sleep for a short period of time to prevent slow starter syndrome */ std::this_thread::sleep_for(100ms); zmq_connect(clientSocket, "tcp://localhost:8888"); zmq_setsockopt(clientSocket, ZMQ_RCVTIMEO, &CLIENT_TIMEOUT, sizeof(CLIENT_TIMEOUT)); } virtual ~Server() { zmq_close(clientSocket); zmq_ctx_destroy(clientContext); server.stop(); serverThread.join(); } void subscribeClient(const std::vector<byte>& topic) { zmq_setsockopt(clientSocket, ZMQ_SUBSCRIBE, &topic[0], topic.size()); } bool recvNextMsgAsClient(std::vector<byte>& bytes, bool& more) { zmq_msg_t part; zmq_msg_init(&part); { int rc = zmq_recvmsg(clientSocket, &part, 0); if (rc == -1) { Log::error("Error during receiving: %s", zmq_strerror(errno)); zmq_msg_close(&part); return false; } } const auto size = zmq_msg_size(&part); // std::vector::reserve does not work with std::memcpy bytes = std::vector<byte>(size); std::memcpy(bytes.data(), zmq_msg_data(&part), size); more = [socket = this->clientSocket]() { std::int64_t more; auto sizeOfMore = sizeof(more); zmq_getsockopt(socket, ZMQ_RCVMORE, &more, &sizeOfMore); return (more != 0); }(); zmq_msg_close(&part); return true; } }; inline ::testing::AssertionResult equal(const std::vector<byte>& a, const std::vector<byte>& b) { auto sizeOfA = a.size(); auto sizeOfB = b.size(); if (sizeOfA != sizeOfB) { return ::testing::AssertionFailure() << "amount of stored data differs" << "; " << sizeOfA << " != " << sizeOfB; } for (std::size_t i = 0; i < sizeOfA; ++i) { if (a[i] != b[i]) { return ::testing::AssertionFailure() << "stored data mismatch at postion " << i << "; " << static_cast<int>(a[i]) << " != " << static_cast<int>(b[i]); } } return ::testing::AssertionSuccess(); } inline ::testing::AssertionResult noErrorDuringRecv(bool rc) { if (rc) { return ::testing::AssertionSuccess(); } return ::testing::AssertionFailure() << "error during receiving. Maybe a timeout?"; } TEST(ToLittleEndian, ConvertsIntegerCorrectly) { const int x = 256; auto bytes = server::Server::toLittleEndian(x); ASSERT_TRUE(equal(bytes, { 0x00, 0x00, 0x01, 0x00 })); } constexpr crypto::Key TESTKEY { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; inline server::IMsgQueue::Messages createNewTestMessages( const std::vector<byte>& testData, const std::uint32_t topicID) { auto *msg = createMsg(TESTKEY, testData); ++currentlyAllocatedMsgInstances; return server::IMsgQueue::Messages(topicID, { std::make_pair(msg, &deleteMsg) }); } TEST_F(Server, cryptsMessages) { constexpr std::size_t NMSGS = 1; const std::vector<byte> testData { 0x04, 0x08, 0x15, 0x10, 0x17, 0x2a }; constexpr std::uint32_t topicID = 108; subscribeClient(server::Server::toLittleEndian(topicID)); std::vector<server::IMsgQueue::Messages> vmsgs; ASSERT_EQ(currentlyAllocatedMsgInstances.load(), 0); for (std::size_t i = 0; i < NMSGS; ++i) { vmsgs.push_back(createNewTestMessages(testData, topicID)); } ASSERT_EQ(currentlyAllocatedMsgInstances.load(), NMSGS); using bytes = std::vector<byte>; std::vector<bytes> bytesRecvByClient; auto rc = std::async(std::launch::async, [&]() { bytes b; bool more; do { Log::debug("Client is waiting for a new message ..."); bool rc = recvNextMsgAsClient(b, more); Log::debug("Client received a new message."); if (!rc || bytesRecvByClient.size() > 2) { return false; } bytesRecvByClient.push_back(b); } while (more); return true; }); for (auto&& msgs : vmsgs) { Log::debug("Pushing new messages ..."); msgQueue->push(std::move(msgs)); // std::this_thread::sleep_for(100ms); } /* * rc.get() blocks until either * -> all messages are received by the client, or * -> an error occurs */ ASSERT_TRUE(noErrorDuringRecv(rc.get())); ASSERT_EQ(bytesRecvByClient.size(), 3); struct RecvBytes { bytes topicID; bytes iv; bytes cipher; } recvBytes; recvBytes.topicID = std::move(bytesRecvByClient[0]); recvBytes.iv = std::move(bytesRecvByClient[1]); recvBytes.cipher = std::move(bytesRecvByClient[2]); // topic ID ASSERT_TRUE(equal( recvBytes.topicID, server::Server::toLittleEndian(topicID) )); Log::debug("Topic ID was submitted successfully"); // IV crypto::IV iv; ASSERT_EQ(recvBytes.iv.size(), iv.size()); Log::debug("IV was submitted successfully"); std::copy_n( std::make_move_iterator(recvBytes.iv.begin()), iv.size(), iv.begin() ); // CIPHER crypto::decrypt(&recvBytes.cipher[0], recvBytes.cipher.size(), TESTKEY, iv); ASSERT_TRUE(equal(recvBytes.cipher, testData)); Log::debug("Cipher was submitted successfully"); for (std::size_t i= 0; currentlyAllocatedMsgInstances.load() != 0; ++i) { if (i > 10) { break; } std::this_thread::sleep_for(10ms); } ASSERT_EQ(currentlyAllocatedMsgInstances.load(), 0); }
Tondorf/gravioli
server/test/test_server.cpp
C++
gpl-3.0
7,611
/* dsa-keygen.c * * Generation of DSA keypairs */ /* nettle, low-level cryptographics library * * Copyright (C) 2013, 2014 Red Hat * * The nettle library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * The nettle library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the nettle library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02111-1301, USA. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <assert.h> #include <stdlib.h> #include <string.h> #include <nettle/dsa.h> #include <dsa-fips.h> #include <nettle/bignum.h> unsigned _dsa_check_qp_sizes(unsigned q_bits, unsigned p_bits, unsigned generate) { switch (q_bits) { case 160: if (_gnutls_fips_mode_enabled() != 0 && generate != 0) return 0; if (p_bits != 1024) return 0; break; case 224: if (p_bits != 2048) return 0; break; case 256: if (p_bits != 2048 && p_bits != 3072) return 0; break; default: return 0; } return 1; } /* This generates p,q params using the A.1.2.1 algorithm in FIPS 186-4. * * The hash function used is SHA384. */ int _dsa_generate_dss_pq(struct dsa_params *params, struct dss_params_validation_seeds *cert, unsigned seed_length, void *seed, void *progress_ctx, nettle_progress_func * progress, unsigned p_bits /* = L */ , unsigned q_bits /* = N */ ) { mpz_t r, p0, t, z, s, tmp, dp0; int ret; unsigned iterations, old_counter, i; uint8_t *storage = NULL; unsigned storage_length = 0; ret = _dsa_check_qp_sizes(q_bits, p_bits, 1); if (ret == 0) { return 0; } if (seed_length < q_bits / 8) { _gnutls_debug_log("Seed length must be larger than %d bytes (it is %d)\n", q_bits/8, seed_length); return 0; } mpz_init(p0); mpz_init(dp0); mpz_init(r); mpz_init(t); mpz_init(z); mpz_init(s); mpz_init(tmp); /* firstseed < 2^(N-1) */ mpz_set_ui(r, 1); mpz_mul_2exp(r, r, q_bits - 1); nettle_mpz_set_str_256_u(s, seed_length, seed); if (mpz_cmp(s, r) < 0) { goto fail; } cert->qseed_length = sizeof(cert->qseed); cert->pseed_length = sizeof(cert->pseed); ret = st_provable_prime(params->q, &cert->qseed_length, cert->qseed, &cert->qgen_counter, q_bits, seed_length, seed, progress_ctx, progress); if (ret == 0) { goto fail; } if (progress) progress(progress_ctx, 'q'); ret = st_provable_prime(p0, &cert->pseed_length, cert->pseed, &cert->pgen_counter, 1 + div_ceil(p_bits, 2), cert->qseed_length, cert->qseed, progress_ctx, progress); if (ret == 0) { goto fail; } iterations = div_ceil(p_bits, DIGEST_SIZE*8); old_counter = cert->pgen_counter; if (iterations > 0) { storage_length = iterations * DIGEST_SIZE; storage = malloc(storage_length); if (storage == NULL) { goto fail; } nettle_mpz_set_str_256_u(s, cert->pseed_length, cert->pseed); for (i = 0; i < iterations; i++) { cert->pseed_length = nettle_mpz_sizeinbase_256_u(s); nettle_mpz_get_str_256(cert->pseed_length, cert->pseed, s); hash(&storage[(iterations - i - 1) * DIGEST_SIZE], cert->pseed_length, cert->pseed); mpz_add_ui(s, s, 1); } /* x = 2^(p_bits-1) + (x mod 2^(p_bits-1)) */ nettle_mpz_set_str_256_u(tmp, storage_length, storage); } mpz_set_ui(r, 1); mpz_mul_2exp(r, r, p_bits - 1); mpz_mod_2exp(tmp, tmp, p_bits - 1); mpz_add(tmp, tmp, r); /* Generate candidate prime p in [2^(bits-1), 2^bits] */ /* t = u[x/2c0] */ mpz_mul_2exp(dp0, p0, 1); /* dp0 = 2*p0 */ mpz_mul(dp0, dp0, params->q); /* dp0 = 2*p0*q */ mpz_cdiv_q(t, tmp, dp0); retry: /* c = 2p0*q*t + 1 */ mpz_mul(params->p, dp0, t); mpz_add_ui(params->p, params->p, 1); if (mpz_sizeinbase(params->p, 2) > p_bits) { /* t = 2^(bits-1)/2qp0 */ mpz_set_ui(tmp, 1); mpz_mul_2exp(tmp, tmp, p_bits - 1); mpz_cdiv_q(t, tmp, dp0); /* p = t* 2tq p0 + 1 */ mpz_mul(params->p, dp0, t); mpz_add_ui(params->p, params->p, 1); } cert->pgen_counter++; mpz_set_ui(r, 0); if (iterations > 0) { for (i = 0; i < iterations; i++) { cert->pseed_length = nettle_mpz_sizeinbase_256_u(s); nettle_mpz_get_str_256(cert->pseed_length, cert->pseed, s); hash(&storage[(iterations - i - 1) * DIGEST_SIZE], cert->pseed_length, cert->pseed); mpz_add_ui(s, s, 1); } /* r = a */ nettle_mpz_set_str_256_u(r, storage_length, storage); } cert->pseed_length = nettle_mpz_sizeinbase_256_u(s); nettle_mpz_get_str_256(cert->pseed_length, cert->pseed, s); /* a = 2 + (a mod (p-3)) */ mpz_sub_ui(tmp, params->p, 3); /* c is too large to worry about negatives */ mpz_mod(r, r, tmp); mpz_add_ui(r, r, 2); /* z = a^(2tq) mod p */ mpz_mul_2exp(tmp, t, 1); /* tmp = 2t */ mpz_mul(tmp, tmp, params->q); /* tmp = 2tq */ mpz_powm(z, r, tmp, params->p); mpz_sub_ui(tmp, z, 1); mpz_gcd(tmp, tmp, params->p); if (mpz_cmp_ui(tmp, 1) == 0) { mpz_powm(tmp, z, p0, params->p); if (mpz_cmp_ui(tmp, 1) == 0) { goto success; } } if (progress) progress(progress_ctx, 'x'); if (cert->pgen_counter >= (4 * p_bits + old_counter)) return 0; mpz_add_ui(t, t, 1); goto retry; success: if (progress) progress(progress_ctx, 'p'); ret = 1; goto finish; fail: ret = 0; finish: mpz_clear(dp0); mpz_clear(p0); mpz_clear(tmp); mpz_clear(t); mpz_clear(z); mpz_clear(s); mpz_clear(r); free(storage); return ret; } int _dsa_generate_dss_g(struct dsa_params *params, unsigned domain_seed_size, const uint8_t* domain_seed, void *progress_ctx, nettle_progress_func * progress, unsigned index) { mpz_t e, w; uint16_t count; uint8_t *dseed = NULL; unsigned dseed_size; unsigned pos; uint8_t digest[DIGEST_SIZE]; int ret; if (index > 255 || domain_seed_size == 0) return 0; dseed_size = domain_seed_size + 4 + 1 + 2; dseed = malloc(dseed_size); if (dseed == NULL) return 0; mpz_init(e); mpz_init(w); memcpy(dseed, domain_seed, domain_seed_size); pos = domain_seed_size; memcpy(dseed + pos, "\x67\x67\x65\x6e", 4); pos += 4; *(dseed + pos) = (uint8_t) index; pos += 1; mpz_sub_ui(e, params->p, 1); mpz_fdiv_q(e, e, params->q); for (count = 1; count < 65535; count++) { *(dseed + pos) = (count >> 8) & 0xff; *(dseed + pos + 1) = count & 0xff; hash(digest, dseed_size, dseed); nettle_mpz_set_str_256_u(w, DIGEST_SIZE, digest); mpz_powm(params->g, w, e, params->p); if (mpz_cmp_ui(params->g, 2) >= 0) { /* found */ goto success; } if (progress) progress(progress_ctx, 'x'); } /* if we're here we failed */ if (progress) progress(progress_ctx, 'X'); ret = 0; goto finish; success: if (progress) progress(progress_ctx, 'g'); ret = 1; finish: free(dseed); mpz_clear(e); mpz_clear(w); return ret; } /* Generates the public and private DSA (or DH) keys */ void _dsa_generate_dss_xy(struct dsa_params *params, mpz_t y, mpz_t x, void *random_ctx, nettle_random_func * random) { mpz_t r; mpz_init(r); mpz_set(r, params->q); mpz_sub_ui(r, r, 2); nettle_mpz_random(x, random_ctx, random, r); mpz_add_ui(x, x, 1); mpz_powm(y, params->g, x, params->p); mpz_clear(r); } /* This generates p, q, g params using the algorithms from FIPS 186-4. * For p, q, the Shawe-Taylor algorithm is used. * For g, the verifiable canonical generation of the generator is used. * * The hash function used is SHA384. * * pub: The output public key * key: The output private key * cert: A certificate that can be used to verify the generated parameters * index: 1 for digital signatures (DSA), 2 for key establishment (DH) * p_bits: The requested size of p * q_bits: The requested size of q * */ int dsa_generate_dss_pqg(struct dsa_params *params, struct dss_params_validation_seeds *cert, unsigned index, void *random_ctx, nettle_random_func * random, void *progress_ctx, nettle_progress_func * progress, unsigned p_bits /* = L */ , unsigned q_bits /* = N */ ) { int ret; uint8_t domain_seed[MAX_PVP_SEED_SIZE*3]; unsigned domain_seed_size = 0; ret = _dsa_check_qp_sizes(q_bits, p_bits, 1); if (ret == 0) return 0; cert->seed_length = 2 * (q_bits / 8) + 1; if (cert->seed_length > sizeof(cert->seed)) return 0; random(random_ctx, cert->seed_length, cert->seed); ret = _dsa_generate_dss_pq(params, cert, cert->seed_length, cert->seed, progress_ctx, progress, p_bits, q_bits); if (ret == 0) return 0; domain_seed_size = cert->seed_length + cert->qseed_length + cert->pseed_length; memcpy(domain_seed, cert->seed, cert->seed_length); memcpy(&domain_seed[cert->seed_length], cert->pseed, cert->pseed_length); memcpy(&domain_seed[cert->seed_length+cert->pseed_length], cert->qseed, cert->qseed_length); ret = _dsa_generate_dss_g(params, domain_seed_size, domain_seed, progress_ctx, progress, index); if (ret == 0) return 0; return 1; } int _dsa_generate_dss_pqg(struct dsa_params *params, struct dss_params_validation_seeds *cert, unsigned index, unsigned seed_size, void *seed, void *progress_ctx, nettle_progress_func * progress, unsigned p_bits /* = L */ , unsigned q_bits /* = N */ ) { int ret; uint8_t domain_seed[MAX_PVP_SEED_SIZE*3]; unsigned domain_seed_size = 0; ret = _dsa_check_qp_sizes(q_bits, p_bits, 1); if (ret == 0) return 0; if (_gnutls_fips_mode_enabled() != 0) { cert->seed_length = 2 * (q_bits / 8) + 1; if (cert->seed_length != seed_size) { _gnutls_debug_log("Seed length must be %d bytes (it is %d)\n", cert->seed_length, seed_size); return 0; } } else { cert->seed_length = seed_size; } if (cert->seed_length > sizeof(cert->seed)) return 0; memcpy(cert->seed, seed, cert->seed_length); ret = _dsa_generate_dss_pq(params, cert, cert->seed_length, cert->seed, progress_ctx, progress, p_bits, q_bits); if (ret == 0) return 0; domain_seed_size = cert->seed_length + cert->qseed_length + cert->pseed_length; memcpy(domain_seed, cert->seed, cert->seed_length); memcpy(&domain_seed[cert->seed_length], cert->pseed, cert->pseed_length); memcpy(&domain_seed[cert->seed_length+cert->pseed_length], cert->qseed, cert->qseed_length); ret = _dsa_generate_dss_g(params, domain_seed_size, domain_seed, progress_ctx, progress, index); if (ret == 0) return 0; return 1; } int dsa_generate_dss_keypair(struct dsa_params *params, mpz_t y, mpz_t x, void *random_ctx, nettle_random_func * random, void *progress_ctx, nettle_progress_func * progress) { _dsa_generate_dss_xy(params, y, x, random_ctx, random); if (progress) progress(progress_ctx, '\n'); return 1; }
attilamolnar/gnutls
lib/nettle/int/dsa-keygen-fips186.c
C
gpl-3.0
11,099
#include "contacts.h" #include <malloc.h> int main() { contPtr info = (contPtr)malloc(sizeof(struct contacts)); info->name = "1"; vertexPtr rear = initVertex(info); rear = addVertexRelationOnName(rear, "1", "4"); rear = addVertexRelationOnName(rear, "4", "2"); rear = addVertexRelationOnName(rear, "2", "1"); rear = addVertexRelationOnName(rear, "5", "1"); rear = addVertexRelationOnName(rear, "2", "3"); vertexPtr target = getVertexBasedOnName(rear, "4"); vertexPtr src = getVertexBasedOnName(rear, "2"); bool e = DFS(src, target); e = 0; e = BFS(src, target); return 0; }
ScarlettCanaan/mylife
data_structure/hwFinal/testcase.c
C
gpl-3.0
607
start_proxy() { # Accept one connection from mfsmount on the fake port socat tcp-listen:$1,reuseaddr system:" socat stdio tcp\:$(get_ip_addr)\:$2 | # connect to real server { dd bs=1k count=12k ; # forward 12MB sleep 1d ; # and go catatonic }" & } if ! is_program_installed socat; then test_fail "Configuration error, please install 'socat'" fi timeout_set 1 minute CHUNKSERVERS=4 \ DISK_PER_CHUNKSERVER=1 \ MOUNT_EXTRA_CONFIG="mfscachemode=NEVER" \ USE_RAMDISK=YES \ setup_local_empty_lizardfs info dir="${info[mount0]}/dir" mkdir "$dir" lizardfs setgoal xor3 "$dir" FILE_SIZE=123456789 file-generate "$dir/file" # Find any chunkserver serving part 1 of some chunk csid=$(find_first_chunkserver_with_chunks_matching 'chunk_xor_1_of_3*') port=${info[chunkserver${csid}_port]} # Limit data transfer from this chunkserver start_proxy $port $((port + 1000)) lizardfs_chunkserver_daemon $csid stop LD_PRELOAD="${LIZARDFS_INSTALL_FULL_LIBDIR}/libredirect_bind.so" lizardfs_chunkserver_daemon $csid start lizardfs_wait_for_all_ready_chunkservers if ! file-validate "$dir/file"; then test_add_failure "Data read from file is different than written" fi
lizardfs/lizardfs
tests/test_suites/ShortSystemTests/test_cs_failure_during_xor_read.sh
Shell
gpl-3.0
1,211
<?php /************************************************** * PHP DEBUGGER **************************************************/ /************************************************** * @package phpDebugger * @subpackage core * @version 1.01 * @build 1042 **************************************************/ /************************************************** * @author: Roman Matthias Keil * @copyright: Roman Matthias Keil **************************************************/ Application::import('config.debugger'); Application::import('core.debugger.Debugger'); class DebuggerFactory { /** * @var Debugger */ private static $debugger = null; /** * @param string $_level * @return unknown_type */ static function getInstance() { if(!isset(DebuggerFactory::$debugger)) DebuggerFactory::$debugger = new Debugger(); return DebuggerFactory::$debugger; } } ?>
keil/phpDebugger
core/classes/debugger/DebuggerFactory.class.php
PHP
gpl-3.0
892
import { NgModule } from '@angular/core'; import { MdAutocompleteModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdCheckboxModule, MdChipsModule, MdCoreModule, MdDatepickerModule, MdDialogModule, MdExpansionModule, MdGridListModule, MdIconModule, MdInputModule, MdListModule, MdMenuModule, MdNativeDateModule, MdProgressBarModule, MdProgressSpinnerModule, MdRadioModule, MdRippleModule, MdSelectModule, MdSidenavModule, MdSliderModule, MdSlideToggleModule, MdSnackBarModule, MdSortModule, MdTableModule, MdTabsModule, MdToolbarModule, MdTooltipModule, } from '@angular/material'; @NgModule({ exports: [ MdAutocompleteModule, MdButtonModule, MdButtonToggleModule, MdCardModule, MdCheckboxModule, MdChipsModule, MdCoreModule, MdDatepickerModule, MdDialogModule, MdExpansionModule, MdGridListModule, MdIconModule, MdInputModule, MdListModule, MdMenuModule, MdNativeDateModule, MdProgressBarModule, MdProgressSpinnerModule, MdRadioModule, MdRippleModule, MdSelectModule, MdSidenavModule, MdSliderModule, MdSlideToggleModule, MdSnackBarModule, MdSortModule, MdTableModule, MdTabsModule, MdToolbarModule, MdTooltipModule, ] }) export class MaterialModule {}
timdavish/TopTraining2
client/src/app/shared/material.module.ts
TypeScript
gpl-3.0
1,328
<?php /** * @since Created on 24 Jun 2012 * @package EveOnlineApi * @author Thies Wandschneider <thies@wandschneider.de> * @license GNU/LGPL, see COPYING * @link http://themanwiththehat.wordpress.com * * This file is part of the EveOnlineApi Plugin for cakePHP 2. * * The project is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The project is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this project. If not, see <http://www.gnu.org/licenses/>. */ App::uses('EveOnlineApiAppModel', 'EveOnlineApi.Model'); /** * MapSolarSystemJump Model * */ class MapSolarSystemJump extends EveOnlineApiAppModel { /** * Use database config * * @var string */ public $useDbConfig = 'evedump'; /** * Use table * * @var mixed False or table name */ public $useTable = 'mapSolarSystemJumps'; /** * Primary key field * * @var string */ public $primaryKey = 'fromSolarSystemID'; /** * Validation rules * * @var array */ public $validate = array( 'toSolarSystemID' => array( 'numeric' => array( 'rule' => array('numeric'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); }
TheManWithTheHat/EveOnlineApi
Model/MapSolarSystemJump.php
PHP
gpl-3.0
1,787
# mspa M Single Page Application ๋‹จ์ผ ํŽ˜์ด์ง€ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜(SPA)์€ "๋‹จ์ผ ํŽ˜์ด์ง€ ์›น" ๊ธ€์ž๋งŒ ๋นผ๋ฉด ๊ทธ๋ƒฅ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ž…๋‹ˆ๋‹ค. ์œˆ๋„์šฐ์— ์„ค์น˜ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” .exe ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ ๋ฐฉ์‹๊ณผ ํ•˜๋“ฑ ์ฐจ์ด๊ฐ€ ์—†๊ณ  ๋ณด์—ฌ์ง€๋Š” ๊ธฐ๋ฐ˜์ด ๋ธŒ๋ผ์šฐ์ €์•ˆ์ด๋ผ๋Š” ๊ฒƒ ๋ฐ–์— ์ฐจ์ด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ช‡๋…„์ „ ๋ฆฌ์น˜ ์ธํ„ฐ๋„ท ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜(RIA)๋ฅผ ์ด๋Œ์—ˆ๋˜ ํ”Œ๋ž™์Šค(Flex)๋ฅผ ๋– ์˜ฌ๋ ค๋„ ์ข‹์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ง€๊ธˆ์€ ๋ชจ๋ฐ”์ผ๊ณผ ์›น์˜ ์‹œ๋Œ€์ด๋‹ˆ HTML/CSS/JavaScript ๋งŒ์œผ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. MSPA ํ”„๋ ˆ์ž„์›Œํฌ๋Š” HTML์—์„œ ๋ถ€์กฑํ•œ ๋ ˆ์ด์•„์›ƒ๊ธฐ๋Šฅ์„ ๋‹จ์ผํŽ˜์ด์ง€์— ๋งž๊ฒŒ ์ฒ˜๋ฆฌํ•ด ์ฃผ๋Š” ๋ ˆ์ด์•„์›ƒ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ๋˜ํ•œ ๋‹ค ์ˆ˜์˜ ๊ฐœ๋ณ„ํ™”๋ฉด๋“ค์„ ๋™์ ์œผ๋กœ ๋กœ๋”ฉํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์„œ, ๋งŽ์€ ์ˆ˜์˜ ๋‹จ์œ„ํ™”๋ฉด๊ณผ ํŒ์—…ํ™”๋ฉด์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. MSPA ํ”„๋ ˆ์ž„์›Œํฌ๋Š” ๋‹จ์œ„ํ™”๋ฉด๊ณผ ํŒ์—…ํ™”๋ฉด์„ ๋งŒ๋“œ๋Š” ์ผ๊ด€์„ฑ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋งŽ์€ ์ˆ˜์˜ ํ™”๋ฉด์ด ์žˆ์–ด๋„ ๊ทธ ๊ตฌ์กฐ ๋™์ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์œ ์ง€๊ด€๋ฆฌ๊ฐ€ ์šฉ์ดํ•ฉ๋‹ˆ๋‹ค. MSPA ํ”„๋ ˆ์ž„์›Œํฌ๋Š” Restful API์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์ฒ˜๋ฆฌํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์„œ๋ฒ„์™€์˜ ๋ฐ์ดํ„ฐํ†ต์‹ ์„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๊ตฌ์„ฑ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. # ๋ ˆ์ด์•„์›ƒ ์ปดํฌ๋„ŒํŠธ ์†Œ๊ฐœ # ํ•„์š”์„ฑ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ฒ˜๋Ÿผ ๋ธŒ๋ผ์šฐ์ฆˆ์˜ ํฌ๊ธฐ๋ณ€ํ™”์— ๋”ฐ๋ผ ๋‚ด๋ถ€ ์ปจํŠธ๋กค๋“ค์ด ์ž๋™์œผ๋กœ ์žฌ๋ฐฐ์น˜ ๋˜๋Š” ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๊ฐ ์ปดํฌ๋„ŒํŠธ๊ฐ„์˜ ๋ฐฐ์น˜๋ฅผ ์ž๋™์œผ๋กœ ์„ค์ •ํ•ด ์ฃผ๋Š” ๋ ˆ์ด์•„์›ƒ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์›น์˜ CSS๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—๋Š” ํ”ฝ์…€๊ณผ ํผ์„ผํŠธ๋ฅผ ์ง€์›ํ•˜๋‚˜, ์ด๋ฅผ ํ˜ผ์šฉํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋Š” ๊ฒƒ์ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜๊ณผ ๊ฐ€์žฅ ํฐ ์ฐจ์ด์ ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ด๋ฅผ ํ˜ผ์šฉํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ณ , ๊ณ„์ธต๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค์ˆ˜ ์žˆ๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. # ์›๋ฆฌ divํƒœํฌ์˜ ์œ„์น˜์™€ ํฌ๊ธฐ๋ฅผ ์ œ์–ดํ•˜๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ์ด๊ฒƒ์„ ๋ถ€๋ชจ์™€ ์ž์‹๊ฐ„์˜ ๊ณ„์ธต๊ตฌ์กฐ๋กœ ๋งŒ๋“ญ๋‹ˆ๋‹ค. ๋ถ€๋ชจ์ปดํฌ๋„ŒํŠธ๋Š” ๋‹ค ์ˆ˜์˜ ์ž์‹์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋„๋ก ๋ฐฐ์—ด๋กœ ์ž์‹์ปดํฌ๋„ŒํŠธ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. ์ด๋“ค์„ HTML์˜ ํŠธ๋ฆฌ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ, ํ™”๋ฉด์ƒ์˜ ๋ ˆ์ด์•„์›ƒ ํŠธ๋ฆฌ๋กœ ์ธ์‹ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ๋ถ€๋ชจ์ปดํฌ๋„ŒํŠธ์˜ ๋ฐฐ์น˜๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ, ๋ถ€๋ชจ์ปดํฌ๋„ŒํŠธ์— ์„ค์ •ํ•œ ๊ทœ์น™์— ๋”ฐ๋ผ ์ž์‹์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ฐฐ์น˜ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. MComponent์˜ ๊ฐ€์žฅ ํฐ ํŠน์ง•์€ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์ด์ฆˆ ๋ณ€ํ™”๋ฅผ ๊ฐ์ง€ํ•˜๊ณ , ์ž์‹ ์˜ ํฌ๊ธฐ๋ฅผ ์žฌ์„ค์ •ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ์ตœ์ƒ์œ„์˜ MPageRootScreen์—์„œ ํฌ๊ธฐ๋ณ€ํ™”๋ฅผ ๊ฐ์ง€ํ•œ ํ›„, ์ปดํฌ๋„ŒํŠธ ๊ณ„์ธต๊ตฌ์กฐ๋ฅผ ํ†ตํ•ด ์žฌ๋ฐฐ์น˜๋ฅผ ๋ฉ”์†Œ๋“œ ํ˜ธ์ถœ๋กœ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋น ๋ฅด๊ฒŒ ์ฒ˜๋ฆฌ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.
mukeunkim/mspa
README.md
Markdown
gpl-3.0
2,825
๏ปฟ/* Post-Deployment Script Template -------------------------------------------------------------------------------------- This file contains SQL statements that will be appended to the build script. Use SQLCMD syntax to include a file in the post-deployment script. Example: :r .\myfile.sql Use SQLCMD syntax to reference a variable in the post-deployment script. Example: :setvar TableName MyTable SELECT * FROM [$(TableName)] -------------------------------------------------------------------------------------- */ -- ะ•ัะปะธ ะฝะตั‚ ะฑะปะพะณะพะฒ IF NOT EXISTS (SELECT * FROM [News].[Blog]) BEGIN DECLARE @adminId INT SELECT @adminId=UserId FROM [dbo].[User] WHERE Username='admin' SET IDENTITY_INSERT [News].[Blog] ON INSERT INTO [News].[Blog] ([BlogId], [Title], [OwnerId]) VALUES (1, N'ะะพะฒะพัั‚ะธ ัะฐะนั‚ะฐ', @adminId) INSERT INTO [News].[Blog_User] ([BlogId],[UserId]) VALUES (1, @adminId) SET IDENTITY_INSERT [News].[Blog] OFF END GO
synweb/rocms
News/RoCMS.News.Database/InitialData.sql
SQL
gpl-3.0
1,050
#include "moc_Uzytkownik.cpp" #include "Settings.h" /*! * init function read settings !*/ void Uzytkownik::init () { QSettings settings("elinux", "user"); nameEdit->setText (settings.value ("name").toString()); placeEdit->setText (settings.value ("city").toString()); codeEdit->setText (settings.value ("zip").toString()); addressEdit->setText (settings.value ("address").toString()); accountEdit->setText (settings.value ("account").toString()); if (!settings.value ("secIdType").isNull ()) { int current = secIdType->findText(settings.value ("secIdType").toString()); secIdType->setCurrentIndex (current); } nipEdit->setText (settings.value ("tic").toString()); regonEdit->setText (settings.value ("regon").toString()); // i guess it's statistical number nipEdit->setInputMask(sett().value("ticMask", "999-99-999-99; ").toString()); accountEdit->setInputMask(sett().value("accountMask", "99-9999-9999-9999-9999-9999-9999; ").toString()); } /*! * save settings !*/ void Uzytkownik::okClick () { QSettings settings("elinux", "user"); settings.setValue ("name", nameEdit->text ()); // zapis String settings.setValue ("city", placeEdit->text ()); settings.setValue ("zip", codeEdit->text ()); settings.setValue ("address", addressEdit->text ()); settings.setValue ("account", accountEdit->text ()); settings.setValue ("tic", nipEdit->text ()); settings.setValue ("secIdType", secIdType->currentText ()); settings.setValue ("regon", regonEdit->text ()); close (); } Uzytkownik::Uzytkownik(QWidget *parent): QDialog(parent) { setupUi(this); init(); }
rafalrusin/qfaktury
src/Uzytkownik.cpp
C++
gpl-3.0
1,619
# -*- encoding: utf-8 -*- from robottelo.constants import FILTER, FOREMAN_PROVIDERS from nailgun import entities from robottelo.ui.base import Base, UINoSuchElementError, UIError from robottelo.ui.locators import common_locators, locators, tab_locators from robottelo.ui.navigator import Navigator class ResourceProfileFormBase(object): """Base class for compute resources profiles forms""" _page = None # some fields are like two panel and to select from the left one to the # right as users groups and roles # please see how implemented in ResourceProfileFormEC2 for security_groups selector_fields = [] # some fields can be part of sections that can be added # like storage and networks, please check how implemented in # ResourceProfileFormRHEV (implement network_interfaces and storage) group_fields_locators = {} fetch_values_locators = {} def __init__(self, page): """Initiate compute resource profile form :type page: ComputeProfile :param page: The compute profile object ComputeProfile or ComputeResource """ self._page = page @property def page(self): """Return the current page ComputeResource or ComputeProfile""" return self._page def _clean_value(self, name, value): """Check some values and correct them accordingly""" if name in self.selector_fields: if not isinstance(value, (list, tuple)): value = [value] return value def _assign_locator_value(self, target, value): """Assign provided value to page element depending on the type of that element """ target_type = self.page.element_type(target) if (target_type == 'span' or target_type == 'select') and ' (' in value: # do all the necessary workaround self.page.click(target) # Typing entity value without parenthesis part self.page.assign_value( common_locators['select_list_search_box'], value.split(' (') [0]) # selecting Value by its full name (with parenthesis # part) self.page.click( common_locators['entity_select_list_vmware'] % value.split (' (')[0]) pass else: self.page.assign_value(target, value) def set_value(self, name, value): """Set the value of the corresponding field in UI""" locator_attr = '{0}_locator'.format(name) locator = getattr(self, locator_attr, None) if locator is None and name not in self.group_fields_locators: raise UIError('Field name: {0} not supported'.format(name)) value = self._clean_value(name, value) if name in self.selector_fields: self.page.configure_entity(value, locator) elif name in self.group_fields_locators: field_index = 0 group_fields_locators = self.group_fields_locators[name] add_node_locator = group_fields_locators['_add_node'] for group_field in value: if group_field is not None: for field_key, field_value in group_field.items(): field_locator = group_fields_locators.get(field_key) available_fields = self.page.find_elements( field_locator) if len(available_fields) - 1 < field_index: self.page.click(add_node_locator) available_fields = self.page.find_elements( field_locator) self._assign_locator_value( available_fields[field_index], field_value) field_index += 1 else: self._assign_locator_value(locator, value) def set_values(self, **kwargs): """Set the values of the corresponding fields in UI""" for key, value in kwargs.items(): self.set_value(key, value) def get_values(self, params_names): """Get the values of the corresponding fields in UI""" return_dict = {} for param_name in params_names: locator_attr = 'fetch_{0}_locator'.format(param_name) if locator_attr not in self.fetch_values_locators: raise UIError( 'Field name: {0} not supported'.format(param_name)) field_locator = self.fetch_values_locators[locator_attr] return_dict[param_name] = self.page.get_element_value( field_locator) return return_dict def submit(self): """Press the submit form button""" self.page.click(common_locators['submit']) class ResourceProfileFormEC2(ResourceProfileFormBase): """Implement EC2 compute resource profile form""" flavor_locator = locators["resource.compute_profile.ec2_flavor"] image_locator = locators["resource.compute_profile.ec2_image"] subnet_locator = locators["resource.compute_profile.ec2_subnet"] managed_ip_locator = locators["resource.compute_profile.ec2_managed_ip"] availability_zone_locator = locators[ "resource.compute_profile.ec2_availability_zone"] security_groups_locator = FILTER['ec2_security_groups'] selector_fields = ['security_groups'] def _clean_value(self, name, value): """Check some values and correct them accordingly""" value = ResourceProfileFormBase._clean_value(self, name, value) if not value: if name == 'availability_zone': value = 'No preference' elif name == 'subnet': value = 'EC2' elif name == 'security_groups': value = [] return value class ResourceProfileFormRHEV(ResourceProfileFormBase): """Implement RHEV compute resource profile form""" cluster_locator = locators["resource.compute_profile.rhev_cluster"] template_locator = locators["resource.compute_profile.rhev_template"] cores_locator = locators["resource.compute_profile.rhev_cores"] memory_locator = locators["resource.compute_profile.rhev_memory"] group_fields_locators = dict( network_interfaces=dict( _add_node=locators[ "resource.compute_profile.interface_add_node"], name=locators["resource.compute_profile.rhev_interface_name"], network=locators["resource.compute_profile.rhev_interface_network"] ), storage=dict( _add_node=locators[ "resource.compute_profile.storage_add_node"], size=locators["resource.compute_profile.rhev_storage_size"], storage_domain=locators[ "resource.compute_profile.rhev_storage_domain"], preallocate_disk=locators[ "resource.compute_profile.rhev_storage_preallocate"], bootable=locators["resource.compute_profile.rhev_storage_bootable"] ), ) fetch_values_locators = dict( fetch_cluster_locator=locators[ "resource.compute_profile.fetch_rhev_cluster"], fetch_cores_locator=locators["resource.compute_profile.rhev_cores"], fetch_memory_locator=locators["resource.compute_profile.rhev_memory"], fetch_size_locator=locators[ "resource.compute_profile.rhev_storage_size"], fetch_storage_domain_locator=locators[ "resource.compute_profile.fetch_rhev_storage_domain"], fetch_bootable_locator=locators[ "resource.compute_profile.rhev_storage_bootable"], fetch_preallocate_disk_locator=locators[ "resource.compute_profile.rhev_storage_preallocate"], ) def set_values(self, **kwargs): """Set the values of the corresponding fields in UI""" # if template is the fields to set, it set in priority as, when # selecting a template, configuration data is loaded in UI template_key = 'template' template = kwargs.get(template_key) if template is not None: self.set_value(template_key, template) del kwargs[template_key] # when setting memory value it does not fire the change event, # that do the necessary validation and update the memory hidden field, # without this event fired the memory value cannot be saved, memory_key = 'memory' memory = kwargs.get(memory_key) if memory is not None: memory_input = self.page.wait_until_element(self.memory_locator) self._assign_locator_value(memory_input, memory) # explicitly fire change event, as seems not fired by send keys self.page.browser.execute_script( "arguments[0].dispatchEvent(new Event('change'));", memory_input, ) del kwargs[memory_key] ResourceProfileFormBase.set_values(self, **kwargs) class ResourceProfileFormVMware(ResourceProfileFormBase): """Implement VMware compute resource profile form""" cpus_locator = locators["resource.compute_profile.vmware_cpus"] corespersocket_locator = locators[ "resource.compute_profile.vmware_corespersocket"] memory_locator = locators["resource.compute_profile.vmware_memory"] cluster_locator = locators["resource.compute_profile.vmware_cluster"] folder_locator = locators["resource.compute_profile.vmware_folder"] guest_os_locator = locators["resource.compute_profile.vmware_guest_os"] scsicontroller_locator = locators[ "resource.compute_profile.vmware_scsicontroller"] virtualhw_version_locator = locators[ "resource.compute_profile.vmware_virtualhw_version"] memory_hotadd_locator = locators[ "resource.compute_profile.vmware_memory_hotadd"] cpu_hotadd_locator = locators[ "resource.compute_profile.vmware_cpu_hotadd"] cdrom_drive_locator = locators[ "resource.compute_profile.vmware_cdrom_drive"] annotation_notes_locator = locators[ "resource.compute_profile.vmware_annotation_notes"] image_locator = locators["resource.compute_profile.rhev_image"] pool_locator = locators[ "resource.compute_profile.vmware_resource_pool"] group_fields_locators = dict( network_interfaces=dict( _add_node=locators[ "resource.compute_profile.interface_add_node"], name=locators["resource.compute_profile.vmware_interface_name"], network=locators[ "resource.compute_profile.vmware_interface_network"] ), storage=dict( _add_node=locators[ "resource.compute_profile.storage_add_node"], datastore=locators[ "resource.compute_profile.vmware_storage_datastore"], size=locators["resource.compute_profile.vmware_storage_size"], thin_provision=locators[ "resource.compute_profile.vmware_storage_thin_provision"], eager_zero=locators[ "resource.compute_profile.vmware_storage_eager_zero"], disk_mode=locators["resource.compute_profile.vmware_disk_mode"] ), ) _compute_resource_profiles = { FOREMAN_PROVIDERS['ec2']: ResourceProfileFormEC2, FOREMAN_PROVIDERS['rhev']: ResourceProfileFormRHEV, FOREMAN_PROVIDERS['vmware']: ResourceProfileFormVMware, } def get_compute_resource_profile(page, res_type=None): """Return the corresponding instance compute resource profile form object """ resource_profile_class = _compute_resource_profiles.get(res_type) if not resource_profile_class: raise UIError( 'Resource profile for resource type: {0}' ' not supported'.format(res_type) ) return resource_profile_class(page) class ComputeResource(Base): """Provides the CRUD functionality for Compute Resources.""" def navigate_to_entity(self): """Navigate to Compute Resource entity page""" Navigator(self.browser).go_to_compute_resources() def _search_locator(self): """Specify locator for Compute Resource entity search procedure""" return locators['resource.select_name'] def _configure_resource_provider( self, provider_type=None, parameter_list=None): """Provide configuration capabilities for compute resource provider. All values should be passed in absolute correspondence to UI. For example, we need to input some data to 'URL' field, select checkbox 'Console Passwords' and choose 'SPICE' value from select list, so next parameter list should be passed:: [ ['URL', libvirt_url, 'field'], ['Display Type', 'SPICE', 'select'], ['Console passwords', False, 'checkbox'] ] We have cases when it is necessary to push a button to populate values for select list. For such scenarios we have 'special select' parameter type. For example, for 'RHEV' provider, we need to click 'Load Datacenters' button to get values for 'Datacenter' list:: [ ['Description', 'My_Test', 'field'], ['URL', libvirt_url, 'field'], ['Username', 'admin', 'field'], ['Password', 'test', 'field'], ['X509 Certification Authorities', 'test', 'field'], ['Datacenter', 'test', 'special select'], ] """ if provider_type: self.select(locators['resource.provider_type'], provider_type) if parameter_list is None: return for parameter_name, parameter_value, parameter_type in parameter_list: if parameter_name.find('/') >= 0: _, parameter_name = parameter_name.split('/') param_locator = '.'.join(( 'resource', (parameter_name.lower()).replace(' ', '_') )) if parameter_type != 'special select': self.assign_value( locators[param_locator], parameter_value) else: button_locator = '.'.join(( 'resource', (parameter_name.lower()).replace(' ', '_'), 'button' )) self.click(locators[button_locator]) self.assign_value(locators[param_locator], parameter_value) def _configure_orgs(self, orgs, org_select): """Provides configuration capabilities for compute resource organization. The following format should be used:: orgs=['Aoes6V', 'JIFNPC'], org_select=True """ self.configure_entity( orgs, FILTER['cr_org'], tab_locator=tab_locators['tab_org'], entity_select=org_select ) def _configure_locations(self, locations, loc_select): """Provides configuration capabilities for compute resource location The following format should be used:: locations=['Default Location'], loc_select=True """ self.configure_entity( locations, FILTER['cr_loc'], tab_locator=tab_locators['tab_loc'], entity_select=loc_select ) def create(self, name, provider_type, parameter_list, orgs=None, org_select=None, locations=None, loc_select=None): """Creates a compute resource.""" self.click(locators['resource.new']) self.assign_value(locators['resource.name'], name) self._configure_resource_provider(provider_type, parameter_list) if locations: self._configure_locations(locations, loc_select) if orgs: self._configure_orgs(orgs, org_select) self.click(common_locators['submit']) def update(self, name, newname=None, parameter_list=None, orgs=None, org_select=None, locations=None, loc_select=None): """Updates compute resource entity.""" element = self.search(name) if element is None: raise UINoSuchElementError( 'Could not find the resource {0}'.format(name)) self.click(locators['resource.edit'] % name) self.wait_until_element(locators['resource.name']) if newname: self.assign_value(locators['resource.name'], newname) self._configure_resource_provider(parameter_list=parameter_list) if locations: self._configure_locations(locations, loc_select) if orgs: self._configure_orgs(orgs, org_select) self.click(common_locators['submit']) def search_container(self, cr_name, container_name): """Searches for specific container located in compute resource under 'Containers' tab """ self.search_and_click(cr_name) self.click(tab_locators['resource.tab_containers']) self.assign_value( locators['resource.filter_containers'], container_name) return self.wait_until_element( locators['resource.select_container'] % container_name) def list_vms(self, res_name): """Lists vms of a particular compute resource. Note: Currently lists only vms that show up on the first page. """ self.search_and_click(res_name) self.click(tab_locators['resource.tab_virtual_machines']) vm_elements = self.find_elements(locators['resource.vm_list']) return [vm.text for vm in vm_elements] def add_image(self, res_name, parameter_list): """Adds an image to a compute resource.""" self.search_and_click(res_name) self.click(locators['resource.image_add']) self.wait_until_element(locators['resource.image_name']) for parameter_name, parameter_value in parameter_list: param_locator = '_'.join(( 'resource.image', (parameter_name.lower()) )) self.assign_value(locators[param_locator], parameter_value) self.click(locators['resource.image_submit']) def list_images(self, res_name): """Lists images on Compute Resource. Note: Currently lists only images that show up on the first page. """ self.search_and_click(res_name) self.click(tab_locators['resource.tab_images']) image_elements = self.find_elements(locators['resource.image_list']) return [image.text for image in image_elements] def vm_action_toggle(self, res_name, vm_name, really): """Toggle power status of a vm on the compute resource.""" self.search_and_click(res_name) self.click(tab_locators['resource.tab_virtual_machines']) button = self.find_element( locators['resource.vm_power_button'] % vm_name ) self.click(button) if "Off" in button.text: self.handle_alert(really) def vm_delete(self, res_name, vm_name, really): """Removes a vm from the compute resource.""" self.search_and_click(res_name) self.click(tab_locators['resource.tab_virtual_machines']) for locator in [locators['resource.vm_delete_button_dropdown'], locators['resource.vm_delete_button']]: self.click(locator % vm_name) self.handle_alert(really) def search_vm(self, resource_name, vm_name): """Searches for existing Virtual machine from particular compute resource. It is necessary to use custom search here as we need to select compute resource tab before searching for particular Virtual machine and also, there is no search button to click """ self.search_and_click(resource_name) self.click(tab_locators['resource.tab_virtual_machines']) self.assign_value( locators['resource.search_filter'], vm_name) strategy, value = self._search_locator() return self.wait_until_element((strategy, value % vm_name)) def power_on_status(self, resource_name, vm_name): """Return the compute resource virtual machine power status :param resource_name: The compute resource name :param vm_name: the virtual machine name :return: on or off """ element = self.search_vm(resource_name, vm_name) if element is None: raise UIError( 'Could not find Virtual machine "{0}"'.format(vm_name)) return self.wait_until_element( locators['resource.power_status']).text.lower() def set_power_status(self, resource_name, vm_name, power_on=None): """Perform power on or power off for VM's :param bool power_on: True - for On, False - for Off """ status = None locator_status = locators['resource.power_status'] element = self.search_vm(resource_name, vm_name) if element is None: raise UIError( 'Could not find Virtual machine "{0}"'.format(vm_name)) button = self.find_element( locators['resource.vm_power_button'] ) if power_on is True: if 'On' not in button.text: raise UIError( 'Could not start VM {0}. VM is running'.format(vm_name) ) self.click(button) self.search_vm(resource_name, vm_name) status = self.wait_until_element(locator_status).text elif power_on is False: if 'Off' not in button.text: raise UIError( 'Could not stop VM {0}. VM is not running'.format(vm_name) ) self.click(button, wait_for_ajax=False) self.handle_alert(True) self.search_vm(resource_name, vm_name) status = self.wait_until_element(locator_status).text return status def select_profile(self, resource_name, profile_name): """Select the compute profile of a specific compute resource :param resource_name: Name of compute resource to select from the list :param profile_name: Name of profile that contains required compute resource (e.g. '2-Medium' or '1-Small') :return: resource type and the resource profile form element :returns: tuple """ resource_element = self.search(resource_name) resource_type = self.wait_until_element( locators['resource.resource_type'] % resource_name).text self.click(resource_element) self.click(tab_locators['resource.tab_compute_profiles']) self.click(locators["resource.compute_profile"] % profile_name) return (resource_type, self.wait_until_element(locators['profile.resource_form'])) def get_profile_values(self, resource_name, profile_name, params_name): """Fetch provided compute profile parameters values :param resource_name: Name of compute resource to select from the list :param profile_name: Name of profile that contains required compute resource (e.g. '2-Medium' or '1-Small') :param params_name: the compute resource profile configuration properties fields to get :return: Dictionary of parameters names and their corresponding values """ resource_type, _ = self.select_profile(resource_name, profile_name) resource_profile_form = get_compute_resource_profile( self, resource_type) return resource_profile_form.get_values(params_name) def set_profile_values(self, resource_name, profile_name, **kwargs): """Fill and Submit the compute resource profile form configuration properties :param resource_name: Name of compute resource to select from the list :param profile_name: Name of profile that contains required compute resource (e.g. '2-Medium' or '1-Small') :param kwargs: the compute resource profile configuration properties fields to be set """ resource_type, _ = self.select_profile(resource_name, profile_name) resource_profile_form = get_compute_resource_profile( self, resource_type) resource_profile_form.set_values(**kwargs) resource_profile_form.submit() def check_image_os(self, os_name): """Check if the OS is present, if not create the required OS :param os_name: OS name to check, and create :return: Created os """ # Check if OS that image needs is present or no, If not create the OS result = entities.OperatingSystem().search(query={ u'search': u'title="{0}"'.format(os_name) }) if result: os = result[0] else: os = entities.OperatingSystem( name=os_name.split(' ')[0], major=os_name.split(' ')[1].split('.')[0], minor=os_name.split(' ')[1].split('.')[1], ).create() return os
sghai/robottelo
robottelo/ui/computeresource.py
Python
gpl-3.0
25,187
<!-- Mad-Advertisement Copyright (C) 2011 Thorsten Marx <thmarx@gmx.net> 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, see <http://www.gnu.org/licenses/>. --> <wicket:extend xmlns:wicket="http://wicket.apache.org"> <a href="#" wicket:id="backLink"><wicket:message key="backlink.label"/></a> <br/> <h2> <wicket:message key="editsite.title" /> : <u><span wicket:id="sitename"></span></u> </h2> <br /> <br /> <div class="column"> <div class="overview left"> <h3 class="title"> <wicket:message key="overview.site" /> </h3> <form wicket:id="inputForm" class="inputForm"> <table> <tr> <td><wicket:message key="inputForm.name" /></td> <td><input wicket:id="name" id="name" type="text" size="40" /></td> </tr> <tr> <td><wicket:message key="inputForm.url" /></td> <td><input wicket:id="url" id="url" type="text" size="40" /></td> </tr> <tr> <td><wicket:message key="inputForm.description" /></td> <td><textarea wicket:id="description" id="description" cols="40" rows="10"></textarea></td> </tr> <tr> <td></td> <td><input type="submit" wicket:id="saveButton" value="save" /></td> </tr> </table> </form> <div wicket:id="feedback"></div> </div> <div class="overview right"> <h3 class="title"> <wicket:message key="overview.places" /> </h3> <button wicket:id="newPlace"> <wicket:message key="button.newplace" /> </button> <br /> <br /> <span wicket:id="navigator">[dataview navigator]</span> <table cellspacing="0" class="dataview" style="width: 80%;"> <colgroup> <col width="10%" /> <col width="30%" /> <col width="30%" /> </colgroup> <tr style="text-align: center;"> <th>ID</th> <th>Name</th> <th>Created</th> <th>Editieren</th> <th>L&ouml;schen</th> </tr> <tr wicket:id="pageable" style="text-align: center;"> <td><span wicket:id="id">[id]</span></td> <td><span wicket:id="name">[name]</span></td> <td><span wicket:id="created">[created]</span></td> <td><span wicket:id="editPlace">[editPlace]</span></td> <td><a href="#" wicket:id="deletePlace"><wicket:message key="actionpanel.delete" /></a></td> </tr> </table> <div wicket:id="placeFeedback"></div> </div> </div> </wicket:extend>
codepilotde/AdServing
ad.manager/src/main/resources/net/mad/ads/manager/web/pages/manager/site/edit/EditSitePage.html
HTML
gpl-3.0
2,925
package org.arig.robot.system.encoders; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.arig.robot.model.monitor.MonitorTimeSerie; import org.arig.robot.monitoring.IMonitoringWrapper; import org.springframework.beans.factory.annotation.Autowired; /** * The Class Abstract2WheelsEncoders. * * @author gdepuille */ @Slf4j public abstract class Abstract2WheelsEncoders { @Autowired private IMonitoringWrapper monitoringWrapper; @Getter private double distance; @Getter private double orientation; @Getter private double gauche; @Getter private double droit; @Getter private double coefGauche; @Getter private double coefDroit; private boolean alternate; private final String name; protected Abstract2WheelsEncoders(final String name) { this.name = name; distance = orientation = 0; coefDroit = coefGauche = 1.0; alternate = false; } public void lectureValeurs() { if (alternate) { gauche = lectureGauche() * coefGauche; droit = lectureDroit() * coefDroit; } else { droit = lectureDroit() * coefDroit; gauche = lectureGauche() * coefGauche; } alternate = !alternate; calculPolarValues(); sendMonitoring(); } public void setCoefs(final double coefGauche, final double coefDroit) { this.coefGauche = coefGauche; this.coefDroit = coefDroit; } public abstract void reset(); protected abstract double lectureGauche(); protected abstract double lectureDroit(); private void calculPolarValues() { distance = (droit + gauche) / 2; orientation = droit - gauche; } private void sendMonitoring() { // Construction du monitoring MonitorTimeSerie serie = new MonitorTimeSerie() .measurementName("encodeurs") .addTag(MonitorTimeSerie.TAG_NAME, name) .addField("gauche", getGauche()) .addField("droit", getDroit()) .addField("distance", getDistance()) .addField("orientation", getOrientation()); monitoringWrapper.addTimeSeriePoint(serie); } }
ARIG-Robotique/robots
robot-system-lib-parent/robot-system-lib-core/src/main/java/org/arig/robot/system/encoders/Abstract2WheelsEncoders.java
Java
gpl-3.0
2,265
<?php /* * This file is part of the Moodle Plugin CI package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Copyright (c) 2018 Blackboard Inc. (http://www.blackboard.com) * License http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace MoodlePluginCI\Tests\PluginValidate; use MoodlePluginCI\PluginValidate\Plugin; use MoodlePluginCI\PluginValidate\Requirements\BlockRequirements; use MoodlePluginCI\PluginValidate\Requirements\RequirementsResolver; class BlockRequirementsTest extends \PHPUnit_Framework_TestCase { /** * @var BlockRequirements */ private $requirements; protected function setUp() { $this->requirements = new BlockRequirements(new Plugin('block_html', 'block', 'html', ''), 29); } protected function tearDown() { $this->requirements = null; } public function testResolveRequirements() { $resolver = new RequirementsResolver(); $this->assertInstanceOf( 'MoodlePluginCI\PluginValidate\Requirements\BlockRequirements', $resolver->resolveRequirements(new Plugin('', 'block', '', ''), 29) ); } public function testGetRequiredFiles() { $files = $this->requirements->getRequiredFiles(); $this->assertNotEmpty($files); foreach ($files as $file) { $this->assertInternalType('string', $file); } } public function testGetRequiredFunctions() { $functions = $this->requirements->getRequiredFunctions(); $this->assertNotEmpty($functions); foreach ($functions as $function) { $this->assertInstanceOf('MoodlePluginCI\PluginValidate\Finder\FileTokens', $function); } } public function testGetRequiredClasses() { $classes = $this->requirements->getRequiredClasses(); $this->assertNotEmpty($classes); foreach ($classes as $class) { $this->assertInstanceOf('MoodlePluginCI\PluginValidate\Finder\FileTokens', $class); } } public function testGetRequiredStrings() { $fileToken = $this->requirements->getRequiredStrings(); $this->assertInstanceOf('MoodlePluginCI\PluginValidate\Finder\FileTokens', $fileToken); $this->assertSame('lang/en/block_html.php', $fileToken->file); } public function testGetRequiredCapabilities() { $fileToken = $this->requirements->getRequiredCapabilities(); $this->assertInstanceOf('MoodlePluginCI\PluginValidate\Finder\FileTokens', $fileToken); $this->assertSame('db/access.php', $fileToken->file); } }
moodlerooms/moodle-plugin-ci
tests/PluginValidate/Requirements/BlockRequirementsTest.php
PHP
gpl-3.0
2,707
๏ปฟusing System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FF1Lib.Sanity { public struct SCDeferredAreaQueueEntry { public short Source { get; set; } public short Target { get; set; } public SCDeferredAreaQueueEntry(short source, short target) : this() { Source = source; Target = target; } } public class SCDeferredAreaQueueEntryEqualityComparer : IEqualityComparer<SCDeferredAreaQueueEntry> { public bool Equals(SCDeferredAreaQueueEntry x, SCDeferredAreaQueueEntry y) { return x.Source == y.Source && x.Target == y.Target; } public int GetHashCode([DisallowNull] SCDeferredAreaQueueEntry obj) { return (int)obj.Source + 2048 * (int)obj.Target; } } }
Entroper/Randomizers
FF1Lib/Sanity/SCDeferredAreaQueueEntry.cs
C#
gpl-3.0
806
import scala.collection.JavaConversions._ // you can use println for debugging purposes, e.g. // println("this is a debug message") object Solution { def solution(A: Array[Int]): Int = { // write your code in Scala 2.10 val n = A.length var k: Int = 1 var j: Int = 0 for (i <- 1 to n-1) { if (A(j)==A(i)) k += 1 else { k -= 1 if (k < 0) { j = i k = 1 } } } // check if (2 * A.count(_ == A(j)) > n) j else -1 } }
sfindeisen/prgctst
codility/lesson/Dominator.scala
Scala
gpl-3.0
661