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
#! /bin/sh for i in `ls ./ | sed s'|.po||'` ; do msgmerge --update --no-fuzzy-matching --no-wrap --add-location=file --backup=none ./$i.po pamac.pot done
manjaro/pamac
po/update_po_files.sh
Shell
gpl-3.0
156
package org.ovirt.engine.core.bll.transport; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VdsProtocol; import org.ovirt.engine.core.common.businessentities.VdsStatic; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.interfaces.FutureVDSCall; import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType; import org.ovirt.engine.core.common.vdscommands.TimeBoundPollVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; import org.ovirt.engine.core.vdsbroker.ResourceManager; /** * We need to detect whether vdsm supports jsonrpc or only xmlrpc. It is confusing to users * when they have cluster 3.5+ and connect to vdsm <3.5 which supports only xmlrpc. * In order to present version information in such situation we need fallback to xmlrpc. * */ public class ProtocolDetector { private Integer connectionTimeout = null; private Integer retryAttempts = null; private VDS vds; public ProtocolDetector(VDS vds) { this.vds = vds; this.retryAttempts = Config.<Integer> getValue(ConfigValues.ProtocolFallbackRetries); this.connectionTimeout = Config.<Integer> getValue(ConfigValues.ProtocolFallbackTimeoutInMilliSeconds); } /** * Attempts to connect to vdsm using a proxy from {@code VdsManager} for a host. * There are 3 attempts to connect. * * @return <code>true</code> if connected or <code>false</code> if connection failed. */ public boolean attemptConnection() { boolean connected = false; try { for (int i = 0; i < this.retryAttempts; i++) { long timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout); FutureVDSCall<VDSReturnValue> task = Backend.getInstance().getResourceManager().runFutureVdsCommand(FutureVDSCommandType.TimeBoundPoll, new TimeBoundPollVDSCommandParameters(vds.getId(), timeout, TimeUnit.SECONDS)); VDSReturnValue returnValue = task.get(timeout, TimeUnit.SECONDS); connected = returnValue.getSucceeded(); if (connected) { break; } Thread.sleep(this.connectionTimeout); } } catch (TimeoutException | InterruptedException ignored) { } return connected; } /** * Stops {@code VdsManager} for a host. */ public void stopConnection() { ResourceManager.getInstance().RemoveVds(this.vds.getId()); } /** * Fall back the protocol and attempts the connection {@link ProtocolDetector#attemptConnection()}. * * @return <code>true</code> if connected or <code>false</code> if connection failed. */ public boolean attemptFallbackProtocol() { vds.setProtocol(VdsProtocol.XML); ResourceManager.getInstance().AddVds(vds, false); return attemptConnection(); } /** * Updates DB with fall back protocol (xmlrpc). */ public void setFallbackProtocol() { final VdsStatic vdsStatic = this.vds.getStaticData(); vdsStatic.setProtocol(VdsProtocol.XML); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance().getVdsStaticDao().update(vdsStatic); return null; } }); } }
jtux270/translate
ovirt/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/transport/ProtocolDetector.java
Java
gpl-3.0
3,963
import {createBrowserHistory} from 'history'; import stringUtil from '@shared/util/stringUtil'; import ConfigStore from '../stores/ConfigStore'; const history = createBrowserHistory({basename: stringUtil.withoutTrailingSlash(ConfigStore.getBaseURI())}); export default history;
stephdewit/flood
client/src/javascript/util/history.js
JavaScript
gpl-3.0
281
/* Creative Machines Lab Aracna Firmware aracna.c - Main Program File Copyright (c) Creative Machines Lab, Cornell University, 2012 - http://www.creativemachines.org Authored by Jeremy Blum - http://www.jeremyblum.com LICENSE: GPLv3 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/>. */ /** FIRMWARE REVISION */ #define FIRMWARE_VERSION 0x01 /** HARDWARE CONFIGURATION */ #define NUM_MOTORS 8 #ifndef F_CPU #define F_CPU 16000000UL #endif /** INCLUDE AVR HEADERS */ #include <avr/io.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <util/delay.h> /** INCLUDE PROGRAM HEADERS */ #include "aracna.h" #include "macros.h" #include "ax12.h" #include "uart.h" // UART Configuration and Buffers // putchar and getchar are in uart.c //FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW); #define SERIAL_STRING_LENGTH 60 //Input String Length char input[SERIAL_STRING_LENGTH]; //complete input string uint16_t vals[NUM_MOTORS] = {0}; //For holding the values that come over serial for each of our servos char cmd; //the command character // making these volatile keeps the compiler from optimizing loops of available() volatile int ax_rx_Pointer; volatile int ax_tx_Pointer; volatile int ax_rx_int_Pointer; /** Main program entry point. This routine contains the overall program flow */ int main(void) { initialize(); //Configures Ports, sets default values, etc. //Loop Forever for (;;) { //we add data starting with an '.' to the buffer until we get the newline character. fgets(input, sizeof(input), stdin); //Get the actual input (reads up to and including newline character) cmd = input[1]; //command char is always the first char of the input data after the '.' //Command = 'q' - Query for the current status if (cmd == 'q') { memset(input, 0, sizeof(input)); //Clear previous input fprintf(stdout, ".q%d,%d\n", FIRMWARE_VERSION, NUM_MOTORS); //ACK w/ Firmware Version, # of Motors } //Command = 'l' - Command to Control Debug LED else if (cmd == 'l') { if (input[2] == '1') DEBUG_LED_ON(); //Turn LED On else if (input[2] == '0') DEBUG_LED_OFF(); //Turn LED Off memset(input, 0, sizeof(input)); //Clear previous input fprintf(stdout, ".l%d\n", DEBUG_LED_STATE()); //ACK } //Command = 'v' - Sets all motor speeds //Comma separated entries telling all motors to set certain speeds //Assumes motor IDs are 0 <-> NUM_MOTORS-1 else if (cmd == 'v') { parse_serial(); //Read the input string to an array of values memset(input, 0, sizeof(input)); //Clear previous input //send those speed commands for (int i = 0; i<NUM_MOTORS; i++) { ax12SetRegister2(i, AX_GOAL_SPEED_L, vals[i]); } _delay_ms(25); //Only after we have commanded all the speeds, can we check the status fprintf(stdout, ".v"); //ACK Character //Send ACK Info for (int i = 0; i<NUM_MOTORS; i++) { fprintf(stdout, "%d", ax12GetRegister(i, AX_GOAL_SPEED_L, 2)); //Return velocity setting if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter } fprintf(stdout, "\n"); //ACK Newline } //Command = 'c' - Command all the motors to a new position //Comma separated entries telling all motors to move to positions from 0-1023 //Assumes motor IDs are 0 <-> NUM_MOTORS-1 else if (cmd == 'c') { parse_serial(); //Read the input string to an array of positions memset(input, 0, sizeof(input)); //Clear previous input //send those position commands for (int i = 0; i<NUM_MOTORS; i++) { ax12SetRegister2(i, AX_GOAL_POSITION_L, vals[i]); } //Only after we have commanded all the positions, can we check the status fprintf(stdout, ".c"); //ACK Character //Send ACK Info for (int i = 0; i<NUM_MOTORS; i++) { while(ax12GetRegister(i,AX_MOVING,1)); //Wait for this motor to finish moving fprintf(stdout, "%d", ax12GetRegister(i, AX_PRESENT_POSITION_L, 2)); //Return the present position if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter } fprintf(stdout, "\n"); //ACK Newline } } } /** initialize() Sets up the UARTS, configures pin directions, says hello, then blinks at you. */ void initialize(void) { //init the UART0 to the Computer uart_init(); stdout = &uart_output; stdin = &uart_input; //Initialize the AX12 UART1 ax12Init(1000000); //Initialize Pin Directions and States for I/O DDRB |= (DEBUG_LED_NUM); DEBUG_LED_OFF(); //We're live. Say Hello fprintf(stdout,".h\n"); //Blink The Board LED and all Dynamixel LEDs to show We're good to go for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0); DEBUG_LED_OFF(); _delay_ms(500); for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 1); DEBUG_LED_ON(); _delay_ms(500); for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0); DEBUG_LED_OFF(); } /** parse_serial() Assumes the input buffer has been populated with data of this form: ".c<val0>,<val1>,<val2>,...<val7>\n" as a char array This function reads this buffer, and populates the "vals" array with the integer representations of 10-bit values for each motor command */ void parse_serial(void) { for (uint8_t i = 0; i < NUM_MOTORS; i++) vals[i] = 0; //Skip leading '.' and command char uint8_t i = 2; uint8_t motor_num = 0; uint8_t mtr_tmp[4] = {10, 10, 10, 10}; uint8_t mtr_tmp_pos = 0; while (motor_num < NUM_MOTORS) { //look for the commas if (input[i] == ',' || input[i] == '\n') { if (mtr_tmp[3] < 10) vals[motor_num] = mtr_tmp[0]*1000 + mtr_tmp[1]*100 + mtr_tmp[2]*10 + mtr_tmp[3]; else if (mtr_tmp[2] < 10) vals[motor_num] = mtr_tmp[0]*100 + mtr_tmp[1]*10 + mtr_tmp[2]; else if (mtr_tmp[1] < 10) vals[motor_num] = mtr_tmp[0]*10 + mtr_tmp[1]; else vals[motor_num] = mtr_tmp[0]; motor_num++; for (uint8_t j = 0; j<4; j++) mtr_tmp[j] = 10; mtr_tmp_pos = 0; } else { mtr_tmp[mtr_tmp_pos] = input[i] - '0'; mtr_tmp_pos++; } i++; } }
booi/aracna
aracna-embedded-code/aracna/aracna.c
C
gpl-3.0
6,751
# GamesInputSketcher
Xantomen/GamesInputSketcher
README.md
Markdown
gpl-3.0
20
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Dashboard</div> <div class="panel-body"> Hello {{Auth::guard('user')->user()->name}} You are logged in! {{ Auth()->guard('user')->user()->email }} </div> </div> </div> </div> </div> @endsection
aneeshsudhakaran/laravel5.3demo
resources/views/frontend/dashboard.blade.php
PHP
gpl-3.0
602
/* * This file is part of eduVPN. * * eduVPN 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. * * eduVPN 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 eduVPN. If not, see <http://www.gnu.org/licenses/>. */ package nl.eduvpn.app.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import nl.eduvpn.app.R; import nl.eduvpn.app.adapter.viewholder.MessageViewHolder; import nl.eduvpn.app.entity.message.Maintenance; import nl.eduvpn.app.entity.message.Message; import nl.eduvpn.app.entity.message.Notification; import nl.eduvpn.app.utils.FormattingUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Adapter for serving the message views inside a list. * Created by Daniel Zolnai on 2016-10-19. */ public class MessagesAdapter extends RecyclerView.Adapter<MessageViewHolder> { private List<Message> _userMessages; private List<Message> _systemMessages; private List<Message> _mergedList = new ArrayList<>(); private LayoutInflater _layoutInflater; public void setUserMessages(List<Message> userMessages) { _userMessages = userMessages; _regenerateList(); } public void setSystemMessages(List<Message> systemMessages) { _systemMessages = systemMessages; _regenerateList(); } private void _regenerateList() { _mergedList.clear(); if (_userMessages != null) { _mergedList.addAll(_userMessages); } if (_systemMessages != null) { _mergedList.addAll(_systemMessages); } Collections.sort(_mergedList); notifyDataSetChanged(); } @Override public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (_layoutInflater == null) { _layoutInflater = LayoutInflater.from(parent.getContext()); } return new MessageViewHolder(_layoutInflater.inflate(R.layout.list_item_message, parent, false)); } @Override public void onBindViewHolder(MessageViewHolder holder, int position) { Message message = _mergedList.get(position); if (message instanceof Maintenance) { holder.messageIcon.setVisibility(View.VISIBLE); Context context = holder.messageText.getContext(); String maintenanceText = FormattingUtils.getMaintenanceText(context, (Maintenance)message); holder.messageText.setText(maintenanceText); } else if (message instanceof Notification) { holder.messageIcon.setVisibility(View.GONE); holder.messageText.setText(((Notification)message).getContent()); } else { throw new RuntimeException("Unexpected message type!"); } } @Override public int getItemCount() { return _mergedList.size(); } }
dzolnai/android
app/src/main/java/nl/eduvpn/app/adapter/MessagesAdapter.java
Java
gpl-3.0
3,444
/* This file is part of Jellyfish. Jellyfish 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. Jellyfish 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 Jellyfish. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __JELLYFISH_PARSE_DNA_HPP__ #define __JELLYFISH_PARSE_DNA_HPP__ #include <iostream> #include <vector> #include <jellyfish/double_fifo_input.hpp> #include <jellyfish/atomic_gcc.hpp> #include <jellyfish/misc.hpp> #include <jellyfish/sequence_parser.hpp> #include <jellyfish/allocators_mmap.hpp> #include <jellyfish/dna_codes.hpp> #include <jellyfish/seedmod/seedmod.hpp> namespace jellyfish { class parse_dna : public double_fifo_input<sequence_parser::sequence_t> { typedef std::vector<const char *> fary_t; uint_t mer_len; size_t buffer_size; const fary_t files; fary_t::const_iterator current_file; bool have_seam; char *seam; allocators::mmap buffer_data; bool canonical; sequence_parser *fparser; const char *Spaced_seed_cstr; public: /* Action to take for a given letter in fasta file: * A, C, G, T: map to 0, 1, 2, 3. Append to kmer * Other nucleic acid code: map to -1. reset kmer * '\n': map to -2. ignore * Other ASCII: map to -3. Report error. */ static uint64_t mer_string_to_binary(const char *in, uint_t klen) { uint64_t res = 0; for(uint_t i = 0; i < klen; i++) { const uint_t c = dna_codes[(uint_t)*in++]; if(c & CODE_NOT_DNA) return 0; res = (res << 2) | c; } return res; } static void mer_binary_to_string(uint64_t mer, uint_t klen, char *out) { static const char table[4] = { 'A', 'C', 'G', 'T' }; for(unsigned int i = 0 ; i < klen; i++) { out[klen-1-i] = table[mer & (uint64_t)0x3]; mer >>= 2; } out[klen] = '\0'; } static uint64_t reverse_complement(uint64_t v, uint_t length) { v = ((v >> 2) & 0x3333333333333333UL) | ((v & 0x3333333333333333UL) << 2); v = ((v >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((v & 0x0F0F0F0F0F0F0F0FUL) << 4); v = ((v >> 8) & 0x00FF00FF00FF00FFUL) | ((v & 0x00FF00FF00FF00FFUL) << 8); v = ((v >> 16) & 0x0000FFFF0000FFFFUL) | ((v & 0x0000FFFF0000FFFFUL) << 16); v = ( v >> 32 ) | ( v << 32); return (((uint64_t)-1) - v) >> (bsizeof(v) - (length << 1)); } template<typename T> parse_dna(T _files_start, T _files_end, uint_t _mer_len, unsigned int nb_buffers, size_t _buffer_size, const char * seed_cstr); ~parse_dna() { delete [] seam; } void set_canonical(bool v = true) { canonical = v; } virtual void fill(); class thread { parse_dna *parser; bucket_t *sequence; const uint_t mer_len, lshift; __uint128_t kmer, rkmer; const __uint128_t masq; uint64_t ret_mer; uint_t cmlen; const bool canonical; uint64_t distinct, total; typedef void (*error_reporter)(std::string& err); error_reporter error_report; public: explicit thread(parse_dna *_parser) : parser(_parser), sequence(0), mer_len(_parser->mer_len), lshift(2 * (mer_len - 1)), kmer(0), rkmer(0), ret_mer(0), masq((~(__uint128_t)(0))^((~(__uint128_t)(0))<<(2*mer_len))), cmlen(0), canonical(parser->canonical), distinct(0), total(0), error_report(0) {} uint64_t get_uniq() const { return 0; } uint64_t get_distinct() const { return distinct; } uint64_t get_total() const { return total; } template<typename T> void parse(T &counter) { cmlen = kmer = rkmer = ret_mer = 0; while((sequence = parser->next())) { const char *start = sequence->start; const char * const end = sequence->end; while(start < end) { const uint_t c = dna_codes[(uint_t)*start++]; switch(c) { case CODE_IGNORE: break; case CODE_COMMENT: report_bad_input(*(start-1)); // Fall through case CODE_RESET: cmlen = kmer = rkmer = 0; break; default: kmer = ((kmer << 2) & masq) | c; //rkmer = (rkmer >> 2) | ((0x3 - c) << lshift); if(++cmlen >= mer_len) { cmlen = mer_len; ret_mer = 0; kraken::squash_kmer_for_index(parser->Spaced_seed_cstr, mer_len, kmer,ret_mer); typename T::val_type oval; if(canonical){ //counter->add(kmer < rkmer ? kmer : rkmer, 1, &oval); std::cerr<<"Jellyfish with SpacedSeeds does not support canonical kmers." <<std::endl; exit(-1); }else{ counter->add(ret_mer, 1, &oval); //DEBUG //std::cerr<<kraken::kmer_to_str(mer_len,kmer)<<" <--> " // <<kraken::kmer_to_str(mer_len,ret_mer) // <<std::endl; } distinct += oval == (typename T::val_type)0; ++total; } } } // Buffer exhausted. Get a new one cmlen = kmer = rkmer = 0; parser->release(sequence); } } void set_error_reporter(error_reporter e) { error_report = e; } private: void report_bad_input(char c) { if(!error_report) return; std::string err("Bad character in sequence: "); err += c; error_report(err); } }; friend class thread; thread new_thread() { return thread(this); } }; } template<typename T> jellyfish::parse_dna::parse_dna(T _files_start, T _files_end, uint_t _mer_len, unsigned int nb_buffers, size_t _buffer_size, const char * seed_cstr) : double_fifo_input<sequence_parser::sequence_t>(nb_buffers), mer_len(_mer_len), buffer_size(allocators::mmap::round_to_page(_buffer_size)), files(_files_start, _files_end), current_file(files.begin()), have_seam(false), buffer_data(buffer_size * nb_buffers), canonical(false), Spaced_seed_cstr(seed_cstr) { seam = new char[mer_len]; memset(seam, 'A', mer_len); unsigned long i = 0; for(bucket_iterator it = bucket_begin(); it != bucket_end(); ++it, ++i) { it->end = it->start = (char *)buffer_data.get_ptr() + i * buffer_size; } assert(i == nb_buffers); fparser = sequence_parser::new_parser(*current_file); } #endif
macieksk/Jellyfish
jellyfish/parse_dna.hpp
C++
gpl-3.0
7,390
#!/bin/sh # Test some of cp's options and how cp handles situations in # which a naive implementation might overwrite the source file. # Copyright (C) 1998-2017 Free Software Foundation, Inc. # 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/>. . "${srcdir=.}/tests/init.sh"; path_prepend_ ./src print_ver_ cp # Unset CDPATH. Otherwise, output from the 'cd dir' command # can make this test fail. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH VERSION_CONTROL=numbered; export VERSION_CONTROL # Determine whether a hard link to a symlink points to the symlink # itself or to its referent. For example, the link from FreeBSD6.1 # does dereference a symlink, but the one from Linux does not. ln -s no-such dangling-slink ln dangling-slink hard-link > /dev/null 2>&1 \ && hard_link_to_symlink_does_the_deref=no \ || hard_link_to_symlink_does_the_deref=yes rm -f no-such dangling-slink hard-link test $hard_link_to_symlink_does_the_deref = yes \ && remove_these_sed='/^0 -[bf]*l .*sl1 ->/d; /hlsl/d' \ || remove_these_sed='/^ELIDE NO TEST OUTPUT/d' exec 3>&1 1> actual # FIXME: This should be bigger: like more than 8k contents=XYZ for args in 'foo symlink' 'symlink foo' 'foo foo' 'sl1 sl2' \ 'foo hardlink' 'hlsl sl2'; do for options in '' -d -f -df --rem -b -bd -bf -bdf \ -l -dl -fl -dfl -bl -bdl -bfl -bdfl; do case $args$options in # These tests are not portable. # They all involve making a hard link to a symbolic link. # In the past, we've skipped the tests that are not portable, # by doing "continue" here and eliminating the corresponding # expected output lines below. Don't do that anymore. 'symlink foo'-dfl) continue;; 'symlink foo'-bdl) continue;; 'symlink foo'-bdfl) continue;; 'sl1 sl2'-dfl) continue;; 'sl1 sl2'-bd*l) continue;; 'sl1 sl2'-dl) continue;; esac # cont'd Instead, skip them only on systems for which link does # dereference a symlink. Detect and skip such tests here. case $hard_link_to_symlink_does_the_deref:$args:$options in 'yes:sl1 sl2:-fl') continue ;; 'yes:sl1 sl2:-bl') continue ;; 'yes:sl1 sl2:-bfl') continue ;; yes:hlsl*) continue ;; esac rm -rf dir mkdir dir cd dir echo $contents > foo case "$args" in *symlink*) ln -s foo symlink ;; esac case "$args" in *hardlink*) ln foo hardlink ;; esac case "$args" in *sl1*) ln -s foo sl1;; esac case "$args" in *sl2*) ln -s foo sl2;; esac case "$args" in *hlsl*) ln sl2 hlsl;; esac ( ( # echo 1>&2 cp $options $args cp $options $args 2>_err echo $? $options # Normalize the program name and diagnostics in the error output, # and put brackets around the output. if test -s _err; then sed ' s/^[^:]*:\([^:]*\).*/cp:\1/ 1s/^/[/ $s/$/]/ ' _err fi # Strip off all but the file names. ls=$(ls -gG --ignore=_err . \ | sed \ -e '/^total /d' \ -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//') echo "($ls)" # Make sure the original is unchanged and that # the destination is a copy. for f in $args; do if test -f $f; then case "$(cat $f)" in "$contents") ;; *) echo cp FAILED;; esac else echo symlink-loop fi done ) | tr '\n' ' ' echo ) | sed 's/ *$//' cd .. done echo done cat <<\EOF | sed "$remove_these_sed" > expected 1 [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo) 1 -d [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo) 1 -f [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo) 1 -df [cp: 'foo' and 'symlink' are the same file] (foo symlink -> foo) 0 --rem (foo symlink) 0 -b (foo symlink symlink.~1~ -> foo) 0 -bd (foo symlink symlink.~1~ -> foo) 0 -bf (foo symlink symlink.~1~ -> foo) 0 -bdf (foo symlink symlink.~1~ -> foo) 1 -l [cp: cannot create hard link 'symlink' to 'foo'] (foo symlink -> foo) 1 -dl [cp: cannot create hard link 'symlink' to 'foo'] (foo symlink -> foo) 0 -fl (foo symlink) 0 -dfl (foo symlink) 0 -bl (foo symlink symlink.~1~ -> foo) 0 -bdl (foo symlink symlink.~1~ -> foo) 0 -bfl (foo symlink symlink.~1~ -> foo) 0 -bdfl (foo symlink symlink.~1~ -> foo) 1 [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 1 -d [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 1 -f [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 1 -df [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 1 --rem [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 1 -b [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 0 -bd (foo -> foo foo.~1~ symlink -> foo) symlink-loop symlink-loop 1 -bf [cp: 'symlink' and 'foo' are the same file] (foo symlink -> foo) 0 -bdf (foo -> foo foo.~1~ symlink -> foo) symlink-loop symlink-loop 0 -l (foo symlink -> foo) 0 -dl (foo symlink -> foo) 0 -fl (foo symlink -> foo) 0 -bl (foo symlink -> foo) 0 -bfl (foo symlink -> foo) 1 [cp: 'foo' and 'foo' are the same file] (foo) 1 -d [cp: 'foo' and 'foo' are the same file] (foo) 1 -f [cp: 'foo' and 'foo' are the same file] (foo) 1 -df [cp: 'foo' and 'foo' are the same file] (foo) 1 --rem [cp: 'foo' and 'foo' are the same file] (foo) 1 -b [cp: 'foo' and 'foo' are the same file] (foo) 1 -bd [cp: 'foo' and 'foo' are the same file] (foo) 0 -bf (foo foo.~1~) 0 -bdf (foo foo.~1~) 0 -l (foo) 0 -dl (foo) 0 -fl (foo) 0 -dfl (foo) 0 -bl (foo) 0 -bdl (foo) 0 -bfl (foo foo.~1~) 0 -bdfl (foo foo.~1~) 1 [cp: 'sl1' and 'sl2' are the same file] (foo sl1 -> foo sl2 -> foo) 0 -d (foo sl1 -> foo sl2 -> foo) 1 -f [cp: 'sl1' and 'sl2' are the same file] (foo sl1 -> foo sl2 -> foo) 0 -df (foo sl1 -> foo sl2 -> foo) 0 --rem (foo sl1 -> foo sl2) 0 -b (foo sl1 -> foo sl2 sl2.~1~ -> foo) 0 -bd (foo sl1 -> foo sl2 -> foo sl2.~1~ -> foo) 0 -bf (foo sl1 -> foo sl2 sl2.~1~ -> foo) 0 -bdf (foo sl1 -> foo sl2 -> foo sl2.~1~ -> foo) 1 -l [cp: cannot create hard link 'sl2' to 'sl1'] (foo sl1 -> foo sl2 -> foo) 0 -fl (foo sl1 -> foo sl2) 0 -bl (foo sl1 -> foo sl2 sl2.~1~ -> foo) 0 -bfl (foo sl1 -> foo sl2 sl2.~1~ -> foo) 1 [cp: 'foo' and 'hardlink' are the same file] (foo hardlink) 1 -d [cp: 'foo' and 'hardlink' are the same file] (foo hardlink) 1 -f [cp: 'foo' and 'hardlink' are the same file] (foo hardlink) 1 -df [cp: 'foo' and 'hardlink' are the same file] (foo hardlink) 0 --rem (foo hardlink) 0 -b (foo hardlink hardlink.~1~) 0 -bd (foo hardlink hardlink.~1~) 0 -bf (foo hardlink hardlink.~1~) 0 -bdf (foo hardlink hardlink.~1~) 0 -l (foo hardlink) 0 -dl (foo hardlink) 0 -fl (foo hardlink) 0 -dfl (foo hardlink) 0 -bl (foo hardlink) 0 -bdl (foo hardlink) 0 -bfl (foo hardlink) 0 -bdfl (foo hardlink) 1 [cp: 'hlsl' and 'sl2' are the same file] (foo hlsl -> foo sl2 -> foo) 0 -d (foo hlsl -> foo sl2 -> foo) 1 -f [cp: 'hlsl' and 'sl2' are the same file] (foo hlsl -> foo sl2 -> foo) 0 -df (foo hlsl -> foo sl2 -> foo) 0 --rem (foo hlsl -> foo sl2) 0 -b (foo hlsl -> foo sl2 sl2.~1~ -> foo) 0 -bd (foo hlsl -> foo sl2 -> foo sl2.~1~ -> foo) 0 -bf (foo hlsl -> foo sl2 sl2.~1~ -> foo) 0 -bdf (foo hlsl -> foo sl2 -> foo sl2.~1~ -> foo) 1 -l [cp: cannot create hard link 'sl2' to 'hlsl'] (foo hlsl -> foo sl2 -> foo) 0 -dl (foo hlsl -> foo sl2 -> foo) 0 -fl (foo hlsl -> foo sl2) 0 -dfl (foo hlsl -> foo sl2 -> foo) 0 -bl (foo hlsl -> foo sl2 sl2.~1~ -> foo) 0 -bdl (foo hlsl -> foo sl2 -> foo) 0 -bfl (foo hlsl -> foo sl2 sl2.~1~ -> foo) 0 -bdfl (foo hlsl -> foo sl2 -> foo) EOF exec 1>&3 3>&- compare expected actual 1>&2 || fail=1 Exit $fail
adtools/coreutils
tests/cp/same-file.sh
Shell
gpl-3.0
8,456
drop table if exists hml;
nmdp-bioinformatics/service-hml
service-jdbi/src/main/sql/mysql-drop.sql
SQL
gpl-3.0
26
<?php use Alchemy\Phrasea\Model\Serializer\CaptionSerializer; use Symfony\Component\Yaml\Yaml; /** * @group functional * @group legacy */ class caption_recordTest extends \PhraseanetTestCase { /** * @var caption_record */ protected $object; public function setUp() { parent::setUp(); $this->object = new caption_record(self::$DI['app'], self::$DI['record_1'], self::$DI['record_1']->get_databox()); } /** * @covers \caption_record::serializeXML */ public function testSerializeXML() { foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) { $n = $databox_field->is_multi() ? 3 : 1; for ($i = 0; $i < $n; $i ++) { \caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8)); } } $xml = self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_XML); $sxe = simplexml_load_string($xml); $this->assertInstanceOf('SimpleXMLElement', $sxe); foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) { if ($field->get_databox_field()->is_multi()) { $tagname = $field->get_name(); $retrieved = []; foreach ($sxe->description->$tagname as $value) { $retrieved[] = (string) $value; } $values = $field->get_values(); $this->assertEquals(count($values), count($retrieved)); foreach ($values as $val) { $this->assertTrue(in_array($val->getValue(), $retrieved)); } } else { $tagname = $field->get_name(); $data = $field->get_values(); $value = array_pop($data); $this->assertEquals($value->getValue(), (string) $sxe->description->$tagname); } } } public function testSerializeJSON() { foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) { $n = $databox_field->is_multi() ? 3 : 1; for ($i = 0; $i < $n; $i ++) { \caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8)); } } $json = json_decode(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_JSON), true); foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) { if ($field->get_databox_field()->is_multi()) { $tagname = $field->get_name(); $retrieved = []; foreach ($json["record"]["description"][$tagname] as $value) { $retrieved[] = $value; } $values = $field->get_values(); $this->assertEquals(count($values), count($retrieved)); foreach ($values as $val) { $this->assertTrue(in_array($val->getValue(), $retrieved)); } } else { $tagname = $field->get_name(); $data = $field->get_values(); $value = array_pop($data); $this->assertEquals($value->getValue(), $json["record"]["description"][$tagname]); } } } /** * @covers \caption_record::serializeYAML */ public function testSerializeYAML() { foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) { $n = $databox_field->is_multi() ? 3 : 1; for ($i = 0; $i < $n; $i ++) { \caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], self::$DI['app']['random.low']->generateString(8)); } } $parser = new Yaml(); $yaml = $parser->parse(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_YAML)); foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) { if ($field->get_databox_field()->is_multi()) { $tagname = $field->get_name(); $retrieved = []; foreach ($yaml["record"]["description"][$tagname] as $value) { $retrieved[] = (string) $value; } $values = $field->get_values(); $this->assertEquals(count($values), count($retrieved)); foreach ($values as $val) { $this->assertTrue(in_array($val->getValue(), $retrieved)); } } else { $tagname = $field->get_name(); $data = $field->get_values(); $value = array_pop($data); $this->assertEquals($value->getValue(), (string) $yaml["record"]["description"][$tagname]); } } } /** * @covers \caption_record::get_fields * @todo Implement testGet_fields(). */ public function testGet_fields() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::get_field * @todo Implement testGet_field(). */ public function testGet_field() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::get_dc_field * @todo Implement testGet_dc_field(). */ public function testGet_dc_field() { $field = null; foreach (self::$DI['app']->getDataboxes() as $databox) { foreach ($databox->get_meta_structure() as $meta) { $meta->set_dces_element(new databox_Field_DCES_Contributor()); $field = $meta; $set = true; break; } break; } if (!$field) { $this->markTestSkipped('Unable to set a DC field'); } $captionField = self::$DI['record_1']->get_caption()->get_field($field->get_name()); if (!$captionField) { self::$DI['record_1']->set_metadatas([ [ 'meta_id' => null, 'meta_struct_id' => $field->get_id(), 'value' => ['HELLO MO !'], ] ]); $value = 'HELLO MO !'; } else { $value = $captionField->get_serialized_values(); } $this->assertEquals($value, self::$DI['record_1']->get_caption()->get_dc_field(databox_Field_DCESAbstract::Contributor)->get_serialized_values()); } /** * @covers \caption_record::get_highlight_fields * @todo Implement testGet_highlight_fields(). */ public function testGet_highlight_fields() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::get_cache_key * @todo Implement testGet_cache_key(). */ public function testGet_cache_key() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::get_data_from_cache * @todo Implement testGet_data_from_cache(). */ public function testGet_data_from_cache() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::set_data_to_cache * @todo Implement testSet_data_to_cache(). */ public function testSet_data_to_cache() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers \caption_record::delete_data_from_cache * @todo Implement testDelete_data_from_cache(). */ public function testDelete_data_from_cache() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } }
bburnichon/Phraseanet
tests/classes/caption/recordTest.php
PHP
gpl-3.0
8,719
a, a:hover{color: #5FB0E4} @font-face {font-family: Ebrima; font-weight:700; font-style:normal} body {padding-top: 10px; background: #2b2d2e; height: 679px; background-size:cover; position:relative; color: #ffffff; letter-spacing: .05em; font-family: Ebrima, 'National Light', "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif} .form-signIn { max-width: 400px; padding: 10px; margin: 0 auto; opacity: 1} .form-signIn .form-control { position: relative; height: auto; padding: 10px; font-size: 16px; background-color: #fff; border: none} .form-signIn input[type="email"], .form-signIn input[type="text"], .form-signIn input[type="password"], .form-signIn input[type="tel"]{ height: 45px; border-radius: 0; -webkit-border-radius: 0; -moz-border-radius: 0} .form-signIn .btn{ border-radius: 2px; -webkit-border-radius: 2px; -moz-border-radius: 2px} .btn-login, .btn-signUp{ background-color: #5FB0E4; border: none;color: #fff} .btn-login, .btn-signUp{background-color: #5FB0E4; color: #fff} .btn-login:hover, .btn-signUp:hover, .btn-login:active, .btn-signUp:active{color: lightgray} .c-blue{color: #5FB0E4} .space-top-8{margin-top:50px} .footer-divider{border-color:#5FB0E4} .space-top-1{margin-top: 1em} .space-top-2{margin-top: 2em} .space-bottom-2{margin-bottom: 2em}
AlbertHambardzumyan/AUA
St/web/css/register.css
CSS
gpl-3.0
1,301
from ..daltools.util.full import init Z = [8., 1., 1.] Rc = init([0.00000000, 0.00000000, 0.48860959]) Dtot = [0, 0, -0.76539388] Daa = init([ [ 0.00000000, 0.00000000, -0.28357300], [ 0.15342658, 0.00000000, 0.12734703], [-0.15342658, 0.00000000, 0.12734703], ]) QUc = init([-7.31176220, 0., 0., -5.43243232, 0., -6.36258665]) QUN = init([4.38968295, 0., 0., 0., 0., 1.75400326]) QUaa = init([ [-3.29253618, 0.00000000, 0.00000000, -4.54316657, 0.00000000, -4.00465380], [-0.13213704, 0.00000000, 0.24980518, -0.44463288, 0.00000000, -0.26059139], [-0.13213704, 0.00000000,-0.24980518, -0.44463288, 0.00000000, -0.26059139] ]) Fab = init([ [-0.11E-03, 0.55E-04, 0.55E-04], [ 0.55E-04, -0.55E-04, 0.16E-30], [ 0.55E-04, 0.16E-30, -0.55E-04] ]) Lab = init([ [0.11E-03, 0.28E-03, 0.28E-03], [0.28E-03, 0.17E-03, 0.22E-03], [0.28E-03, 0.22E-03, 0.17E-03] ]) la = init([ [0.0392366,-27.2474016 , 27.2081650], [0.0358964, 27.2214515 ,-27.2573479], [0.01211180, -0.04775576, 0.03564396], [0.01210615, -0.00594030, -0.00616584], [10.69975088, -5.34987556, -5.34987532], [-10.6565582, 5.3282791 , 5.3282791] ]) O = [ 0.76145382, -0.00001648, 1.75278523, -0.00007538, 0.00035773, 1.39756345 ] H1O = [ 3.11619527, 0.00019911, 1.25132346, 2.11363325, 0.00111442, 2.12790474 ] H1 = [ 0.57935224, 0.00018083, 0.43312326, 0.11495546, 0.00004222, 0.45770123 ] H2O = [ 3.11568759, 0.00019821, 1.25132443, -2.11327482, -0.00142746, 2.12790473 ] H2H1 = [ 0.04078206, -0.00008380, -0.01712262, -0.00000098, 0.00000084, -0.00200285 ] H2 = [ 0.57930522, 0.00018221, 0.43312149, -0.11493635, -0.00016407, 0.45770123 ] Aab = init([O, H1O, H1, H2O, H2H1, H2]) Aa = init([ [ 3.87739525, 0.00018217, 3.00410918, 0.00010384, 0.00020122, 3.52546819 ], [ 2.15784091, 0.00023848, 1.05022368, 1.17177159, 0.00059985, 1.52065218 ], [ 2.15754005, 0.00023941, 1.05022240, -1.17157425, -0.00087738, 1.52065217 ] ]) ff = 0.001 rMP = init([ #O [ [-8.70343886, 0.00000000, 0.00000000, -0.39827574, -3.68114747, 0.00000000, 0.00000000, -4.58632761, 0.00000000, -4.24741556], [-8.70343235, 0.00076124, 0.00000000, -0.39827535, -3.68114147, 0.00000000, 0.00193493, -4.58631888, 0.00000000, -4.24741290], [-8.70343291,-0.00076166, 0.00000000, -0.39827505, -3.68114128, 0.00000000, -0.00193603, -4.58631789, 0.00000000, -4.24741229], [-8.70343685,-0.00000006, 0.00175241, -0.39827457, -3.68114516, 0.00000000, 0.00000161, -4.58632717, 0.00053363, -4.24741642], [-8.70343685, 0.00000000, -0.00175316, -0.39827456, -3.68114514, 0.00000000, 0.00000000, -4.58632711, -0.00053592, -4.24741639], [-8.70166502, 0.00000000, 0.00000144, -0.39688042, -3.67884999, 0.00000000, 0.00000000, -4.58395384, 0.00000080, -4.24349307], [-8.70520554, 0.00000000, 0.00000000, -0.39967554, -3.68344246, 0.00000000, 0.00000000, -4.58868836, 0.00000000, -4.25134640], ], #H1O [ [ 0.00000000, 0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, 0.43066796, 0.04316104, 0.00000000, 0.36285790], [ 0.00150789, 0.10111974, 0.00000000, 0.11541803, 0.53753360, 0.00000000, 0.43120945, 0.04333774, 0.00000000, 0.36314215], [-0.00150230, 0.09934695, 0.00000000, 0.11398581, 0.53667861, 0.00000000, 0.43012612, 0.04298361, 0.00000000, 0.36257249], [ 0.00000331, 0.10023328, 0.00125017, 0.11470067, 0.53710812, -0.00006107, 0.43066944, 0.04316020, 0.00015952, 0.36285848], [ 0.00000100, 0.10023249, -0.00125247, 0.11470042, 0.53710716, 0.00006135, 0.43066837, 0.04316018, -0.00015966, 0.36285788], [ 0.00088692, 0.10059268, -0.00000064, 0.11590322, 0.53754715, -0.00000006, 0.43071206, 0.04334198, -0.00000015, 0.36330053], [-0.00088334, 0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, 0.43062352, 0.04297910, 0.00000000, 0.36241326], ], #H1 [ [-0.64828057, 0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, -0.03144252, -0.46920879, 0.00000000, -0.50818752], [-0.64978846, 0.10389186, 0.00000000, 0.07204462, -0.47729337, 0.00000000, -0.03154159, -0.47074619, 0.00000000, -0.50963693], [-0.64677827, 0.10273316, 0.00000000, 0.07173584, -0.47408263, 0.00000000, -0.03134407, -0.46768337, 0.00000000, -0.50674873], [-0.64828388, 0.10331167, 0.00043314, 0.07189029, -0.47568875, -0.00023642, -0.03144270, -0.46921635, -0.00021728, -0.50819386], [-0.64828157, 0.10331095, -0.00043311, 0.07188988, -0.47568608, 0.00023641, -0.03144256, -0.46921346, 0.00021729, -0.50819095], [-0.64916749, 0.10338629, -0.00000024, 0.07234862, -0.47634698, 0.00000013, -0.03159569, -0.47003679, 0.00000011, -0.50936853], [-0.64739723, 0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, -0.03129003, -0.46838912, 0.00000000, -0.50701656], ], #H2O [ [ 0.00000000,-0.10023328, 0.00000000, 0.11470275, 0.53710687, 0.00000000, -0.43066796, 0.04316104, 0.00000000, 0.36285790], [-0.00150139,-0.09934749, 0.00000000, 0.11398482, 0.53667874, 0.00000000, -0.43012670, 0.04298387, 0.00000000, 0.36257240], [ 0.00150826,-0.10112008, 0.00000000, 0.11541676, 0.53753350, 0.00000000, -0.43120982, 0.04333795, 0.00000000, 0.36314186], [-0.00000130,-0.10023170, 0.00125018, 0.11470018, 0.53710620, 0.00006107, -0.43066732, 0.04316017, 0.00015952, 0.36285728], [ 0.00000101,-0.10023249, -0.00125247, 0.11470042, 0.53710716, -0.00006135, -0.43066838, 0.04316018, -0.00015966, 0.36285788], [ 0.00088692,-0.10059268, -0.00000064, 0.11590322, 0.53754715, 0.00000006, -0.43071206, 0.04334198, -0.00000015, 0.36330053], [-0.00088334,-0.09987383, 0.00000000, 0.11350091, 0.53666602, 0.00000000, -0.43062352, 0.04297910, 0.00000000, 0.36241326], ], #H2H1 [ [ 0.00000000, 0.00000000, 0.00000000, -0.00378789, 0.00148694, 0.00000000, 0.00000000, 0.00599079, 0.00000000, 0.01223822], [ 0.00000000, 0.00004089, 0.00000000, -0.00378786, 0.00148338, 0.00000000, -0.00004858, 0.00599281, 0.00000000, 0.01224094], [ 0.00000000,-0.00004067, 0.00000000, -0.00378785, 0.00148341, 0.00000000, 0.00004861, 0.00599277, 0.00000000, 0.01224093], [ 0.00000000,-0.00000033, -0.00001707, -0.00378763, 0.00149017, 0.00000000, 0.00000001, 0.00599114, -0.00001229, 0.01223979], [ 0.00000000, 0.00000000, 0.00001717, -0.00378763, 0.00149019, 0.00000000, 0.00000000, 0.00599114, 0.00001242, 0.01223980], [ 0.00000000, 0.00000000, 0.00000000, -0.00378978, 0.00141897, 0.00000000, 0.00000000, 0.00590445, 0.00000002, 0.01210376], [ 0.00000000, 0.00000000, 0.00000000, -0.00378577, 0.00155694, 0.00000000, 0.00000000, 0.00607799, 0.00000000, 0.01237393], ], #H2 [ [-0.64828057,-0.10330994, 0.00000000, 0.07188960, -0.47568174, 0.00000000, 0.03144252, -0.46920879, 0.00000000, -0.50818752], [-0.64677918,-0.10273369, 0.00000000, 0.07173576, -0.47408411, 0.00000000, 0.03134408, -0.46768486, 0.00000000, -0.50674986], [-0.64978883,-0.10389230, 0.00000000, 0.07204446, -0.47729439, 0.00000000, 0.03154159, -0.47074717, 0.00000000, -0.50963754], [-0.64827927,-0.10331022, 0.00043313, 0.07188947, -0.47568340, 0.00023642, 0.03144242, -0.46921057, -0.00021727, -0.50818804], [-0.64828158,-0.10331095, -0.00043311, 0.07188988, -0.47568609, -0.00023641, 0.03144256, -0.46921348, 0.00021729, -0.50819097], [-0.64916749,-0.10338629, -0.00000024, 0.07234862, -0.47634698, -0.00000013, 0.03159569, -0.47003679, 0.00000011, -0.50936853], [-0.64739723,-0.10323524, 0.00000000, 0.07143322, -0.47502412, 0.00000000, 0.03129003, -0.46838912, 0.00000000, -0.50701656] ] ]) Am = init([ [8.186766009140, 0., 0.], [0., 5.102747935447, 0.], [0., 0., 6.565131856389] ]) Amw = init([ [11.98694996213, 0., 0.], [0., 4.403583657738, 0.], [0., 0., 2.835142058626] ]) R = [ [ 0.00000, 0.00000, 0.69801], [-1.48150, 0.00000, -0.34901], [ 1.48150, 0.00000, -0.34901] ] Qtot = -10.0 Q = rMP[0, 0, (0, 2, 5)] D = rMP[1:4, 0, :] QU = rMP[4:, 0, :] dQa = rMP[0, :, (0,2,5)] dQab = rMP[0, :, (1, 3, 4)] #These are string data for testing potential file PAn0 = """AU 3 -1 0 1 1 0.000 0.000 0.698 1 -1.481 0.000 -0.349 1 1.481 0.000 -0.349 """ PA00 = """AU 3 0 0 1 1 0.000 0.000 0.698 -0.703 1 -1.481 0.000 -0.349 0.352 1 1.481 0.000 -0.349 0.352 """ PA10 = """AU 3 1 0 1 1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 """ PA20 = """AU 3 2 0 1 1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 """ PA21 = """AU 3 2 1 1 1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.466 1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 1.576 1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 1.576 """ PA22 = """AU 3 2 2 1 1 0.000 0.000 0.698 -0.703 -0.000 0.000 -0.284 -3.293 0.000 -0.000 -4.543 -0.000 -4.005 3.875 -0.000 -0.000 3.000 -0.000 3.524 1 -1.481 0.000 -0.349 0.352 0.153 0.000 0.127 -0.132 0.000 0.250 -0.445 0.000 -0.261 2.156 -0.000 1.106 1.051 -0.000 1.520 1 1.481 0.000 -0.349 0.352 -0.153 0.000 0.127 -0.132 -0.000 -0.250 -0.445 0.000 -0.261 2.156 -0.000 -1.106 1.051 -0.000 1.520 """ OUTPUT_n0_1 = """\ --------------- Atomic domain 1 --------------- Domain center: 0.00000 0.00000 0.69801 """ OUTPUT_00_1 = OUTPUT_n0_1 + """\ Nuclear charge: 8.00000 Electronic charge: -8.70344 Total charge: -0.70344 """ OUTPUT_10_1 = OUTPUT_00_1 + """\ Electronic dipole -0.00000 0.00000 -0.28357 """ OUTPUT_20_1 = OUTPUT_10_1 + """\ Electronic quadrupole -3.29254 0.00000 -0.00000 -4.54317 0.00000 -4.00466 """ OUTPUT_01_1 = OUTPUT_00_1 + """\ Isotropic polarizablity (w=0) 3.46639 """ OUTPUT_02_1 = OUTPUT_00_1 + """\ Electronic polarizability (w=0) 3.87468 -0.00000 3.00027 -0.00000 -0.00000 3.52422 """
fishstamp82/loprop
test/h2o_data.py
Python
gpl-3.0
11,431
import inctest error = 0 try: a = inctest.A() except: print "didn't find A" print "therefore, I didn't include 'testdir/subdir1/hello.i'" error = 1 pass try: b = inctest.B() except: print "didn't find B" print "therefore, I didn't include 'testdir/subdir2/hello.i'" error = 1 pass if error == 1: raise RuntimeError # Check the import in subdirectory worked if inctest.importtest1(5) != 15: print "import test 1 failed" raise RuntimeError if inctest.importtest2("black") != "white": print "import test 2 failed" raise RuntimeError
jrversteegh/softsailor
deps/swig-2.0.4/Examples/test-suite/python/inctest_runme.py
Python
gpl-3.0
563
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include "PlayListItemAudioPanel.h" #include "PlayListItemAudio.h" #include "PlayListDialog.h" #include "PlayListSimpleDialog.h" //(*InternalHeaders(PlayListItemAudioPanel) #include <wx/intl.h> #include <wx/string.h> //*) //(*IdInit(PlayListItemAudioPanel) const long PlayListItemAudioPanel::ID_STATICTEXT2 = wxNewId(); const long PlayListItemAudioPanel::ID_FILEPICKERCTRL2 = wxNewId(); const long PlayListItemAudioPanel::ID_CHECKBOX2 = wxNewId(); const long PlayListItemAudioPanel::ID_SLIDER1 = wxNewId(); const long PlayListItemAudioPanel::ID_CHECKBOX1 = wxNewId(); const long PlayListItemAudioPanel::ID_STATICTEXT4 = wxNewId(); const long PlayListItemAudioPanel::ID_SPINCTRL1 = wxNewId(); const long PlayListItemAudioPanel::ID_STATICTEXT3 = wxNewId(); const long PlayListItemAudioPanel::ID_TEXTCTRL1 = wxNewId(); //*) BEGIN_EVENT_TABLE(PlayListItemAudioPanel,wxPanel) //(*EventTable(PlayListItemAudioPanel) //*) END_EVENT_TABLE() class AudioFilePickerCtrl : public wxFilePickerCtrl { public: AudioFilePickerCtrl(wxWindow *parent, wxWindowID id, const wxString& path = wxEmptyString, const wxString& message = wxFileSelectorPromptStr, const wxString& wildcard = wxFileSelectorDefaultWildcardStr, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxFLP_DEFAULT_STYLE, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxFilePickerCtrlNameStr) : wxFilePickerCtrl(parent, id, path, message, AUDIOFILES, pos, size, style, validator, name) {} virtual ~AudioFilePickerCtrl() {} }; PlayListItemAudioPanel::PlayListItemAudioPanel(wxWindow* parent, PlayListItemAudio* audio, wxWindowID id,const wxPoint& pos,const wxSize& size) { _audio = audio; //(*Initialize(PlayListItemAudioPanel) wxFlexGridSizer* FlexGridSizer1; Create(parent, id, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("id")); FlexGridSizer1 = new wxFlexGridSizer(0, 2, 0, 0); FlexGridSizer1->AddGrowableCol(1); StaticText2 = new wxStaticText(this, ID_STATICTEXT2, _("Audio File:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2")); FlexGridSizer1->Add(StaticText2, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); FilePickerCtrl_AudioFile = new AudioFilePickerCtrl(this, ID_FILEPICKERCTRL2, wxEmptyString, _("Audio File"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFLP_FILE_MUST_EXIST|wxFLP_OPEN|wxFLP_USE_TEXTCTRL, wxDefaultValidator, _T("ID_FILEPICKERCTRL2")); FlexGridSizer1->Add(FilePickerCtrl_AudioFile, 1, wxALL|wxEXPAND, 5); FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); CheckBox_OverrideVolume = new wxCheckBox(this, ID_CHECKBOX2, _("Override Volume"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX2")); CheckBox_OverrideVolume->SetValue(false); FlexGridSizer1->Add(CheckBox_OverrideVolume, 1, wxALL|wxEXPAND, 5); FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); Slider1 = new wxSlider(this, ID_SLIDER1, 100, 0, 100, wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_SLIDER1")); FlexGridSizer1->Add(Slider1, 1, wxALL|wxEXPAND, 5); FlexGridSizer1->Add(-1,-1,1, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 5); CheckBox_FastStartAudio = new wxCheckBox(this, ID_CHECKBOX1, _("Fast Start Audio"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1")); CheckBox_FastStartAudio->SetValue(false); FlexGridSizer1->Add(CheckBox_FastStartAudio, 1, wxALL|wxEXPAND, 5); StaticText4 = new wxStaticText(this, ID_STATICTEXT4, _("Priority:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT4")); FlexGridSizer1->Add(StaticText4, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); SpinCtrl_Priority = new wxSpinCtrl(this, ID_SPINCTRL1, _T("5"), wxDefaultPosition, wxDefaultSize, 0, 1, 10, 5, _T("ID_SPINCTRL1")); SpinCtrl_Priority->SetValue(_T("5")); FlexGridSizer1->Add(SpinCtrl_Priority, 1, wxALL|wxEXPAND, 5); StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("Delay:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3")); FlexGridSizer1->Add(StaticText3, 1, wxALL|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); TextCtrl_Delay = new wxTextCtrl(this, ID_TEXTCTRL1, _("0.000"), wxDefaultPosition, wxDefaultSize, wxTE_RIGHT, wxDefaultValidator, _T("ID_TEXTCTRL1")); FlexGridSizer1->Add(TextCtrl_Delay, 1, wxALL|wxEXPAND, 5); SetSizer(FlexGridSizer1); FlexGridSizer1->Fit(this); FlexGridSizer1->SetSizeHints(this); Connect(ID_FILEPICKERCTRL2,wxEVT_COMMAND_FILEPICKER_CHANGED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged); Connect(ID_CHECKBOX2,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick); //*) FilePickerCtrl_AudioFile->SetFileName(wxFileName(audio->GetAudioFile())); TextCtrl_Delay->SetValue(wxString::Format(wxT("%.3f"), (float)audio->GetDelay() / 1000.0)); CheckBox_FastStartAudio->SetValue(audio->GetFastStartAudio()); if (audio->GetVolume() != -1) { CheckBox_OverrideVolume->SetValue(true); Slider1->SetValue(audio->GetVolume()); } else { CheckBox_OverrideVolume->SetValue(false); } ValidateWindow(); } PlayListItemAudioPanel::~PlayListItemAudioPanel() { //(*Destroy(PlayListItemAudioPanel) //*) _audio->SetDelay(wxAtof(TextCtrl_Delay->GetValue()) * 1000); _audio->SetFastStartAudio(CheckBox_FastStartAudio->GetValue()); if (CheckBox_OverrideVolume->GetValue()) { _audio->SetVolume(Slider1->GetValue()); } else { _audio->SetVolume(-1); } _audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString()); } void PlayListItemAudioPanel::OnTextCtrl_DelayText(wxCommandEvent& event) { } void PlayListItemAudioPanel::OnFilePickerCtrl2FileChanged(wxFileDirPickerEvent& event) { _audio->SetAudioFile(FilePickerCtrl_AudioFile->GetFileName().GetFullPath().ToStdString()); wxCommandEvent e(EVT_UPDATEITEMNAME); wxPostEvent(GetParent()->GetParent()->GetParent()->GetParent(), e); } void PlayListItemAudioPanel::ValidateWindow() { if (CheckBox_OverrideVolume->GetValue()) { Slider1->Enable(); } else { Slider1->Enable(false); } } void PlayListItemAudioPanel::OnCheckBox_OverrideVolumeClick(wxCommandEvent& event) { ValidateWindow(); }
smeighan/xLights
xSchedule/PlayList/PlayListItemAudioPanel.cpp
C++
gpl-3.0
6,948
Что такое танец? Для чего люди, по видимому, серьезные и спокойные, двигающиеся обычно вполне целесообразно, вдруг срываются с места и начинают производить телодвижения, весьма утомительные и явно бесполезные? Потребность танца объясняют различным образом. Некоторые господа дошли даже до того, что придают ему значение мистическое, молитвенное. Может быть, это и так, но в таком случае о молитве эти господа имеют довольно своеобразное представление. Полагаю, что реальное наблюдение над танцем ответит на вопрос точнее, чем какая либо философская теория. *** В век сентиментализма, то есть лжи, которую многие считают красивой, наши предки танцевали менуэт: мужчина и женщина с робким видом приближались друг к другу и отдалялись друг от друга. > Жест мужчины: — О, прошу тебя! > > Жест женщины: — Нет, не хочу. > > Далее: — Я умоляю. > > Она: — Я боюсь. > > Затем: — Я умру. > > Она: — А... Ну, в таком случае... На этом менуэт прерывался, заканчиваясь разве что мимолетным, почтительным объятием. Сентиментализм (в танце) скоро приелся. Люди отбросили всю предварительную часть, которой посвящен был менуэт, и прямо перешли к его заключению, развивая его в прямой последовательности: они сразу начали бросаться в объятия друг друга. Явился вальс. Правда, и в этом была наглядная последовательность: сначала объятья вальса были, так сказать, схематическими, условными: мужчина держался от женщины на некотором отдалении. Затем приблизился. Затем прижался. Вальс «modern» особенно поучителен в этом отношении. Я оставляю без внимания польку, потому что она только грубее вальса по внешности, но суть ее та же самая. Я перехожу к танцу, называемому «кэк-уок». Он развивался у нас на глазах и все его знают. Отмечу в нем одну особенность, которая может быть для некоторых явится новой. В Америке — родина «кэк-уока» — высшим преступлением топа считает изнасилование негром белой женщины. И вот самый «шикарный» кэк-уок исполняется негром и белой женщиной. Что они проделывают на сцене — вы сами видели. Кэк-уок это менуэт XX века. Он также посвящен предварительной части, но в нем уже ясно, о чем идет речь, хотя, как и в менуэте дело не заходит дальше мимолетного объятия, которое я уже не назвал бы почтительным. *** Разъяснителем танца поистине является матчиш, про который поется: «Матчиш хороший танец и очень жгучий, привез его испанец, брюнет могучий» и т. д. Он настолько понятен, что его даже не решались сразу показать публике во всем объеме: сначала танцевала его женщина — solo, затем несколько женщин вместе, и только после того мужчина с женщиной. Как в девятнадцатом веке менуэт был сменен вальсом, так и в двадцатом кэк-уок перешел в матчиш. Рукопожатия закончились объятиями. В матчише они только более реальны, чем в вальсе. Вы видели? В Париже, говорят, матчиш уже танцуют без костюмов. *** Желающим в один урок постигнуть всю психологию танца я посоветовал бы посмотреть хоть один раз тетеревиный ток. Там они все увидят: начиная с менуэта, продолжая вальсом, кэк-уоком и кончая матчишем... и даже немного далее. _Зой_
georgthegreat/dancebooks-bibtex
transcriptions/[1907, ru] Зой - О танце.md
Markdown
gpl-3.0
5,492
// ************************************************************************** // // // BornAgain: simulate and fit scattering at grazing incidence // //! @file Fit/RootAdapter/GSLMultiMinimizer.h //! @brief Declares class GSLMultiMinimizer. //! //! @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) // // ************************************************************************** // #ifndef GSLMULTIMINIMIZER_H #define GSLMULTIMINIMIZER_H #include "MinimizerConstants.h" #include "RootMinimizerAdapter.h" namespace ROOT { namespace Math { class GSLMinimizer; } } //! Wrapper for the CERN ROOT facade of the GSL multi minimizer family (gradient descent based). //! @ingroup fitting_internal class BA_CORE_API_ GSLMultiMinimizer : public RootMinimizerAdapter { public: explicit GSLMultiMinimizer(const std::string& algorithmName = AlgorithmNames::ConjugateFR); ~GSLMultiMinimizer(); //! Sets minimizer internal print level. void setPrintLevel(int value); int printLevel() const; //! Sets maximum number of iterations. This is an internal minimizer setting which has //! no direct relation to the number of objective function calls (e.g. numberOfIteraction=5 //! might correspond to ~100 objective function calls). void setMaxIterations(int value); int maxIterations() const; std::string statusToString() const override; protected: void propagateOptions() override; const root_minimizer_t* rootMinimizer() const override; private: std::unique_ptr<ROOT::Math::GSLMinimizer> m_gsl_minimizer; }; #endif // GSLMULTIMINIMIZER_H
waltervh/BornAgain
Fit/RootAdapter/GSLMultiMinimizer.h
C
gpl-3.0
1,783
-- git ALTER TABLE gitinfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`; ALTER TABLE gitinfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`; -- hg ALTER TABLE hginfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`; ALTER TABLE hginfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`; -- svn ALTER TABLE svninfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Website`; ALTER TABLE svninfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`; -- mantisbt ALTER TABLE mantisbt ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Link`; ALTER TABLE mantisbt ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`; -- wordpress ALTER TABLE wordpressinfo ADD column `ShortUrl` varchar(5) NOT NULL default 'false' AFTER `Link`; ALTER TABLE wordpressinfo ADD column `Colors` varchar(5) NOT NULL default 'true' AFTER `ShortUrl`;
Schumix/Schumix2
Sql/Updates/3.x.x/3.9.9_sqlite.sql
SQL
gpl-3.0
995
/* * Copyright (c) 1982, 1986, 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)syslog.h 8.1 (Berkeley) 6/2/93 */ #ifndef _SYS_SYSLOG_H #define _SYS_SYSLOG_H 1 #include <features.h> #define __need___va_list #include <stdarg.h> #define _PATH_LOG "/dev/log" /* * priorities/facilities are encoded into a single 32-bit quantity, where the * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility * (0-big number). Both the priorities and the facilities map roughly * one-to-one to strings in the syslogd(8) source code. This mapping is * included in this file. * * priorities (these are ordered) */ #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal but significant condition */ #define LOG_INFO 6 /* informational */ #define LOG_DEBUG 7 /* debug-level messages */ #define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */ /* extract priority */ #define LOG_PRI(p) ((p) & LOG_PRIMASK) #define LOG_MAKEPRI(fac, pri) (((fac) << 3) | (pri)) #ifdef SYSLOG_NAMES #define INTERNAL_NOPRI 0x10 /* the "no priority" priority */ /* mark "facility" */ #define INTERNAL_MARK LOG_MAKEPRI(LOG_NFACILITIES, 0) typedef struct _code { char *c_name; int c_val; } CODE; CODE prioritynames[] = { { "alert", LOG_ALERT }, { "crit", LOG_CRIT }, { "debug", LOG_DEBUG }, { "emerg", LOG_EMERG }, { "err", LOG_ERR }, { "error", LOG_ERR }, /* DEPRECATED */ { "info", LOG_INFO }, { "none", INTERNAL_NOPRI }, /* INTERNAL */ { "notice", LOG_NOTICE }, { "panic", LOG_EMERG }, /* DEPRECATED */ { "warn", LOG_WARNING }, /* DEPRECATED */ { "warning", LOG_WARNING }, { NULL, -1 } }; #endif /* facility codes */ #define LOG_KERN (0<<3) /* kernel messages */ #define LOG_USER (1<<3) /* random user-level messages */ #define LOG_MAIL (2<<3) /* mail system */ #define LOG_DAEMON (3<<3) /* system daemons */ #define LOG_AUTH (4<<3) /* security/authorization messages */ #define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ #define LOG_LPR (6<<3) /* line printer subsystem */ #define LOG_NEWS (7<<3) /* network news subsystem */ #define LOG_UUCP (8<<3) /* UUCP subsystem */ #define LOG_CRON (9<<3) /* clock daemon */ #define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */ #define LOG_FTP (11<<3) /* ftp daemon */ /* other codes through 15 reserved for system use */ #define LOG_LOCAL0 (16<<3) /* reserved for local use */ #define LOG_LOCAL1 (17<<3) /* reserved for local use */ #define LOG_LOCAL2 (18<<3) /* reserved for local use */ #define LOG_LOCAL3 (19<<3) /* reserved for local use */ #define LOG_LOCAL4 (20<<3) /* reserved for local use */ #define LOG_LOCAL5 (21<<3) /* reserved for local use */ #define LOG_LOCAL6 (22<<3) /* reserved for local use */ #define LOG_LOCAL7 (23<<3) /* reserved for local use */ #define LOG_NFACILITIES 24 /* current number of facilities */ #define LOG_FACMASK 0x03f8 /* mask to extract facility part */ /* facility of pri */ #define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3) #ifdef SYSLOG_NAMES CODE facilitynames[] = { { "auth", LOG_AUTH }, { "authpriv", LOG_AUTHPRIV }, { "cron", LOG_CRON }, { "daemon", LOG_DAEMON }, { "ftp", LOG_FTP }, { "kern", LOG_KERN }, { "lpr", LOG_LPR }, { "mail", LOG_MAIL }, { "mark", INTERNAL_MARK }, /* INTERNAL */ { "news", LOG_NEWS }, { "security", LOG_AUTH }, /* DEPRECATED */ { "syslog", LOG_SYSLOG }, { "user", LOG_USER }, { "uucp", LOG_UUCP }, { "local0", LOG_LOCAL0 }, { "local1", LOG_LOCAL1 }, { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, { "local6", LOG_LOCAL6 }, { "local7", LOG_LOCAL7 }, { NULL, -1 } }; #endif /* * arguments to setlogmask. */ #define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */ #define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */ /* * Option flags for openlog. * * LOG_ODELAY no longer does anything. * LOG_NDELAY is the inverse of what it used to be. */ #define LOG_PID 0x01 /* log the pid with each message */ #define LOG_CONS 0x02 /* log on the console if errors in sending */ #define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */ #define LOG_NDELAY 0x08 /* don't delay open */ #define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */ #define LOG_PERROR 0x20 /* log to stderr as well */ __BEGIN_DECLS /* Close descriptor used to write to system logger. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void closelog (void); /* Open connection to system logger. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void openlog (__const char *__ident, int __option, int __facility); /* Set the log mask level. */ extern int setlogmask (int __mask) __THROW; /* Generate a log message using FMT string and option arguments. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void syslog (int __pri, __const char *__fmt, ...) __attribute__ ((__format__(__printf__, 2, 3))); #ifdef __USE_BSD /* Generate a log message using FMT and using arguments pointed to by AP. This function is not part of POSIX and therefore no official cancellation point. But due to similarity with an POSIX interface or due to the implementation it is a cancellation point and therefore not marked with __THROW. */ extern void vsyslog (int __pri, __const char *__fmt, __gnuc_va_list __ap) __attribute__ ((__format__(__printf__, 2, 0))); #endif __END_DECLS #endif /* sys/syslog.h */
javilonas/NCam
cross/Toolchain-PPC-Tuxbox/include/sys/syslog.h
C
gpl-3.0
7,458
from __future__ import absolute_import, print_function, division from mitmproxy import exceptions import pprint def _get_name(itm): return getattr(itm, "name", itm.__class__.__name__) class Addons(object): def __init__(self, master): self.chain = [] self.master = master master.options.changed.connect(self.options_update) def options_update(self, options, updated): for i in self.chain: with self.master.handlecontext(): i.configure(options, updated) def add(self, options, *addons): if not addons: raise ValueError("No addons specified.") self.chain.extend(addons) for i in addons: self.invoke_with_context(i, "start") self.invoke_with_context( i, "configure", self.master.options, self.master.options.keys() ) def remove(self, addon): self.chain = [i for i in self.chain if i is not addon] self.invoke_with_context(addon, "done") def done(self): for i in self.chain: self.invoke_with_context(i, "done") def has_addon(self, name): """ Is an addon with this name registered? """ for i in self.chain: if _get_name(i) == name: return True def __len__(self): return len(self.chain) def __str__(self): return pprint.pformat([str(i) for i in self.chain]) def invoke_with_context(self, addon, name, *args, **kwargs): with self.master.handlecontext(): self.invoke(addon, name, *args, **kwargs) def invoke(self, addon, name, *args, **kwargs): func = getattr(addon, name, None) if func: if not callable(func): raise exceptions.AddonError( "Addon handler %s not callable" % name ) func(*args, **kwargs) def __call__(self, name, *args, **kwargs): for i in self.chain: self.invoke(i, name, *args, **kwargs)
x2Ident/x2Ident_test
mitmproxy/mitmproxy/addons.py
Python
gpl-3.0
2,173
#! /usr/bin/env python ################################################################################################# # # Script Name: bip.py # Script Usage: This script is the menu system and runs everything else. Do not use other # files unless you are comfortable with the code. # # It has the following: # 1. # 2. # 3. # 4. # # You will probably want to do the following: # 1. Make sure the info in bip_config.py is correct. # 2. Make sure GAM (Google Apps Manager) is installed and the path is correct. # 3. Make sure the AD scripts in toos/ are present on the DC running run.ps1. # # Script Updates: # 201709191243 - rdegennaro@sscps.org - copied boilerplate. # ################################################################################################# import os # os.system for clearing screen and simple gam calls import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular) import MySQLdb # MySQLdb is to get data from relevant tables import csv # CSV is used to read output of drive commands that supply data in CSV form import bip_config # declare installation specific variables # setup for MySQLdb connection varMySQLHost = bip_config.mysqlconfig['host'] varMySQLUser = bip_config.mysqlconfig['user'] varMySQLPassword = bip_config.mysqlconfig['password'] varMySQLDB = bip_config.mysqlconfig['db'] # setup to find GAM varCommandGam = bip_config.gamconfig['fullpath'] ################################################################################################# # #################################################################################################
SSCPS/bip-gam-v1
bip.py
Python
gpl-3.0
1,835
/* * Copyright (c) 2013 The Interedition Development Group. * * This file is part of CollateX. * * CollateX 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. * * CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.text.xml; import com.google.common.base.Objects; import javax.xml.XMLConstants; import javax.xml.stream.XMLStreamReader; import java.util.Stack; /** * @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a> */ public class WhitespaceCompressor extends ConversionFilter { private final Stack<Boolean> spacePreservationContext = new Stack<Boolean>(); private final WhitespaceStrippingContext whitespaceStrippingContext; private char lastChar = ' '; public WhitespaceCompressor(WhitespaceStrippingContext whitespaceStrippingContext) { this.whitespaceStrippingContext = whitespaceStrippingContext; } @Override public void start() { spacePreservationContext.clear(); whitespaceStrippingContext.reset(); lastChar = ' '; } @Override protected void onXMLEvent(XMLStreamReader reader) { whitespaceStrippingContext.onXMLEvent(reader); if (reader.isStartElement()) { spacePreservationContext.push(spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek()); final Object xmlSpace = reader.getAttributeValue(XMLConstants.XML_NS_URI, "space"); if (xmlSpace != null) { spacePreservationContext.pop(); spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString())); } } else if (reader.isEndElement()) { spacePreservationContext.pop(); } } String compress(String text) { final StringBuilder compressed = new StringBuilder(); final boolean preserveSpace = Objects.firstNonNull(spacePreservationContext.peek(), false); for (int cc = 0, length = text.length(); cc < length; cc++) { char currentChar = text.charAt(cc); if (!preserveSpace && Character.isWhitespace(currentChar) && (Character.isWhitespace(lastChar) || whitespaceStrippingContext.isInContainerElement())) { continue; } if (currentChar == '\n' || currentChar == '\r') { currentChar = ' '; } compressed.append(lastChar = currentChar); } return compressed.toString(); } }
faustedition/text
text-core/src/main/java/eu/interedition/text/xml/WhitespaceCompressor.java
Java
gpl-3.0
3,002
/* * Copyright (C) 2016-2021 David Rubio Escares / Kodehawa * * Mantaro 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. * Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/ */ package net.kodehawa.mantarobot.commands.currency.profile; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class BadgeUtils { public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) { BufferedImage avatar; BufferedImage badge; try { avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes)); badge = ImageIO.read(new ByteArrayInputStream(badgeBytes)); } catch (IOException impossible) { throw new AssertionError(impossible); } WritableRaster raster = badge.getRaster(); if (allWhite) { for (int xx = 0, width = badge.getWidth(); xx < width; xx++) { for (int yy = 0, height = badge.getHeight(); yy < height; yy++) { int[] pixels = raster.getPixel(xx, yy, (int[]) null); pixels[0] = 255; pixels[1] = 255; pixels[2] = 255; pixels[3] = pixels[3] == 255 ? 165 : 0; raster.setPixel(xx, yy, pixels); } } } BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); int circleCenterX = 88, circleCenterY = 88; int width = 32, height = 32; int circleRadius = 40; Graphics2D g2d = res.createGraphics(); g2d.drawImage(avatar, 0, 0, 128, 128, null); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(new Color(0, 0, 165, 165)); g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius); g2d.drawImage(badge, startX, startY, width, height, null); g2d.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(res, "png", baos); } catch (IOException e) { throw new AssertionError(e); } return baos.toByteArray(); } }
Mantaro/MantaroBot
src/main/java/net/kodehawa/mantarobot/commands/currency/profile/BadgeUtils.java
Java
gpl-3.0
2,976
require 'polyhoraire/auth' require 'test/unit' require 'yaml' class TestAuth < Test::Unit::TestCase def setup @config = YAML.load_file("conf/test_poly.yaml") end def test_connect assert_nothing_raised do auth = Poly::Auth.new user = @config['credentials']['user'] password = @config['credentials']['password'] bday = @config['credentials']['bday'] auth.connect(user,password,bday) end end end
flatzo/polyhoraire
test/polyhoraire/test_auth.rb
Ruby
gpl-3.0
472
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ 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. # # ESPResSo++ 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/>. r""" ******************************************** **espressopp.integrator.LangevinThermostat** ******************************************** .. function:: espressopp.integrator.LangevinThermostat(system) :param system: :type system: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_LangevinThermostat class LangevinThermostatLocal(ExtensionLocal, integrator_LangevinThermostat): def __init__(self, system): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_LangevinThermostat, system) #def enableAdress(self): # if pmi.workerIsActive(): # self.cxxclass.enableAdress(self); if pmi.isController : class LangevinThermostat(Extension): __metaclass__ = pmi.Proxy pmiproxydefs = dict( cls = 'espressopp.integrator.LangevinThermostatLocal', pmiproperty = [ 'gamma', 'temperature', 'adress' ] )
capoe/espressopp.soap
src/integrator/LangevinThermostat.py
Python
gpl-3.0
1,956
asm(1000){ var a = 1; };
soliton4/promiseLand-website
release/client/promiseland/playground/asmsyntax.js
JavaScript
gpl-3.0
27
<?php /** * Modify layout using filter */ /** * Available actions (by ref) * dynamic_block_{block_name}_before where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array * dynamic_block_{block_name}_before_block_items * dynamic_block_{block_name}_after where block_name is name of block e.g. header. action can have two arguments "block" and "block_settings" as array * If you want to disable certain block base on certain condition(s), you can add hide key to $block * You can override render callback of block items by writing a function theme_block_item_{block_item_id} where block_item_id is id of block item e.g. widget, shortcode, post_loop etc. */ /** * Manipulate block items at runtime. * Add logos dynamically without providing any control to user. * * @since 1.0.0.0 * * @param ref array $block_items list of block items in a block * @return void */ function le_theme_filter_header_block_items(&$block_items) { if(!empty($block_items)) { $blocks_new = array(); $blocks_new[] = array( 'id' => 'theme_logo', 'name' => 'Runtime Logos', 'title' => '', 'columns' => 3, 'runtime_id' => 'o7r7ot', 'args' => array() ); foreach($block_items as $item) $blocks_new[] = $item; $block_items = $blocks_new; } } add_action('dynamic_block_header_before_block_items', 'le_theme_filter_header_block_items') ?>
simpleux/le-twentyeleven
extensions/hard_coded_filters.php
PHP
gpl-3.0
1,457
/******************************************************************************* * Copyright (c) 2014 Tombenpotter. * All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at http://www.gnu.org/licenses/gpl.html * * This class was made by Tombenpotter and is distributed as a part of the Electro-Magic Tools mod. * Electro-Magic Tools is a derivative work on Thaumcraft 4 (c) Azanor 2012. * http://www.minecraftforum.net/topic/1585216- ******************************************************************************/ package tombenpotter.emt.common.util; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; public class ResearchAspects { public static AspectList thaumiumDrillResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4); public static AspectList thaumiumChainsawResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.WEAPON, 6).add(Aspect.TOOL, 4); public static AspectList thaumicQuantumHelmet = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 4).add(Aspect.SENSES, 6); public static AspectList diamondOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.TOOL, 3).add(Aspect.MINE, 2).add(Aspect.WEAPON, 2); public static AspectList thaumiumOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4).add(Aspect.WEAPON, 6); public static AspectList thaumicNanoHelmet = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.SENSES, 8).add(Aspect.ARMOR, 6); public static AspectList laserFocusResearch = new AspectList().add(Aspect.FIRE, 3).add(Aspect.DEATH, 2).add(Aspect.WEAPON, 3); public static AspectList christmasFocusResearch = new AspectList().add(Aspect.COLD, 2).add(Aspect.BEAST, 5).add(Aspect.LIFE, 6); public static AspectList shieldFocusResearch = new AspectList().add(Aspect.ARMOR, 5).add(Aspect.AIR, 2).add(Aspect.CRYSTAL, 3).add(Aspect.TRAP, 2); public static AspectList electricGogglesResearch = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 5).add(Aspect.SENSES, 6); public static AspectList potentiaGeneratorResearch = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.EXCHANGE, 4).add(Aspect.METAL, 3); public static AspectList ignisGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.FIRE, 3); public static AspectList auramGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AURA, 3); public static AspectList arborGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.TREE, 3); public static AspectList streamChainsawResearch = new AspectList().add(Aspect.TOOL, 3).add(Aspect.TREE, 3).add(Aspect.WATER, 6).add(Aspect.ENERGY, 4); public static AspectList rockbreakerDrillResearch = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.FIRE, 2).add(Aspect.MINE, 3); public static AspectList shieldBlockResearch = new AspectList().add(Aspect.ARMOR, 3).add(Aspect.TRAP, 2); public static AspectList tinyUraniumResearch = new AspectList().add(Aspect.POISON, 4).add(Aspect.DEATH, 3).add(Aspect.EXCHANGE, 3); public static AspectList thorHammerResearch = new AspectList().add(Aspect.WEAPON, 3).add(Aspect.WEATHER, 4).add(Aspect.ELDRITCH, 3); public static AspectList superchargedThorHammerResearch = new AspectList().add(Aspect.WEAPON, 4).add(Aspect.ENERGY, 6).add(Aspect.BEAST, 4); public static AspectList wandCharger = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRAFT, 2).add(Aspect.EXCHANGE, 3).add(Aspect.GREED, 5); public static AspectList compressedSolars = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.LIGHT, 3).add(Aspect.METAL, 2); public static AspectList solarHelmetRevealing = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AIR, 2).add(Aspect.LIGHT, 4); public static AspectList electricBootsTravel = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 2); public static AspectList nanoBootsTravel = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 3); public static AspectList quantumBootsTravel = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 4); public static AspectList electricScribingTools = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.DARKNESS, 3).add(Aspect.CRAFT, 1); public static AspectList etherealProcessor = new AspectList().add(Aspect.MECHANISM, 3).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5); public static AspectList waterSolars = new AspectList().add(Aspect.WATER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList darkSolars = new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList orderSolars = new AspectList().add(Aspect.ORDER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList fireSolars = new AspectList().add(Aspect.FIRE, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList airSolars = new AspectList().add(Aspect.AIR, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList earthSolars = new AspectList().add(Aspect.EARTH, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4); public static AspectList uuMInfusion = new AspectList().add(Aspect.ELDRITCH, 4).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5); public static AspectList portableNode = new AspectList().add(Aspect.MAGIC, 5).add(Aspect.AURA, 5).add(Aspect.GREED, 5); public static AspectList electricHoeGrowth = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.PLANT, 4).add(Aspect.CROP, 5).add(Aspect.MAGIC, 4); public static AspectList chargeFocus = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.ENERGY, 5).add(Aspect.MECHANISM, 4); public static AspectList wandChargeFocus = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AURA, 4).add(Aspect.EXCHANGE, 4).add(Aspect.GREED, 5); public static AspectList inventoryChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRYSTAL, 4).add(Aspect.MAGIC, 4); public static AspectList armorChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 4).add(Aspect.MAGIC, 4); public static AspectList thaumiumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8); public static AspectList nanoWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4); public static AspectList quantumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4); public static AspectList aerGenerator = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AIR, 3); }
TeamAmeriFrance/Electro-Magic-Tools
src/main/java/tombenpotter/emt/common/util/ResearchAspects.java
Java
gpl-3.0
6,842
#!/usr/bin/env python3 # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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/>. import argparse import os import subprocess import tempfile ACTIVE_DISTROS = ("xenial", "artful", "bionic") def main(): parser = argparse.ArgumentParser() parser.add_argument("day", help="The day of the results, with format yyyymmdd") args = parser.parse_args() install_autopkgtest_results_formatter() with tempfile.TemporaryDirectory(dir=os.environ.get("HOME")) as temp_dir: clone_results_repo(temp_dir) format_results(temp_dir, ACTIVE_DISTROS, args.day) commit_and_push(temp_dir, args.day) def install_autopkgtest_results_formatter(): subprocess.check_call( ["sudo", "snap", "install", "autopkgtest-results-formatter", "--edge"] ) def clone_results_repo(dest_dir): subprocess.check_call( ["git", "clone", "https://github.com/elopio/autopkgtest-results.git", dest_dir] ) def format_results(dest_dir, distros, day): subprocess.check_call( [ "/snap/bin/autopkgtest-results-formatter", "--destination", dest_dir, "--distros", *distros, "--day", day, ] ) def commit_and_push(repo_dir, day): subprocess.check_call( ["git", "config", "--global", "user.email", "u1test+m-o@canonical.com"] ) subprocess.check_call(["git", "config", "--global", "user.name", "snappy-m-o"]) subprocess.check_call(["git", "-C", repo_dir, "add", "--all"]) subprocess.check_call( [ "git", "-C", repo_dir, "commit", "--message", "Add the results for {}".format(day), ] ) subprocess.check_call( [ "git", "-C", repo_dir, "push", "https://{GH_TOKEN}@github.com/elopio/autopkgtest-results.git".format( GH_TOKEN=os.environ.get("GH_TOKEN_PPA_AUTOPKGTEST_RESULTS") ), ] ) if __name__ == "__main__": main()
snapcore/snapcraft
tools/collect_ppa_autopkgtests_results.py
Python
gpl-3.0
2,694
package monitor; public interface RunnableWithResult<T> { public T run() ; }
erseco/ugr_sistemas_concurrentes_distribuidos
Practica_02_monitores/monitor/RunnableWithResult.java
Java
gpl-3.0
84
\item Due segmenti AB ed AC sono sovrapposti come in figura. Se AB è lungo 4 cm ed AC è lungo 6 cm, che operazione fai per calcolare la lunghezza di BC? \begin{figure}[h] \centering \includegraphics[width=13cm]{figure/somma_diff_segmenti.PNG} \end{figure}
giovannicorvino/scuolasoft
esercizi/Es_0137.tex
TeX
gpl-3.0
263
/* Copyright (C) 2013 Hong Jen Yee (PCMan) <pcman.tw@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "filepropsdialog.h" #include "ui_file-props.h" #include "icontheme.h" #include "utilities.h" #include "fileoperation.h" #include <QStringBuilder> #include <QStringListModel> #include <QMessageBox> #include <qdial.h> #include <sys/types.h> #include <time.h> #define DIFFERENT_UIDS ((uid)-1) #define DIFFERENT_GIDS ((gid)-1) #define DIFFERENT_PERMS ((mode_t)-1) using namespace Fm; enum { ACCESS_NO_CHANGE = 0, ACCESS_READ_ONLY, ACCESS_READ_WRITE, ACCESS_FORBID }; FilePropsDialog::FilePropsDialog(FmFileInfoList* files, QWidget* parent, Qt::WindowFlags f): QDialog(parent, f), fileInfos_(fm_file_info_list_ref(files)), singleType(fm_file_info_list_is_same_type(files)), singleFile(fm_file_info_list_get_length(files) == 1 ? true:false), fileInfo(fm_file_info_list_peek_head(files)), mimeType(NULL) { setAttribute(Qt::WA_DeleteOnClose); ui = new Ui::FilePropsDialog(); ui->setupUi(this); if(singleType) { mimeType = fm_mime_type_ref(fm_file_info_get_mime_type(fileInfo)); } FmPathList* paths = fm_path_list_new_from_file_info_list(files); deepCountJob = fm_deep_count_job_new(paths, FM_DC_JOB_DEFAULT); fm_path_list_unref(paths); initGeneralPage(); initPermissionsPage(); } FilePropsDialog::~FilePropsDialog() { delete ui; if(fileInfos_) fm_file_info_list_unref(fileInfos_); if(deepCountJob) g_object_unref(deepCountJob); if(fileSizeTimer) { fileSizeTimer->stop(); delete fileSizeTimer; fileSizeTimer = NULL; } } void FilePropsDialog::initApplications() { if(singleType && mimeType && !fm_file_info_is_dir(fileInfo)) { ui->openWith->setMimeType(mimeType); } else { ui->openWith->hide(); ui->openWithLabel->hide(); } } void FilePropsDialog::initPermissionsPage() { // ownership handling // get owner/group and mode of the first file in the list uid = fm_file_info_get_uid(fileInfo); gid = fm_file_info_get_gid(fileInfo); mode_t mode = fm_file_info_get_mode(fileInfo); ownerPerm = (mode & (S_IRUSR|S_IWUSR|S_IXUSR)); groupPerm = (mode & (S_IRGRP|S_IWGRP|S_IXGRP)); otherPerm = (mode & (S_IROTH|S_IWOTH|S_IXOTH)); execPerm = (mode & (S_IXUSR|S_IXGRP|S_IXOTH)); allNative = fm_file_info_is_native(fileInfo); hasDir = S_ISDIR(mode); // check if all selected files belongs to the same owner/group or have the same mode // at the same time, check if all files are on native unix filesystems GList* l; for(l = fm_file_info_list_peek_head_link(fileInfos_)->next; l; l = l->next) { FmFileInfo* fi = FM_FILE_INFO(l->data); if(allNative && !fm_file_info_is_native(fi)) allNative = false; // not all of the files are native mode_t fi_mode = fm_file_info_get_mode(fi); if(S_ISDIR(fi_mode)) hasDir = true; // the files list contains dir(s) if(uid != DIFFERENT_UIDS && uid != fm_file_info_get_uid(fi)) uid = DIFFERENT_UIDS; // not all files have the same owner if(gid != DIFFERENT_GIDS && gid != fm_file_info_get_gid(fi)) gid = DIFFERENT_GIDS; // not all files have the same owner group if(ownerPerm != DIFFERENT_PERMS && ownerPerm != (fi_mode & (S_IRUSR|S_IWUSR|S_IXUSR))) ownerPerm = DIFFERENT_PERMS; // not all files have the same permission for owner if(groupPerm != DIFFERENT_PERMS && groupPerm != (fi_mode & (S_IRGRP|S_IWGRP|S_IXGRP))) groupPerm = DIFFERENT_PERMS; // not all files have the same permission for grop if(otherPerm != DIFFERENT_PERMS && otherPerm != (fi_mode & (S_IROTH|S_IWOTH|S_IXOTH))) otherPerm = DIFFERENT_PERMS; // not all files have the same permission for other if(execPerm != DIFFERENT_PERMS && execPerm != (fi_mode & (S_IXUSR|S_IXGRP|S_IXOTH))) execPerm = DIFFERENT_PERMS; // not all files have the same executable permission } // init owner/group initOwner(); // if all files are of the same type, and some of them are dirs => all of the items are dirs // rwx values have different meanings for dirs // Let's make it clear for the users // init combo boxes for file permissions here QStringList comboItems; comboItems.append("---"); // no change if(singleType && hasDir) { // all files are dirs comboItems.append(tr("View folder content")); comboItems.append(tr("View and modify folder content")); ui->executable->hide(); } else { //not all of the files are dirs comboItems.append(tr("Read")); comboItems.append(tr("Read and write")); } comboItems.append(tr("Forbidden")); QStringListModel* comboModel = new QStringListModel(comboItems, this); ui->ownerPerm->setModel(comboModel); ui->groupPerm->setModel(comboModel); ui->otherPerm->setModel(comboModel); // owner ownerPermSel = ACCESS_NO_CHANGE; if(ownerPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files if(ownerPerm & S_IRUSR) { // can read if(ownerPerm & S_IWUSR) // can write ownerPermSel = ACCESS_READ_WRITE; else ownerPermSel = ACCESS_READ_ONLY; } else { if((ownerPerm & S_IWUSR) == 0) // cannot read or write ownerPermSel = ACCESS_FORBID; } } ui->ownerPerm->setCurrentIndex(ownerPermSel); // owner and group groupPermSel = ACCESS_NO_CHANGE; if(groupPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files if(groupPerm & S_IRGRP) { // can read if(groupPerm & S_IWGRP) // can write groupPermSel = ACCESS_READ_WRITE; else groupPermSel = ACCESS_READ_ONLY; } else { if((groupPerm & S_IWGRP) == 0) // cannot read or write groupPermSel = ACCESS_FORBID; } } ui->groupPerm->setCurrentIndex(groupPermSel); // other otherPermSel = ACCESS_NO_CHANGE; if(otherPerm != DIFFERENT_PERMS) { // permissions for owner are the same among all files if(otherPerm & S_IROTH) { // can read if(otherPerm & S_IWOTH) // can write otherPermSel = ACCESS_READ_WRITE; else otherPermSel = ACCESS_READ_ONLY; } else { if((otherPerm & S_IWOTH) == 0) // cannot read or write otherPermSel = ACCESS_FORBID; } } ui->otherPerm->setCurrentIndex(otherPermSel); // set the checkbox to partially checked state // when owner, group, and other have different executable flags set. // some of them have exec, and others do not have. execCheckState = Qt::PartiallyChecked; if(execPerm != DIFFERENT_PERMS) { // if all files have the same executable permission // check if the files are all executable if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == (S_IXUSR|S_IXGRP|S_IXOTH)) { // owner, group, and other all have exec permission. execCheckState = Qt::Checked; } else if((mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) { // owner, group, and other all have no exec permission execCheckState = Qt::Unchecked; } } ui->executable->setCheckState(execCheckState); } void FilePropsDialog::initGeneralPage() { // update UI if(singleType) { // all files are of the same mime-type FmIcon* icon = NULL; // FIXME: handle custom icons for some files // FIXME: display special property pages for special files or // some specified mime-types. if(singleFile) { // only one file is selected. icon = fm_file_info_get_icon(fileInfo); } if(mimeType) { if(!icon) // get an icon from mime type if needed icon = fm_mime_type_get_icon(mimeType); ui->fileType->setText(QString::fromUtf8(fm_mime_type_get_desc(mimeType))); ui->mimeType->setText(QString::fromUtf8(fm_mime_type_get_type(mimeType))); } if(icon) { ui->iconButton->setIcon(IconTheme::icon(icon)); } if(singleFile && fm_file_info_is_symlink(fileInfo)) { ui->target->setText(QString::fromUtf8(fm_file_info_get_target(fileInfo))); } else { ui->target->hide(); ui->targetLabel->hide(); } } // end if(singleType) else { // not singleType, multiple files are selected at the same time ui->fileType->setText(tr("Files of different types")); ui->target->hide(); ui->targetLabel->hide(); } // FIXME: check if all files has the same parent dir, mtime, or atime if(singleFile) { // only one file is selected FmPath* parent_path = fm_path_get_parent(fm_file_info_get_path(fileInfo)); char* parent_str = parent_path ? fm_path_display_name(parent_path, true) : NULL; ui->fileName->setText(QString::fromUtf8(fm_file_info_get_disp_name(fileInfo))); if(parent_str) { ui->location->setText(QString::fromUtf8(parent_str)); g_free(parent_str); } else ui->location->clear(); ui->lastModified->setText(QString::fromUtf8(fm_file_info_get_disp_mtime(fileInfo))); // FIXME: need to encapsulate this in an libfm API. time_t atime; struct tm tm; atime = fm_file_info_get_atime(fileInfo); localtime_r(&atime, &tm); char buf[128]; strftime(buf, sizeof(buf), "%x %R", &tm); ui->lastAccessed->setText(QString::fromUtf8(buf)); } else { ui->fileName->setText(tr("Multiple Files")); ui->fileName->setEnabled(false); } initApplications(); // init applications combo box // calculate total file sizes fileSizeTimer = new QTimer(this); connect(fileSizeTimer, SIGNAL(timeout()), SLOT(onFileSizeTimerTimeout())); fileSizeTimer->start(600); g_signal_connect(deepCountJob, "finished", G_CALLBACK(onDeepCountJobFinished), this); fm_job_run_async(FM_JOB(deepCountJob)); } /*static */ void FilePropsDialog::onDeepCountJobFinished(FmDeepCountJob* job, FilePropsDialog* pThis) { pThis->onFileSizeTimerTimeout(); // update file size display // free the job g_object_unref(pThis->deepCountJob); pThis->deepCountJob = NULL; // stop the timer if(pThis->fileSizeTimer) { pThis->fileSizeTimer->stop(); delete pThis->fileSizeTimer; pThis->fileSizeTimer = NULL; } } void FilePropsDialog::onFileSizeTimerTimeout() { if(deepCountJob && !fm_job_is_cancelled(FM_JOB(deepCountJob))) { char size_str[128]; fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_size, fm_config->si_unit); // FIXME: // OMG! It's really unbelievable that Qt developers only implement // QObject::tr(... int n). GNU gettext developers are smarter and // they use unsigned long instead of int. // We cannot use Qt here to handle plural forms. So sad. :-( QString str = QString::fromUtf8(size_str) % QString(" (%1 B)").arg(deepCountJob->total_size); // tr(" (%n) byte(s)", "", deepCountJob->total_size); ui->fileSize->setText(str); fm_file_size_to_str(size_str, sizeof(size_str), deepCountJob->total_ondisk_size, fm_config->si_unit); str = QString::fromUtf8(size_str) % QString(" (%1 B)").arg(deepCountJob->total_ondisk_size); // tr(" (%n) byte(s)", "", deepCountJob->total_ondisk_size); ui->onDiskSize->setText(str); } } void FilePropsDialog::accept() { // applications if(mimeType && ui->openWith->isChanged()) { GAppInfo* currentApp = ui->openWith->selectedApp(); g_app_info_set_as_default_for_type(currentApp, fm_mime_type_get_type(mimeType), NULL); } // check if chown or chmod is needed guint32 newUid = uidFromName(ui->owner->text()); guint32 newGid = gidFromName(ui->ownerGroup->text()); bool needChown = (newUid != uid || newGid != gid); int newOwnerPermSel = ui->ownerPerm->currentIndex(); int newGroupPermSel = ui->groupPerm->currentIndex(); int newOtherPermSel = ui->otherPerm->currentIndex(); Qt::CheckState newExecCheckState = ui->executable->checkState(); bool needChmod = ((newOwnerPermSel != ownerPermSel) || (newGroupPermSel != groupPermSel) || (newOtherPermSel != otherPermSel) || (newExecCheckState != execCheckState)); if(needChmod || needChown) { FmPathList* paths = fm_path_list_new_from_file_info_list(fileInfos_); FileOperation* op = new FileOperation(FileOperation::ChangeAttr, paths); fm_path_list_unref(paths); if(needChown) { // don't do chown if new uid/gid and the original ones are actually the same. if(newUid == uid) newUid = -1; if(newGid == gid) newGid = -1; op->setChown(newUid, newGid); } if(needChmod) { mode_t newMode = 0; mode_t newModeMask = 0; // FIXME: we need to make sure that folders with "r" permission also have "x" // at the same time. Otherwise, it's not able to browse the folder later. if(newOwnerPermSel != ownerPermSel && newOwnerPermSel != ACCESS_NO_CHANGE) { // owner permission changed newModeMask |= (S_IRUSR|S_IWUSR); // affect user bits if(newOwnerPermSel == ACCESS_READ_ONLY) newMode |= S_IRUSR; else if(newOwnerPermSel == ACCESS_READ_WRITE) newMode |= (S_IRUSR|S_IWUSR); } if(newGroupPermSel != groupPermSel && newGroupPermSel != ACCESS_NO_CHANGE) { qDebug("newGroupPermSel: %d", newGroupPermSel); // group permission changed newModeMask |= (S_IRGRP|S_IWGRP); // affect group bits if(newGroupPermSel == ACCESS_READ_ONLY) newMode |= S_IRGRP; else if(newGroupPermSel == ACCESS_READ_WRITE) newMode |= (S_IRGRP|S_IWGRP); } if(newOtherPermSel != otherPermSel && newOtherPermSel != ACCESS_NO_CHANGE) { // other permission changed newModeMask |= (S_IROTH|S_IWOTH); // affect other bits if(newOtherPermSel == ACCESS_READ_ONLY) newMode |= S_IROTH; else if(newOtherPermSel == ACCESS_READ_WRITE) newMode |= (S_IROTH|S_IWOTH); } if(newExecCheckState != execCheckState && newExecCheckState != Qt::PartiallyChecked) { // executable state changed newModeMask |= (S_IXUSR|S_IXGRP|S_IXOTH); if(newExecCheckState == Qt::Checked) newMode |= (S_IXUSR|S_IXGRP|S_IXOTH); } op->setChmod(newMode, newModeMask); if(hasDir) { // if there are some dirs in our selected files QMessageBox::StandardButton r = QMessageBox::question(this, tr("Apply changes"), tr("Do you want to recursively apply these changes to all files and sub-folders?"), QMessageBox::Yes|QMessageBox::No); if(r == QMessageBox::Yes) op->setRecursiveChattr(true); } } op->setAutoDestroy(true); op->run(); } QDialog::accept(); } void FilePropsDialog::initOwner() { if(allNative) { if(uid != DIFFERENT_UIDS) ui->owner->setText(uidToName(uid)); if(gid != DIFFERENT_GIDS) ui->ownerGroup->setText(gidToName(gid)); if(geteuid() != 0) { // on local filesystems, only root can do chown. ui->owner->setEnabled(false); ui->ownerGroup->setEnabled(false); } } }
MoonLightDE/MoonLightDE
src/file-manager/libfm-qt/filepropsdialog.cpp
C++
gpl-3.0
15,744
/************************************************************************ Extended WPF Toolkit Copyright (C) 2010-2012 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license This program can be provided to you by Xceed Software Inc. under a proprietary commercial license agreement for use in non-Open Source projects. The commercial version of Extended WPF Toolkit also includes priority technical support, commercial updates, and many additional useful WPF controls if you license Xceed Business Suite for WPF. Visit http://xceed.com and follow @datagrid on Twitter. **********************************************************************/ using System; using System.Windows.Data; using System.Windows.Media; namespace Xceed.Wpf.Toolkit.Core.Converters { public class ColorToSolidColorBrushConverter : IValueConverter { #region IValueConverter Members /// <summary> /// Converts a Color to a SolidColorBrush. /// </summary> /// <param name="value">The Color produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns> /// A converted SolidColorBrush. If the method returns null, the valid null value is used. /// </returns> public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) { if( value != null ) return new SolidColorBrush( ( Color )value ); return value; } /// <summary> /// Converts a SolidColorBrush to a Color. /// </summary> /// <remarks>Currently not used in toolkit, but provided for developer use in their own projects</remarks> /// <param name="value">The SolidColorBrush that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns> /// A converted value. If the method returns null, the valid null value is used. /// </returns> public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) { if( value != null ) return ( ( SolidColorBrush )value ).Color; return value; } #endregion } }
Emudofus/BehaviorIsManaged
Librairies/WPFToolkit.Extended/Core/Converters/ColorToSolidColorBrushConverter.cs
C#
gpl-3.0
2,652
package cern.colt.matrix.tlong.impl; public class SparseRCMLongMatrix2DViewTest extends SparseRCMLongMatrix2DTest { public SparseRCMLongMatrix2DViewTest(String arg0) { super(arg0); } protected void createMatrices() throws Exception { A = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice(); B = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice(); Bt = new SparseRCMLongMatrix2D(NROWS, NCOLUMNS).viewDice(); } }
Shappiro/GEOFRAME
PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/test/cern/colt/matrix/tlong/impl/SparseRCMLongMatrix2DViewTest.java
Java
gpl-3.0
483
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!-- if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script> <!-- Generated by Natural Docs, version 1.4 --> <!-- http://www.naturaldocs.org --> <!-- saved from url=(0026)http://www.naturaldocs.org --> <div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_FileException><div class=IEntry><a href="../files/lib/exception-file-php.html#FileException" target=_parent class=ISymbol>FileException</a></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults", "HTML"); searchResults.Search(); --></script></div><script language=JavaScript><!-- if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
DrSterling/ezrpg
Docs/search/ClassesF.html
HTML
gpl-3.0
1,455
package handling.handlers; import java.awt.Point; import client.MapleClient; import handling.PacketHandler; import handling.RecvPacketOpcode; import server.MaplePortal; import tools.data.LittleEndianAccessor; public class UseInnerPortalHandler { @PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL) public static void handle(MapleClient c, LittleEndianAccessor lea) { lea.skip(1); if (c.getPlayer() == null || c.getPlayer().getMap() == null) { return; } String portalName = lea.readMapleAsciiString(); MaplePortal portal = c.getPlayer().getMap().getPortal(portalName); if (portal == null) { return; } //That "22500" should not be hard coded in this manner if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) { return; } int toX = lea.readShort(); int toY = lea.readShort(); //Are there not suppose to be checks here? Can players not just PE any x and y value they want? c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY)); c.getPlayer().checkFollow(); } }
Maxcloud/Mushy
src/handling/handlers/UseInnerPortalHandler.java
Java
gpl-3.0
1,090
/* Free Download Manager Copyright (c) 2003-2014 FreeDownloadManager.ORG */ #ifndef __COMMON_H_ #define __COMMON_H_ #include "system.h" #include "fsinet.h" #define SAFE_DELETE_ARRAY(a) {if (a) {delete [] a; a = NULL;}} #endif
DragonZX/fdm
InetFile/common.h
C
gpl-3.0
244
#ifndef REPLY_H #define REPLY_H #include <QNetworkReply> class Reply : public QObject { Q_OBJECT public: int _id; QNetworkReply *res; Reply(int id, QNetworkReply *net){ res = net; _id = id; connect(res,SIGNAL(uploadProgress(qint64,qint64)),this,SLOT(progress(qint64,qint64))); } signals: void percentReady(int percent,int id); public slots: void progress(qint64 up,qint64 to){ float per = (float)100/(float)to*(float)up; percentReady((int)per,_id); } }; #endif
ehopperdietzel/CuarzoPlayer
reply.h
C
gpl-3.0
548
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _VITELOTTE_BEZIER_PATH_ #define _VITELOTTE_BEZIER_PATH_ #include <cassert> #include <vector> #include <Eigen/Geometry> namespace Vitelotte { enum BezierSegmentType { BEZIER_EMPTY = 0, BEZIER_LINEAR = 2, BEZIER_QUADRATIC = 3, BEZIER_CUBIC = 4 }; template < typename _Vector > class BezierSegment { public: typedef typename _Vector::Scalar Scalar; typedef _Vector Vector; typedef BezierSegment<Vector> Self; public: inline BezierSegment() : m_type(BEZIER_EMPTY) {} inline BezierSegment(BezierSegmentType type, const Vector* points) : m_type(type) { std::copy(points, points + type, m_points); } inline BezierSegmentType type() const { return m_type; } inline void setType(BezierSegmentType type) { m_type = type; } inline const Vector& point(unsigned i) const { assert(i < m_type); return m_points[i]; } inline Vector& point(unsigned i) { assert(i < m_type); return m_points[i]; } inline Self getBackward() const { Self seg; seg.setType(type()); for(unsigned i = 0; i < type(); ++i) { seg.point(type() - 1 - i) = point(i); } return seg; } void split(Scalar pos, Self& head, Self& tail) { assert(m_type != BEZIER_EMPTY); // All the points of de Casteljau Algorithm Vector pts[10]; Vector* levels[] = { &pts[9], &pts[7], &pts[4], pts }; // Initialize the current level. std::copy(m_points, m_points + type(), levels[type() - 1]); // Compute all the points for(int level = type()-1; level >= 0; --level) { for(int i = 0; i < level; ++i) { levels[level-1][i] = (Scalar(1) - pos) * levels[level][i] + pos * levels[level][i+1]; } } // Set the segments head.setType(type()); tail.setType(type()); const unsigned last = type() - 1; for(unsigned i = 0; i < type(); ++i) { head.point(i) = levels[last - i][0]; tail.point(i) = levels[i][i]; } } template < typename InIt > void refineUniform(InIt out, unsigned nSplit) { Self head; Self tail = *this; *(out++) = std::make_pair(Scalar(0), point(0)); for(unsigned i = 0; i < nSplit; ++i) { Scalar x = Scalar(i+1) / Scalar(nSplit + 1); tail.split(x, head, tail); *(out++) = std::make_pair(x, tail.point(0)); } *(out++) = std::make_pair(Scalar(1), point(type()-1)); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: BezierSegmentType m_type; Vector m_points[4]; }; template < typename _Vector > class BezierPath { public: typedef _Vector Vector; public: static unsigned size(BezierSegmentType type) { return unsigned(type); } public: inline BezierPath() {} inline unsigned nPoints() const { return m_points.size(); } inline unsigned nSegments() const { return m_segments.size(); } inline BezierSegmentType type(unsigned si) const { return m_segments.at(si).type; } inline unsigned nPoints(unsigned si) const { return size(type(si)); } inline const Vector& point(unsigned pi) const { return m_points.at(pi); } inline Vector& point(unsigned pi) { return m_points.at(pi); } inline const Vector& point(unsigned si, unsigned pi) const { assert(si < nSegments() && pi < nPoints(si)); return m_points.at(m_segments[si].firstPoint + pi); } inline Vector& point(unsigned si, unsigned pi) { assert(si < nSegments() && pi < nPoints(si)); return m_points.at(m_segments[si].firstPoint + pi); } inline void setFirstPoint(const Vector& point) { assert(nPoints() == 0); m_points.push_back(point); } unsigned addSegment(BezierSegmentType type, const Vector* points) { assert(nPoints() != 0); unsigned si = nSegments(); Segment s; s.type = type; s.firstPoint = nPoints() - 1; m_segments.push_back(s); for(unsigned i = 0; i < nPoints(si) - 1; ++i) { m_points.push_back(points[i]); } return si; } BezierSegment<Vector> getSegment(unsigned si) const { assert(si < nSegments()); return BezierSegment<Vector>(type(si), &m_points[m_segments[si].firstPoint]); } private: struct Segment { BezierSegmentType type; unsigned firstPoint; }; typedef std::vector<Vector> PointList; typedef std::vector<Segment> SegmentList; private: PointList m_points; SegmentList m_segments; }; } #endif
cnr-isti-vclab/meshlab
unsupported/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/bezierPath.h
C
gpl-3.0
5,051
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7 Version: 4.7.1 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Dribbble: www.dribbble.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en" dir="rtl"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8" /> <title>Metronic Admin RTL Theme #5 | User Login 3</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1" name="viewport" /> <meta content="Preview page of Metronic Admin RTL Theme #5 for " name="description" /> <meta content="" name="author" /> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN PAGE LEVEL PLUGINS --> <link href="../assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" /> <link href="../assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" /> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN THEME GLOBAL STYLES --> <link href="../assets/global/css/components-rounded-rtl.min.css" rel="stylesheet" id="style_components" type="text/css" /> <link href="../assets/global/css/plugins-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END THEME GLOBAL STYLES --> <!-- BEGIN PAGE LEVEL STYLES --> <link href="../assets/pages/css/login-3-rtl.min.css" rel="stylesheet" type="text/css" /> <!-- END PAGE LEVEL STYLES --> <!-- BEGIN THEME LAYOUT STYLES --> <!-- END THEME LAYOUT STYLES --> <link rel="shortcut icon" href="favicon.ico" /> </head> <!-- END HEAD --> <body class=" login"> <!-- BEGIN LOGO --> <div class="logo"> <a href="index.html"> <img src="../assets/pages/img/logo-big.png" alt="" /> </a> </div> <!-- END LOGO --> <!-- BEGIN LOGIN --> <div class="content"> <!-- BEGIN LOGIN FORM --> <form class="login-form" action="index.html" method="post"> <h3 class="form-title">Login to your account</h3> <div class="alert alert-danger display-hide"> <button class="close" data-close="alert"></button> <span> Enter any username and password. </span> </div> <div class="form-group"> <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that--> <label class="control-label visible-ie8 visible-ie9">Username</label> <div class="input-icon"> <i class="fa fa-user"></i> <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Password</label> <div class="input-icon"> <i class="fa fa-lock"></i> <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" /> </div> </div> <div class="form-actions"> <label class="rememberme mt-checkbox mt-checkbox-outline"> <input type="checkbox" name="remember" value="1" /> Remember me <span></span> </label> <button type="submit" class="btn green pull-right"> Login </button> </div> <div class="login-options"> <h4>Or login with</h4> <ul class="social-icons"> <li> <a class="facebook" data-original-title="facebook" href="javascript:;"> </a> </li> <li> <a class="twitter" data-original-title="Twitter" href="javascript:;"> </a> </li> <li> <a class="googleplus" data-original-title="Goole Plus" href="javascript:;"> </a> </li> <li> <a class="linkedin" data-original-title="Linkedin" href="javascript:;"> </a> </li> </ul> </div> <div class="forget-password"> <h4>Forgot your password ?</h4> <p> no worries, click <a href="javascript:;" id="forget-password"> here </a> to reset your password. </p> </div> <div class="create-account"> <p> Don't have an account yet ?&nbsp; <a href="javascript:;" id="register-btn"> Create an account </a> </p> </div> </form> <!-- END LOGIN FORM --> <!-- BEGIN FORGOT PASSWORD FORM --> <form class="forget-form" action="index.html" method="post"> <h3>Forget Password ?</h3> <p> Enter your e-mail address below to reset your password. </p> <div class="form-group"> <div class="input-icon"> <i class="fa fa-envelope"></i> <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="email" /> </div> </div> <div class="form-actions"> <button type="button" id="back-btn" class="btn grey-salsa btn-outline"> Back </button> <button type="submit" class="btn green pull-right"> Submit </button> </div> </form> <!-- END FORGOT PASSWORD FORM --> <!-- BEGIN REGISTRATION FORM --> <form class="register-form" action="index.html" method="post"> <h3>Sign Up</h3> <p> Enter your personal details below: </p> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Full Name</label> <div class="input-icon"> <i class="fa fa-font"></i> <input class="form-control placeholder-no-fix" type="text" placeholder="Full Name" name="fullname" /> </div> </div> <div class="form-group"> <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that--> <label class="control-label visible-ie8 visible-ie9">Email</label> <div class="input-icon"> <i class="fa fa-envelope"></i> <input class="form-control placeholder-no-fix" type="text" placeholder="Email" name="email" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Address</label> <div class="input-icon"> <i class="fa fa-check"></i> <input class="form-control placeholder-no-fix" type="text" placeholder="Address" name="address" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">City/Town</label> <div class="input-icon"> <i class="fa fa-location-arrow"></i> <input class="form-control placeholder-no-fix" type="text" placeholder="City/Town" name="city" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Country</label> <select name="country" id="country_list" class="select2 form-control"> <option value=""></option> <option value="AF">Afghanistan</option> <option value="AL">Albania</option> <option value="DZ">Algeria</option> <option value="AS">American Samoa</option> <option value="AD">Andorra</option> <option value="AO">Angola</option> <option value="AI">Anguilla</option> <option value="AR">Argentina</option> <option value="AM">Armenia</option> <option value="AW">Aruba</option> <option value="AU">Australia</option> <option value="AT">Austria</option> <option value="AZ">Azerbaijan</option> <option value="BS">Bahamas</option> <option value="BH">Bahrain</option> <option value="BD">Bangladesh</option> <option value="BB">Barbados</option> <option value="BY">Belarus</option> <option value="BE">Belgium</option> <option value="BZ">Belize</option> <option value="BJ">Benin</option> <option value="BM">Bermuda</option> <option value="BT">Bhutan</option> <option value="BO">Bolivia</option> <option value="BA">Bosnia and Herzegowina</option> <option value="BW">Botswana</option> <option value="BV">Bouvet Island</option> <option value="BR">Brazil</option> <option value="IO">British Indian Ocean Territory</option> <option value="BN">Brunei Darussalam</option> <option value="BG">Bulgaria</option> <option value="BF">Burkina Faso</option> <option value="BI">Burundi</option> <option value="KH">Cambodia</option> <option value="CM">Cameroon</option> <option value="CA">Canada</option> <option value="CV">Cape Verde</option> <option value="KY">Cayman Islands</option> <option value="CF">Central African Republic</option> <option value="TD">Chad</option> <option value="CL">Chile</option> <option value="CN">China</option> <option value="CX">Christmas Island</option> <option value="CC">Cocos (Keeling) Islands</option> <option value="CO">Colombia</option> <option value="KM">Comoros</option> <option value="CG">Congo</option> <option value="CD">Congo, the Democratic Republic of the</option> <option value="CK">Cook Islands</option> <option value="CR">Costa Rica</option> <option value="CI">Cote d'Ivoire</option> <option value="HR">Croatia (Hrvatska)</option> <option value="CU">Cuba</option> <option value="CY">Cyprus</option> <option value="CZ">Czech Republic</option> <option value="DK">Denmark</option> <option value="DJ">Djibouti</option> <option value="DM">Dominica</option> <option value="DO">Dominican Republic</option> <option value="EC">Ecuador</option> <option value="EG">Egypt</option> <option value="SV">El Salvador</option> <option value="GQ">Equatorial Guinea</option> <option value="ER">Eritrea</option> <option value="EE">Estonia</option> <option value="ET">Ethiopia</option> <option value="FK">Falkland Islands (Malvinas)</option> <option value="FO">Faroe Islands</option> <option value="FJ">Fiji</option> <option value="FI">Finland</option> <option value="FR">France</option> <option value="GF">French Guiana</option> <option value="PF">French Polynesia</option> <option value="TF">French Southern Territories</option> <option value="GA">Gabon</option> <option value="GM">Gambia</option> <option value="GE">Georgia</option> <option value="DE">Germany</option> <option value="GH">Ghana</option> <option value="GI">Gibraltar</option> <option value="GR">Greece</option> <option value="GL">Greenland</option> <option value="GD">Grenada</option> <option value="GP">Guadeloupe</option> <option value="GU">Guam</option> <option value="GT">Guatemala</option> <option value="GN">Guinea</option> <option value="GW">Guinea-Bissau</option> <option value="GY">Guyana</option> <option value="HT">Haiti</option> <option value="HM">Heard and Mc Donald Islands</option> <option value="VA">Holy See (Vatican City State)</option> <option value="HN">Honduras</option> <option value="HK">Hong Kong</option> <option value="HU">Hungary</option> <option value="IS">Iceland</option> <option value="IN">India</option> <option value="ID">Indonesia</option> <option value="IR">Iran (Islamic Republic of)</option> <option value="IQ">Iraq</option> <option value="IE">Ireland</option> <option value="IL">Israel</option> <option value="IT">Italy</option> <option value="JM">Jamaica</option> <option value="JP">Japan</option> <option value="JO">Jordan</option> <option value="KZ">Kazakhstan</option> <option value="KE">Kenya</option> <option value="KI">Kiribati</option> <option value="KP">Korea, Democratic People's Republic of</option> <option value="KR">Korea, Republic of</option> <option value="KW">Kuwait</option> <option value="KG">Kyrgyzstan</option> <option value="LA">Lao People's Democratic Republic</option> <option value="LV">Latvia</option> <option value="LB">Lebanon</option> <option value="LS">Lesotho</option> <option value="LR">Liberia</option> <option value="LY">Libyan Arab Jamahiriya</option> <option value="LI">Liechtenstein</option> <option value="LT">Lithuania</option> <option value="LU">Luxembourg</option> <option value="MO">Macau</option> <option value="MK">Macedonia, The Former Yugoslav Republic of</option> <option value="MG">Madagascar</option> <option value="MW">Malawi</option> <option value="MY">Malaysia</option> <option value="MV">Maldives</option> <option value="ML">Mali</option> <option value="MT">Malta</option> <option value="MH">Marshall Islands</option> <option value="MQ">Martinique</option> <option value="MR">Mauritania</option> <option value="MU">Mauritius</option> <option value="YT">Mayotte</option> <option value="MX">Mexico</option> <option value="FM">Micronesia, Federated States of</option> <option value="MD">Moldova, Republic of</option> <option value="MC">Monaco</option> <option value="MN">Mongolia</option> <option value="MS">Montserrat</option> <option value="MA">Morocco</option> <option value="MZ">Mozambique</option> <option value="MM">Myanmar</option> <option value="NA">Namibia</option> <option value="NR">Nauru</option> <option value="NP">Nepal</option> <option value="NL">Netherlands</option> <option value="AN">Netherlands Antilles</option> <option value="NC">New Caledonia</option> <option value="NZ">New Zealand</option> <option value="NI">Nicaragua</option> <option value="NE">Niger</option> <option value="NG">Nigeria</option> <option value="NU">Niue</option> <option value="NF">Norfolk Island</option> <option value="MP">Northern Mariana Islands</option> <option value="NO">Norway</option> <option value="OM">Oman</option> <option value="PK">Pakistan</option> <option value="PW">Palau</option> <option value="PA">Panama</option> <option value="PG">Papua New Guinea</option> <option value="PY">Paraguay</option> <option value="PE">Peru</option> <option value="PH">Philippines</option> <option value="PN">Pitcairn</option> <option value="PL">Poland</option> <option value="PT">Portugal</option> <option value="PR">Puerto Rico</option> <option value="QA">Qatar</option> <option value="RE">Reunion</option> <option value="RO">Romania</option> <option value="RU">Russian Federation</option> <option value="RW">Rwanda</option> <option value="KN">Saint Kitts and Nevis</option> <option value="LC">Saint LUCIA</option> <option value="VC">Saint Vincent and the Grenadines</option> <option value="WS">Samoa</option> <option value="SM">San Marino</option> <option value="ST">Sao Tome and Principe</option> <option value="SA">Saudi Arabia</option> <option value="SN">Senegal</option> <option value="SC">Seychelles</option> <option value="SL">Sierra Leone</option> <option value="SG">Singapore</option> <option value="SK">Slovakia (Slovak Republic)</option> <option value="SI">Slovenia</option> <option value="SB">Solomon Islands</option> <option value="SO">Somalia</option> <option value="ZA">South Africa</option> <option value="GS">South Georgia and the South Sandwich Islands</option> <option value="ES">Spain</option> <option value="LK">Sri Lanka</option> <option value="SH">St. Helena</option> <option value="PM">St. Pierre and Miquelon</option> <option value="SD">Sudan</option> <option value="SR">Suriname</option> <option value="SJ">Svalbard and Jan Mayen Islands</option> <option value="SZ">Swaziland</option> <option value="SE">Sweden</option> <option value="CH">Switzerland</option> <option value="SY">Syrian Arab Republic</option> <option value="TW">Taiwan, Province of China</option> <option value="TJ">Tajikistan</option> <option value="TZ">Tanzania, United Republic of</option> <option value="TH">Thailand</option> <option value="TG">Togo</option> <option value="TK">Tokelau</option> <option value="TO">Tonga</option> <option value="TT">Trinidad and Tobago</option> <option value="TN">Tunisia</option> <option value="TR">Turkey</option> <option value="TM">Turkmenistan</option> <option value="TC">Turks and Caicos Islands</option> <option value="TV">Tuvalu</option> <option value="UG">Uganda</option> <option value="UA">Ukraine</option> <option value="AE">United Arab Emirates</option> <option value="GB">United Kingdom</option> <option value="US">United States</option> <option value="UM">United States Minor Outlying Islands</option> <option value="UY">Uruguay</option> <option value="UZ">Uzbekistan</option> <option value="VU">Vanuatu</option> <option value="VE">Venezuela</option> <option value="VN">Viet Nam</option> <option value="VG">Virgin Islands (British)</option> <option value="VI">Virgin Islands (U.S.)</option> <option value="WF">Wallis and Futuna Islands</option> <option value="EH">Western Sahara</option> <option value="YE">Yemen</option> <option value="ZM">Zambia</option> <option value="ZW">Zimbabwe</option> </select> </div> <p> Enter your account details below: </p> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Username</label> <div class="input-icon"> <i class="fa fa-user"></i> <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Password</label> <div class="input-icon"> <i class="fa fa-lock"></i> <input class="form-control placeholder-no-fix" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" /> </div> </div> <div class="form-group"> <label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label> <div class="controls"> <div class="input-icon"> <i class="fa fa-check"></i> <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" /> </div> </div> </div> <div class="form-group"> <label class="mt-checkbox mt-checkbox-outline"> <input type="checkbox" name="tnc" /> I agree to the <a href="javascript:;">Terms of Service </a> & <a href="javascript:;">Privacy Policy </a> <span></span> </label> <div id="register_tnc_error"> </div> </div> <div class="form-actions"> <button id="register-back-btn" type="button" class="btn grey-salsa btn-outline"> Back </button> <button type="submit" id="register-submit-btn" class="btn green pull-right"> Sign Up </button> </div> </form> <!-- END REGISTRATION FORM --> </div> <!-- END LOGIN --> <!--[if lt IE 9]> <script src="../assets/global/plugins/respond.min.js"></script> <script src="../assets/global/plugins/excanvas.min.js"></script> <script src="../assets/global/plugins/ie8.fix.min.js"></script> <![endif]--> <!-- BEGIN CORE PLUGINS --> <script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN PAGE LEVEL PLUGINS --> <script src="../assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script> <script src="../assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN THEME GLOBAL SCRIPTS --> <script src="../assets/global/scripts/app.min.js" type="text/javascript"></script> <!-- END THEME GLOBAL SCRIPTS --> <!-- BEGIN PAGE LEVEL SCRIPTS --> <script src="../assets/pages/scripts/login.min.js" type="text/javascript"></script> <!-- END PAGE LEVEL SCRIPTS --> <!-- BEGIN THEME LAYOUT SCRIPTS --> <!-- END THEME LAYOUT SCRIPTS --> </body> </html>
FernandoUnix/AcessoRestrito
metronic_v4.7.1/theme_rtl/admin_5_rounded/page_user_login_3.html
HTML
gpl-3.0
28,572
<html> <head><title>download de dados</title></head> <body> <h3>Dados anuais por &oacute;rg&atilde;o</h3> <p><a href="2008/orgaos.json">2008</a></p> <p><a href="2009/orgaos.json">2009</a></p> <p><a href="2010/orgaos.json">2010</a></p> <p><a href="2011/orgaos.json">2011</a></p> <p><a href="2012/orgaos.json">2012</a></p> <p><a href="2013/orgaos.json">2013</a></p> </body> </html>
JeffsFernandes/cuidando2
projeto/projeto/static/data/index.html
HTML
gpl-3.0
380
// This file is part of Hermes2D. // // Hermes2D is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Hermes2D 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 Hermes2D. If not, see <http://www.gnu.org/licenses/>. #include "curved.h" #include <algorithm> #include "global.h" #include "shapeset/shapeset_h1_all.h" #include "shapeset/shapeset_common.h" #include "shapeset/precalc.h" #include "mesh.h" #include "quad_all.h" #include "matrix.h" #include "algebra/dense_matrix_operations.h" using namespace Hermes::Algebra::DenseMatrixOperations; namespace Hermes { namespace Hermes2D { HERMES_API Quad1DStd g_quad_1d_std; HERMES_API Quad2DStd g_quad_2d_std; H1ShapesetJacobi ref_map_shapeset; PrecalcShapesetAssembling ref_map_pss_static(&ref_map_shapeset); CurvMapStatic::CurvMapStatic() { int order = ref_map_shapeset.get_max_order(); this->edge_proj_matrix_size = order - 1; // Edges. this->edge_proj_matrix = new_matrix<double>(edge_proj_matrix_size, edge_proj_matrix_size); edge_p = malloc_with_check<double>(edge_proj_matrix_size); // Bubbles - triangles. this->tri_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_TRIANGLE); bubble_proj_matrix_tri = new_matrix<double>(tri_bubble_np, tri_bubble_np); bubble_tri_p = malloc_with_check<double>(tri_bubble_np); // Bubbles - quads. order = H2D_MAKE_QUAD_ORDER(order, order); this->quad_bubble_np = ref_map_shapeset.get_num_bubbles(order, HERMES_MODE_QUAD); bubble_proj_matrix_quad = new_matrix<double>(quad_bubble_np, quad_bubble_np); bubble_quad_p = malloc_with_check<double>(quad_bubble_np); this->precalculate_cholesky_projection_matrices_bubble(); this->precalculate_cholesky_projection_matrix_edge(); } CurvMapStatic::~CurvMapStatic() { free_with_check(edge_proj_matrix, true); free_with_check(bubble_proj_matrix_tri, true); free_with_check(bubble_proj_matrix_quad, true); free_with_check(edge_p); free_with_check(bubble_tri_p); free_with_check(bubble_quad_p); } double** CurvMapStatic::calculate_bubble_projection_matrix(short* indices, ElementMode2D mode) { unsigned short nb; double** mat; if (mode == HERMES_MODE_TRIANGLE) { mat = this->bubble_proj_matrix_tri; nb = this->tri_bubble_np; } else { mat = this->bubble_proj_matrix_quad; nb = this->quad_bubble_np; } PrecalcShapesetAssembling ref_map_pss_static_temp(&ref_map_shapeset); ref_map_pss_static_temp.set_active_element(ref_map_pss_static.get_active_element()); for (unsigned short i = 0; i < nb; i++) { for (unsigned short j = i; j < nb; j++) { short ii = indices[i], ij = indices[j]; unsigned short o = ref_map_shapeset.get_order(ii, mode) + ref_map_shapeset.get_order(ij, mode); o = std::max(H2D_GET_V_ORDER(o), H2D_GET_H_ORDER(o)); ref_map_pss_static.set_active_shape(ii); ref_map_pss_static.set_quad_order(o, H2D_FN_VAL); const double* fni = ref_map_pss_static.get_fn_values(); ref_map_pss_static_temp.set_active_shape(ij); ref_map_pss_static_temp.set_quad_order(o, H2D_FN_VAL); const double* fnj = ref_map_pss_static_temp.get_fn_values(); double3* pt = g_quad_2d_std.get_points(o, mode); double val = 0.0; for (unsigned short k = 0; k < g_quad_2d_std.get_num_points(o, mode); k++) val += pt[k][2] * (fni[k] * fnj[k]); mat[i][j] = mat[j][i] = val; } } return mat; } void CurvMapStatic::precalculate_cholesky_projection_matrices_bubble() { // *** triangles *** // calculate projection matrix of maximum order { Element e; e.nvert = 3; e.cm = nullptr; e.id = -1; ref_map_pss_static.set_active_element(&e); short* indices = ref_map_shapeset.get_bubble_indices(ref_map_shapeset.get_max_order(), HERMES_MODE_TRIANGLE); curvMapStatic.bubble_proj_matrix_tri = calculate_bubble_projection_matrix(indices, HERMES_MODE_TRIANGLE); // cholesky factorization of the matrix choldc(curvMapStatic.bubble_proj_matrix_tri, this->tri_bubble_np, curvMapStatic.bubble_tri_p); } // *** quads *** // calculate projection matrix of maximum order { Element e; e.nvert = 4; e.cm = nullptr; e.id = -1; ref_map_pss_static.set_active_element(&e); short *indices = ref_map_shapeset.get_bubble_indices(H2D_MAKE_QUAD_ORDER(ref_map_shapeset.get_max_order(), ref_map_shapeset.get_max_order()), HERMES_MODE_QUAD); curvMapStatic.bubble_proj_matrix_quad = calculate_bubble_projection_matrix(indices, HERMES_MODE_QUAD); // cholesky factorization of the matrix choldc(curvMapStatic.bubble_proj_matrix_quad, this->quad_bubble_np, curvMapStatic.bubble_quad_p); } } void CurvMapStatic::precalculate_cholesky_projection_matrix_edge() { // calculate projection matrix of maximum order for (int i = 0; i < this->edge_proj_matrix_size; i++) { for (int j = i; j < this->edge_proj_matrix_size; j++) { int o = i + j + 4; double2* pt = g_quad_1d_std.get_points(o); double val = 0.0; for (int k = 0; k < g_quad_1d_std.get_num_points(o); k++) { double fi = 0; double fj = 0; double x = pt[k][0]; switch (i + 2) { case 0: fi = l0(x); break; case 1: fi = l1(x); break; case 2: fi = l2(x); break; case 3: fi = l3(x); break; case 4: fi = l4(x); break; case 5: fi = l5(x); break; case 6: fi = l6(x); break; case 7: fi = l7(x); break; case 8: fi = l8(x); break; case 9: fi = l9(x); break; case 10: fi = l10(x); break; case 11: fi = l11(x); break; } switch (j + 2) { case 0: fj = l0(x); break; case 1: fj = l1(x); break; case 2: fj = l2(x); break; case 3: fj = l3(x); break; case 4: fj = l4(x); break; case 5: fj = l5(x); break; case 6: fj = l6(x); break; case 7: fj = l7(x); break; case 8: fj = l8(x); break; case 9: fj = l9(x); break; case 10: fj = l10(x); break; case 11: fj = l11(x); break; } val += pt[k][1] * (fi * fj); } this->edge_proj_matrix[i][j] = this->edge_proj_matrix[j][i] = val; } } // Cholesky factorization of the matrix choldc(this->edge_proj_matrix, this->edge_proj_matrix_size, this->edge_p); } CurvMapStatic curvMapStatic; Curve::Curve(CurvType type) : type(type) { } Curve::~Curve() { } Arc::Arc() : Curve(ArcType) { kv[0] = kv[1] = kv[2] = 0; kv[3] = kv[4] = kv[5] = 1; } Arc::Arc(double angle) : Curve(ArcType), angle(angle) { kv[0] = kv[1] = kv[2] = 0; kv[3] = kv[4] = kv[5] = 1; } Arc::Arc(const Arc* other) : Curve(ArcType) { this->angle = other->angle; memcpy(this->kv, other->kv, 6 * sizeof(double)); memcpy(this->pt, other->pt, 3 * sizeof(double3)); } Nurbs::Nurbs() : Curve(NurbsType) { pt = nullptr; kv = nullptr; }; Nurbs::~Nurbs() { free_with_check(pt); free_with_check(kv); }; Nurbs::Nurbs(const Nurbs* other) : Curve(NurbsType) { this->degree = other->degree; this->nk = other->nk; this->np = other->np; this->kv = malloc_with_check<double>(nk); this->pt = malloc_with_check<double3>(np); } static double lambda_0(double x, double y) { return -0.5 * (x + y); } static double lambda_1(double x, double y) { return 0.5 * (x + 1); } static double lambda_2(double x, double y) { return 0.5 * (y + 1); } CurvMap::CurvMap() : ref_map_pss(&ref_map_shapeset) { coeffs = nullptr; ctm = nullptr; memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES); this->parent = nullptr; this->sub_idx = 0; } CurvMap::CurvMap(const CurvMap* cm) : ref_map_pss(&ref_map_shapeset) { this->nc = cm->nc; this->order = cm->order; /// \todo Find out if this is safe. this->ctm = cm->ctm; this->coeffs = malloc_with_check<double2>(nc, true); memcpy(coeffs, cm->coeffs, sizeof(double2)* nc); this->toplevel = cm->toplevel; if (this->toplevel) { for (int i = 0; i < 4; i++) { if (cm->curves[i]) { if (cm->curves[i]->type == NurbsType) this->curves[i] = new Nurbs((Nurbs*)cm->curves[i]); else this->curves[i] = new Arc((Arc*)cm->curves[i]); } else this->curves[i] = nullptr; } this->parent = nullptr; this->sub_idx = 0; } else { memset(curves, 0, sizeof(Curve*)* H2D_MAX_NUMBER_EDGES); this->parent = cm->parent; this->sub_idx = cm->sub_idx; } } CurvMap::~CurvMap() { this->free(); } void CurvMap::free() { free_with_check(this->coeffs, true); if (toplevel) { for (int i = 0; i < 4; i++) if (curves[i]) { delete curves[i]; curves[i] = nullptr; } } } double CurvMap::nurbs_basis_fn(unsigned short i, unsigned short k, double t, double* knot) { if (k == 0) { return (t >= knot[i] && t <= knot[i + 1] && knot[i] < knot[i + 1]) ? 1.0 : 0.0; } else { double N1 = nurbs_basis_fn(i, k - 1, t, knot); double N2 = nurbs_basis_fn(i + 1, k - 1, t, knot); if ((N1 > HermesEpsilon) || (N2 > HermesEpsilon)) { double result = 0.0; if ((N1 > HermesEpsilon) && knot[i + k] != knot[i]) result += ((t - knot[i]) / (knot[i + k] - knot[i])) * N1; if ((N2 > HermesEpsilon) && knot[i + k + 1] != knot[i + 1]) result += ((knot[i + k + 1] - t) / (knot[i + k + 1] - knot[i + 1])) * N2; return result; } else return 0.0; } } void CurvMap::nurbs_edge(Element* e, Curve* curve, int edge, double t, double& x, double& y) { // Nurbs curves are parametrized from 0 to 1. t = (t + 1.0) / 2.0; // Start point A, end point B. double2 A = { e->vn[edge]->x, e->vn[edge]->y }; double2 B = { e->vn[e->next_vert(edge)]->x, e->vn[e->next_vert(edge)]->y }; // Vector pointing from A to B. double2 v = { B[0] - A[0], B[1] - A[1] }; // Straight line. if (!curve) { x = A[0] + t * v[0]; y = A[1] + t * v[1]; } else { double3* cp; int degree, np; double* kv; if (curve->type == ArcType) { cp = ((Arc*)curve)->pt; np = ((Arc*)curve)->np; degree = ((Arc*)curve)->degree; kv = ((Arc*)curve)->kv; } else { cp = ((Nurbs*)curve)->pt; np = ((Nurbs*)curve)->np; degree = ((Nurbs*)curve)->degree; kv = ((Nurbs*)curve)->kv; } // sum of basis fns and weights double sum = 0.0; x = y = 0.0; for (int i = 0; i < np; i++) { double basis = nurbs_basis_fn(i, degree, t, kv); sum += cp[i][2] * basis; double x_i = cp[i][0]; double y_i = cp[i][1]; double w_i = cp[i][2]; x += w_i * basis * x_i; y += w_i * basis * y_i; } x /= sum; y /= sum; } } const double2 CurvMap::ref_vert[2][H2D_MAX_NUMBER_VERTICES] = { { { -1.0, -1.0 }, { 1.0, -1.0 }, { -1.0, 1.0 }, { 0.0, 0.0 } }, { { -1.0, -1.0 }, { 1.0, -1.0 }, { 1.0, 1.0 }, { -1.0, 1.0 } } }; void CurvMap::nurbs_edge_0(Element* e, Curve* curve, unsigned short edge, double t, double& x, double& y, double& n_x, double& n_y, double& t_x, double& t_y) { unsigned short va = edge; unsigned short vb = e->next_vert(edge); nurbs_edge(e, curve, edge, t, x, y); x -= 0.5 * ((1 - t) * (e->vn[va]->x) + (1 + t) * (e->vn[vb]->x)); y -= 0.5 * ((1 - t) * (e->vn[va]->y) + (1 + t) * (e->vn[vb]->y)); double k = 4.0 / ((1 - t) * (1 + t)); x *= k; y *= k; } void CurvMap::calc_ref_map_tri(Element* e, Curve** curve, double xi_1, double xi_2, double& x, double& y) { double fx, fy; x = y = 0.0; double l[3] = { lambda_0(xi_1, xi_2), lambda_1(xi_1, xi_2), lambda_2(xi_1, xi_2) }; for (unsigned char j = 0; j < e->get_nvert(); j++) { int va = j; int vb = e->next_vert(j); double la = l[va]; double lb = l[vb]; // vertex part x += e->vn[j]->x * la; y += e->vn[j]->y * la; if (!(((ref_vert[0][va][0] == xi_1) && (ref_vert[0][va][1] == xi_2)) || ((ref_vert[0][vb][0] == xi_1) && (ref_vert[0][vb][1] == xi_2)))) { // edge part double t = lb - la; double n_x, n_y, t_x, t_y; nurbs_edge_0(e, curve[j], j, t, fx, fy, n_x, n_y, t_x, t_y); x += fx * lb * la; y += fy * lb * la; } } } void CurvMap::calc_ref_map_quad(Element* e, Curve** curve, double xi_1, double xi_2, double& x, double& y) { double ex[H2D_MAX_NUMBER_EDGES], ey[H2D_MAX_NUMBER_EDGES]; nurbs_edge(e, curve[0], 0, xi_1, ex[0], ey[0]); nurbs_edge(e, curve[1], 1, xi_2, ex[1], ey[1]); nurbs_edge(e, curve[2], 2, -xi_1, ex[2], ey[2]); nurbs_edge(e, curve[3], 3, -xi_2, ex[3], ey[3]); x = (1 - xi_2) / 2.0 * ex[0] + (1 + xi_1) / 2.0 * ex[1] + (1 + xi_2) / 2.0 * ex[2] + (1 - xi_1) / 2.0 * ex[3] - (1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->x - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->x - (1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->x - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->x; y = (1 - xi_2) / 2.0 * ey[0] + (1 + xi_1) / 2.0 * ey[1] + (1 + xi_2) / 2.0 * ey[2] + (1 - xi_1) / 2.0 * ey[3] - (1 - xi_1)*(1 - xi_2) / 4.0 * e->vn[0]->y - (1 + xi_1)*(1 - xi_2) / 4.0 * e->vn[1]->y - (1 + xi_1)*(1 + xi_2) / 4.0 * e->vn[2]->y - (1 - xi_1)*(1 + xi_2) / 4.0 * e->vn[3]->y; } void CurvMap::calc_ref_map(Element* e, Curve** curve, double xi_1, double xi_2, double2& f) { if (e->get_mode() == HERMES_MODE_QUAD) calc_ref_map_quad(e, curve, xi_1, xi_2, f[0], f[1]); else calc_ref_map_tri(e, curve, xi_1, xi_2, f[0], f[1]); } void CurvMap::edge_coord(Element* e, unsigned short edge, double t, double2& x) const { unsigned short mode = e->get_mode(); double2 a, b; a[0] = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0]; a[1] = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1]; b[0] = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0]; b[1] = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1]; for (int i = 0; i < 2; i++) { x[i] = a[i] + (t + 1.0) / 2.0 * (b[i] - a[i]); } } void CurvMap::calc_edge_projection(Element* e, unsigned short edge, Curve** nurbs, unsigned short order, double2* proj) const { unsigned short i, j, k; unsigned short mo1 = g_quad_1d_std.get_max_order(); unsigned char np = g_quad_1d_std.get_num_points(mo1); unsigned short ne = order - 1; unsigned short mode = e->get_mode(); assert(np <= 15 && ne <= 10); double2 fn[15]; double rhside[2][10]; memset(rhside[0], 0, sizeof(double)* ne); memset(rhside[1], 0, sizeof(double)* ne); double a_1, a_2, b_1, b_2; a_1 = ctm->m[0] * ref_vert[mode][edge][0] + ctm->t[0]; a_2 = ctm->m[1] * ref_vert[mode][edge][1] + ctm->t[1]; b_1 = ctm->m[0] * ref_vert[mode][e->next_vert(edge)][0] + ctm->t[0]; b_2 = ctm->m[1] * ref_vert[mode][e->next_vert(edge)][1] + ctm->t[1]; // values of nonpolynomial function in two vertices double2 fa, fb; calc_ref_map(e, nurbs, a_1, a_2, fa); calc_ref_map(e, nurbs, b_1, b_2, fb); double2* pt = g_quad_1d_std.get_points(mo1); // over all integration points for (j = 0; j < np; j++) { double2 x; double t = pt[j][0]; edge_coord(e, edge, t, x); calc_ref_map(e, nurbs, x[0], x[1], fn[j]); for (k = 0; k < 2; k++) fn[j][k] = fn[j][k] - (fa[k] + (t + 1) / 2.0 * (fb[k] - fa[k])); } double2* result = proj + e->get_nvert() + edge * (order - 1); for (k = 0; k < 2; k++) { for (i = 0; i < ne; i++) { for (j = 0; j < np; j++) { double t = pt[j][0]; double fi = 0; switch (i + 2) { case 0: fi = l0(t); break; case 1: fi = l1(t); break; case 2: fi = l2(t); break; case 3: fi = l3(t); break; case 4: fi = l4(t); break; case 5: fi = l5(t); break; case 6: fi = l6(t); break; case 7: fi = l7(t); break; case 8: fi = l8(t); break; case 9: fi = l9(t); break; case 10: fi = l10(t); break; case 11: fi = l11(t); break; } rhside[k][i] += pt[j][1] * (fi * fn[j][k]); } } // solve cholsl(curvMapStatic.edge_proj_matrix, ne, curvMapStatic.edge_p, rhside[k], rhside[k]); for (i = 0; i < ne; i++) result[i][k] = rhside[k][i]; } } void CurvMap::old_projection(Element* e, unsigned short order, double2* proj, double* old[2]) { unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode()); unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode()); unsigned short nvert = e->get_nvert(); for (unsigned int k = 0; k < nvert; k++) // loop over vertices { // vertex basis functions in all integration points int index_v = ref_map_shapeset.get_vertex_index(k, e->get_mode()); ref_map_pss.set_active_shape(index_v); ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0); const double* vd = ref_map_pss.get_fn_values(); for (int m = 0; m < 2; m++) // part 0 or 1 for (int j = 0; j < np; j++) old[m][j] += proj[k][m] * vd[j]; for (int ii = 0; ii < order - 1; ii++) { // edge basis functions in all integration points int index_e = ref_map_shapeset.get_edge_index(k, 0, ii + 2, e->get_mode()); ref_map_pss.set_active_shape(index_e); ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0); const double* ed = ref_map_pss.get_fn_values(); for (int m = 0; m < 2; m++) //part 0 or 1 for (int j = 0; j < np; j++) old[m][j] += proj[nvert + k * (order - 1) + ii][m] * ed[j]; } } } void CurvMap::calc_bubble_projection(Element* e, Curve** curve, unsigned short order, double2* proj) { ref_map_pss.set_active_element(e); unsigned short i, j, k; unsigned short mo2 = g_quad_2d_std.get_max_order(e->get_mode()); unsigned char np = g_quad_2d_std.get_num_points(mo2, e->get_mode()); unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order; unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode()); double2* fn = new double2[np]; memset(fn, 0, np * sizeof(double2)); double* rhside[2]; double* old[2]; for (i = 0; i < 2; i++) { rhside[i] = new double[nb]; old[i] = new double[np]; memset(rhside[i], 0, sizeof(double)* nb); memset(old[i], 0, sizeof(double)* np); } // compute known part of projection (vertex and edge part) old_projection(e, order, proj, old); // fn values of both components of nonpolynomial function double3* pt = g_quad_2d_std.get_points(mo2, e->get_mode()); for (j = 0; j < np; j++) // over all integration points { double2 a; a[0] = ctm->m[0] * pt[j][0] + ctm->t[0]; a[1] = ctm->m[1] * pt[j][1] + ctm->t[1]; calc_ref_map(e, curve, a[0], a[1], fn[j]); } double2* result = proj + e->get_nvert() + e->get_nvert() * (order - 1); for (k = 0; k < 2; k++) { for (i = 0; i < nb; i++) // loop over bubble basis functions { // bubble basis functions in all integration points int index_i = ref_map_shapeset.get_bubble_indices(qo, e->get_mode())[i]; ref_map_pss.set_active_shape(index_i); ref_map_pss.set_quad_order(mo2, H2D_FN_VAL_0); const double *bfn = ref_map_pss.get_fn_values(); for (j = 0; j < np; j++) // over all integration points rhside[k][i] += pt[j][2] * (bfn[j] * (fn[j][k] - old[k][j])); } // solve if (e->get_mode() == HERMES_MODE_TRIANGLE) cholsl(curvMapStatic.bubble_proj_matrix_tri, nb, curvMapStatic.bubble_tri_p, rhside[k], rhside[k]); else cholsl(curvMapStatic.bubble_proj_matrix_quad, nb, curvMapStatic.bubble_quad_p, rhside[k], rhside[k]); for (i = 0; i < nb; i++) result[i][k] = rhside[k][i]; } for (i = 0; i < 2; i++) { delete[] rhside[i]; delete[] old[i]; } delete[] fn; } void CurvMap::update_refmap_coeffs(Element* e) { ref_map_pss.set_quad_2d(&g_quad_2d_std); ref_map_pss.set_active_element(e); // allocate projection coefficients unsigned char nvert = e->get_nvert(); unsigned char ne = order - 1; unsigned short qo = e->is_quad() ? H2D_MAKE_QUAD_ORDER(order, order) : order; unsigned short nb = ref_map_shapeset.get_num_bubbles(qo, e->get_mode()); this->nc = nvert + nvert*ne + nb; this->coeffs = realloc_with_check<double2>(this->coeffs, nc); // WARNING: do not change the format of the array 'coeffs'. If it changes, // RefMap::set_active_element() has to be changed too. Curve** curves; if (toplevel == false) { ref_map_pss.set_active_element(e); ref_map_pss.set_transform(this->sub_idx); curves = parent->cm->curves; } else { ref_map_pss.reset_transform(); curves = e->cm->curves; } ctm = ref_map_pss.get_ctm(); // calculation of new_ projection coefficients // vertex part for (unsigned char i = 0; i < nvert; i++) { coeffs[i][0] = e->vn[i]->x; coeffs[i][1] = e->vn[i]->y; } if (!e->cm->toplevel) e = e->cm->parent; // edge part for (unsigned char edge = 0; edge < nvert; edge++) calc_edge_projection(e, edge, curves, order, coeffs); //bubble part calc_bubble_projection(e, curves, order, coeffs); } void CurvMap::get_mid_edge_points(Element* e, double2* pt, unsigned short n) { Curve** curves = this->curves; Transformable tran; tran.set_active_element(e); if (toplevel == false) { tran.set_transform(this->sub_idx); e = e->cm->parent; curves = e->cm->curves; } ctm = tran.get_ctm(); double xi_1, xi_2; for (unsigned short i = 0; i < n; i++) { xi_1 = ctm->m[0] * pt[i][0] + ctm->t[0]; xi_2 = ctm->m[1] * pt[i][1] + ctm->t[1]; calc_ref_map(e, curves, xi_1, xi_2, pt[i]); } } CurvMap* CurvMap::create_son_curv_map(Element* e, int son) { // if the top three bits of part are nonzero, we would overflow // -- make the element non-curvilinear if (e->cm->sub_idx & 0xe000000000000000ULL) return nullptr; // if the parent element is already almost straight-edged, // the son will be even more straight-edged if (e->iro_cache == 0) return nullptr; CurvMap* cm = new CurvMap; if (e->cm->toplevel == false) { cm->parent = e->cm->parent; cm->sub_idx = (e->cm->sub_idx << 3) + son + 1; } else { cm->parent = e; cm->sub_idx = (son + 1); } cm->toplevel = false; cm->order = 4; return cm; } } }
filipr/hermes
hermes2d/src/mesh/curved.cpp
C++
gpl-3.0
26,263
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. namespace Microsoft.Xna.Framework.Content.Pipeline.Graphics { /// <summary> /// Provides properties for managing a bone weight. /// </summary> public struct BoneWeight { string boneName; float weight; /// <summary> /// Gets the name of the bone. /// </summary> public string BoneName { get { return boneName; } } /// <summary> /// Gets the amount of bone influence, ranging from zero to one. The complete set of weights in a BoneWeightCollection should sum to one. /// </summary> public float Weight { get { return weight; } internal set { weight = value; } } /// <summary> /// Initializes a new instance of BoneWeight with the specified name and weight. /// </summary> /// <param name="boneName">Name of the bone.</param> /// <param name="weight">Amount of influence, ranging from zero to one.</param> public BoneWeight(string boneName, float weight) { this.boneName = boneName; this.weight = weight; } } }
Blucky87/Otiose2D
src/libs/MonoGame/MonoGame.Framework.Content.Pipeline/Graphics/BoneWeight.cs
C#
gpl-3.0
1,470
<!--! This file is a part of MediaDrop (http://www.mediadrop.net), Copyright 2009-2014 MediaDrop contributors For the exact contribution history, see the git revision log. The source code contained in this file is licensed under the GPLv3 or (at your option) any later version. See LICENSE.txt in the main project directory, for more information. --> <form xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" id="${id}" name="${name}" action="${action}" method="${method}" class="${css_class}" py:attrs="attrs"> <xi:include href="../helpers.html" /> <span py:if="error and not error.error_dict" class="field-error" py:content="error" /> <table class="field-list" py:attrs="list_attrs"> <tbody> <py:for each="i, field in enumerate(fields)" py:with="required = field.is_required and ' required' or None; help_url = getattr(field, 'help_url', None); is_submit = getattr(field, 'type', None) == 'submit'; render_label = show_labels and not field.suppress_label; render_error = error is not None and not field.show_error;"> <tr py:if="field.name == 'url'"> <td> <br /> <div class="field-error" py:if="'_the_form' in tmpl_context.form_errors" py:content="tmpl_context.form_errors['_the_form']"> Display the error from the media controller, if any </div> </td> </tr> <tr class="title" py:if="render_label and not (is_submit or field.show_error)"> <td> <label py:if="render_label" py:content="field.label_text and _(field.label_text) or None" id="${field.id}-label" class="form-label" for="${field.id}" /> <a py:if="field.help_text and help_url" py:content="field.help_text and _(field.help_text) or None" href="${help_url}" class="field-help" /> <span py:if="field.help_text and not help_url" py:content="field.help_text and _(field.help_text) or None" class="field-help" /> <span py:if="not field.show_error" class="field-error" py:content="error_for(field)" /> </td> </tr> <tr> <td class="${render_error and (error_for(field) is not None and 'err' or 'noerr') or ''}"> ${field.display(value_for(field), **args_for(field))} <!-- The following 4 elements are used only by the SwiffUploadManager javascript --> <div py:if="field.name == 'file'" id="bottombar"> <button id="browse-button" class="mcore-btn f-lft"><span>Choose a file to upload</span></button> <div id="file-info" class="f-lft" /> </div> </td> </tr> <tr py:if="field.name == 'description'" class="${field.name}-rel"> <td py:content="xhtml_description('description')" /> </tr> </py:for> </tbody> </table> </form>
kgao/MediaDrop
mediadrop/templates/upload/form.html
HTML
gpl-3.0
2,865
using WowPacketParser.Enums; using WowPacketParser.Hotfix; namespace WowPacketParserModule.V8_0_1_27101.Hotfix { [HotfixStructure(DB2Hash.WorldEffect, HasIndexInData = false)] public class WorldEffectEntry { public uint QuestFeedbackEffectID { get; set; } public byte WhenToDisplay { get; set; } public sbyte TargetType { get; set; } public int TargetAsset { get; set; } public uint PlayerConditionID { get; set; } public ushort CombatConditionID { get; set; } } }
TrinityCore/WowPacketParser
WowPacketParserModule.V8_0_1_27101/Hotfix/WorldEffectEntry.cs
C#
gpl-3.0
530
<?php /** * ObjectManager config with interception processing * * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Interception\ObjectManager\Config; use Magento\Framework\Interception\ObjectManager\ConfigInterface; use Magento\Framework\ObjectManager\DefinitionInterface; use Magento\Framework\ObjectManager\RelationsInterface; use Magento\Framework\ObjectManager\InterceptableValidator; class Developer extends \Magento\Framework\ObjectManager\Config\Config implements ConfigInterface { /** * @var InterceptableValidator */ private $interceptableValidator; /** * @param RelationsInterface $relations * @param DefinitionInterface $definitions * @param InterceptableValidator $interceptableValidator */ public function __construct( RelationsInterface $relations = null, DefinitionInterface $definitions = null, InterceptableValidator $interceptableValidator = null ) { $this->interceptableValidator = $interceptableValidator ?: new InterceptableValidator(); parent::__construct($relations, $definitions); } /** * @var \Magento\Framework\Interception\ConfigInterface */ protected $interceptionConfig; /** * Set Interception config * * @param \Magento\Framework\Interception\ConfigInterface $interceptionConfig * @return void */ public function setInterceptionConfig(\Magento\Framework\Interception\ConfigInterface $interceptionConfig) { $this->interceptionConfig = $interceptionConfig; } /** * Retrieve instance type with interception processing * * @param string $instanceName * @return string */ public function getInstanceType($instanceName) { $type = parent::getInstanceType($instanceName); if ($this->interceptionConfig && $this->interceptionConfig->hasPlugins($instanceName) && $this->interceptableValidator->validate($instanceName) ) { return $type . '\\Interceptor'; } return $type; } /** * Retrieve instance type without interception processing * * @param string $instanceName * @return string */ public function getOriginalInstanceType($instanceName) { return parent::getInstanceType($instanceName); } }
rajmahesh/magento2-master
vendor/magento/framework/Interception/ObjectManager/Config/Developer.php
PHP
gpl-3.0
2,409
<?php namespace TYPO3\Neos\Routing; /* * This file is part of the TYPO3.Neos 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\Annotations as Flow; /** * A route part handler for finding nodes specifically in the website's frontend. * * @Flow\Scope("singleton") */ class BackendModuleArgumentsRoutePartHandler extends \TYPO3\Flow\Mvc\Routing\DynamicRoutePart { /** * @Flow\Inject * @var \TYPO3\Flow\Persistence\PersistenceManagerInterface */ protected $persistenceManager; /** * Iterate through the configured modules, find the matching module and set * the route path accordingly * * @param array $value (contains action, controller and package of the module controller) * @return boolean */ protected function resolveValue($value) { if (is_array($value)) { $this->value = isset($value['@action']) && $value['@action'] !== 'index' ? $value['@action'] : ''; if ($this->value !== '' && isset($value['@format'])) { $this->value .= '.' . $value['@format']; } $exceedingArguments = array(); foreach ($value as $argumentKey => $argumentValue) { if (substr($argumentKey, 0, 1) !== '@' && substr($argumentKey, 0, 2) !== '__') { $exceedingArguments[$argumentKey] = $argumentValue; } } if ($exceedingArguments !== array()) { $exceedingArguments = \TYPO3\Flow\Utility\Arrays::removeEmptyElementsRecursively($exceedingArguments); $exceedingArguments = $this->persistenceManager->convertObjectsToIdentityArrays($exceedingArguments); $queryString = http_build_query(array($this->name => $exceedingArguments), null, '&'); if ($queryString !== '') { $this->value .= '?' . $queryString; } } } return true; } }
dimaip/neos-development-collection
TYPO3.Neos/Classes/TYPO3/Neos/Routing/BackendModuleArgumentsRoutePartHandler.php
PHP
gpl-3.0
2,168
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "meshSearch.H" #include "polyMesh.H" #include "indexedOctree.H" #include "DynamicList.H" #include "demandDrivenData.H" #include "treeDataCell.H" #include "treeDataFace.H" #include "treeDataPoint.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // defineTypeNameAndDebug(Foam::meshSearch, 0); Foam::scalar Foam::meshSearch::tol_ = 1E-3; // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // bool Foam::meshSearch::findNearer ( const point& sample, const pointField& points, label& nearestI, scalar& nearestDistSqr ) { bool nearer = false; forAll(points, pointI) { scalar distSqr = magSqr(points[pointI] - sample); if (distSqr < nearestDistSqr) { nearestDistSqr = distSqr; nearestI = pointI; nearer = true; } } return nearer; } bool Foam::meshSearch::findNearer ( const point& sample, const pointField& points, const labelList& indices, label& nearestI, scalar& nearestDistSqr ) { bool nearer = false; forAll(indices, i) { label pointI = indices[i]; scalar distSqr = magSqr(points[pointI] - sample); if (distSqr < nearestDistSqr) { nearestDistSqr = distSqr; nearestI = pointI; nearer = true; } } return nearer; } // tree based searching Foam::label Foam::meshSearch::findNearestCellTree(const point& location) const { const indexedOctree<treeDataPoint>& tree = cellCentreTree(); scalar span = tree.bb().mag(); pointIndexHit info = tree.findNearest(location, Foam::sqr(span)); if (!info.hit()) { info = tree.findNearest(location, Foam::sqr(GREAT)); } return info.index(); } // linear searching Foam::label Foam::meshSearch::findNearestCellLinear(const point& location) const { const vectorField& centres = mesh_.cellCentres(); label nearestIndex = 0; scalar minProximity = magSqr(centres[nearestIndex] - location); findNearer ( location, centres, nearestIndex, minProximity ); return nearestIndex; } // walking from seed Foam::label Foam::meshSearch::findNearestCellWalk ( const point& location, const label seedCellI ) const { if (seedCellI < 0) { FatalErrorIn ( "meshSearch::findNearestCellWalk(const point&, const label)" ) << "illegal seedCell:" << seedCellI << exit(FatalError); } // Walk in direction of face that decreases distance label curCellI = seedCellI; scalar distanceSqr = magSqr(mesh_.cellCentres()[curCellI] - location); bool closer; do { // Try neighbours of curCellI closer = findNearer ( location, mesh_.cellCentres(), mesh_.cellCells()[curCellI], curCellI, distanceSqr ); } while (closer); return curCellI; } // tree based searching Foam::label Foam::meshSearch::findNearestFaceTree(const point& location) const { // Search nearest cell centre. const indexedOctree<treeDataPoint>& tree = cellCentreTree(); scalar span = tree.bb().mag(); // Search with decent span pointIndexHit info = tree.findNearest(location, Foam::sqr(span)); if (!info.hit()) { // Search with desparate span info = tree.findNearest(location, Foam::sqr(GREAT)); } // Now check any of the faces of the nearest cell const vectorField& centres = mesh_.faceCentres(); const cell& ownFaces = mesh_.cells()[info.index()]; label nearestFaceI = ownFaces[0]; scalar minProximity = magSqr(centres[nearestFaceI] - location); findNearer ( location, centres, ownFaces, nearestFaceI, minProximity ); return nearestFaceI; } // linear searching Foam::label Foam::meshSearch::findNearestFaceLinear(const point& location) const { const vectorField& centres = mesh_.faceCentres(); label nearestFaceI = 0; scalar minProximity = magSqr(centres[nearestFaceI] - location); findNearer ( location, centres, nearestFaceI, minProximity ); return nearestFaceI; } // walking from seed Foam::label Foam::meshSearch::findNearestFaceWalk ( const point& location, const label seedFaceI ) const { if (seedFaceI < 0) { FatalErrorIn ( "meshSearch::findNearestFaceWalk(const point&, const label)" ) << "illegal seedFace:" << seedFaceI << exit(FatalError); } const vectorField& centres = mesh_.faceCentres(); // Walk in direction of face that decreases distance label curFaceI = seedFaceI; scalar distanceSqr = magSqr(centres[curFaceI] - location); while (true) { label betterFaceI = curFaceI; findNearer ( location, centres, mesh_.cells()[mesh_.faceOwner()[curFaceI]], betterFaceI, distanceSqr ); if (mesh_.isInternalFace(curFaceI)) { findNearer ( location, centres, mesh_.cells()[mesh_.faceNeighbour()[curFaceI]], betterFaceI, distanceSqr ); } if (betterFaceI == curFaceI) { break; } curFaceI = betterFaceI; } return curFaceI; } Foam::label Foam::meshSearch::findCellLinear(const point& location) const { bool cellFound = false; label n = 0; label cellI = -1; while ((!cellFound) && (n < mesh_.nCells())) { if (pointInCell(location, n)) { cellFound = true; cellI = n; } else { n++; } } if (cellFound) { return cellI; } else { return -1; } } Foam::label Foam::meshSearch::findNearestBoundaryFaceWalk ( const point& location, const label seedFaceI ) const { if (seedFaceI < 0) { FatalErrorIn ( "meshSearch::findNearestBoundaryFaceWalk" "(const point&, const label)" ) << "illegal seedFace:" << seedFaceI << exit(FatalError); } // Start off from seedFaceI label curFaceI = seedFaceI; const face& f = mesh_.faces()[curFaceI]; scalar minDist = f.nearestPoint ( location, mesh_.points() ).distance(); bool closer; do { closer = false; // Search through all neighbouring boundary faces by going // across edges label lastFaceI = curFaceI; const labelList& myEdges = mesh_.faceEdges()[curFaceI]; forAll (myEdges, myEdgeI) { const labelList& neighbours = mesh_.edgeFaces()[myEdges[myEdgeI]]; // Check any face which uses edge, is boundary face and // is not curFaceI itself. forAll(neighbours, nI) { label faceI = neighbours[nI]; if ( (faceI >= mesh_.nInternalFaces()) && (faceI != lastFaceI) ) { const face& f = mesh_.faces()[faceI]; pointHit curHit = f.nearestPoint ( location, mesh_.points() ); // If the face is closer, reset current face and distance if (curHit.distance() < minDist) { minDist = curHit.distance(); curFaceI = faceI; closer = true; // a closer neighbour has been found } } } } } while (closer); return curFaceI; } Foam::vector Foam::meshSearch::offset ( const point& bPoint, const label bFaceI, const vector& dir ) const { // Get the neighbouring cell label ownerCellI = mesh_.faceOwner()[bFaceI]; const point& c = mesh_.cellCentres()[ownerCellI]; // Typical dimension: distance from point on face to cell centre scalar typDim = mag(c - bPoint); return tol_*typDim*dir; } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Construct from components Foam::meshSearch::meshSearch(const polyMesh& mesh, const bool faceDecomp) : mesh_(mesh), faceDecomp_(faceDecomp), cloud_(mesh_, IDLList<passiveParticle>()), boundaryTreePtr_(NULL), cellTreePtr_(NULL), cellCentreTreePtr_(NULL) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // Foam::meshSearch::~meshSearch() { clearOut(); } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // const Foam::indexedOctree<Foam::treeDataFace>& Foam::meshSearch::boundaryTree() const { if (!boundaryTreePtr_) { // // Construct tree // // all boundary faces (not just walls) labelList bndFaces(mesh_.nFaces()-mesh_.nInternalFaces()); forAll(bndFaces, i) { bndFaces[i] = mesh_.nInternalFaces() + i; } treeBoundBox overallBb(mesh_.points()); Random rndGen(123456); overallBb = overallBb.extend(rndGen, 1E-4); overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); boundaryTreePtr_ = new indexedOctree<treeDataFace> ( treeDataFace // all information needed to search faces ( false, // do not cache bb mesh_, bndFaces // boundary faces only ), overallBb, // overall search domain 8, // maxLevel 10, // leafsize 3.0 // duplicity ); } return *boundaryTreePtr_; } const Foam::indexedOctree<Foam::treeDataCell>& Foam::meshSearch::cellTree() const { if (!cellTreePtr_) { // // Construct tree // treeBoundBox overallBb(mesh_.points()); Random rndGen(123456); overallBb = overallBb.extend(rndGen, 1E-4); overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); cellTreePtr_ = new indexedOctree<treeDataCell> ( treeDataCell ( false, // not cache bb mesh_ ), overallBb, // overall search domain 8, // maxLevel 10, // leafsize 3.0 // duplicity ); } return *cellTreePtr_; } const Foam::indexedOctree<Foam::treeDataPoint>& Foam::meshSearch::cellCentreTree() const { if (!cellCentreTreePtr_) { // // Construct tree // treeBoundBox overallBb(mesh_.cellCentres()); Random rndGen(123456); overallBb = overallBb.extend(rndGen, 1E-4); overallBb.min() -= point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); overallBb.max() += point(ROOTVSMALL, ROOTVSMALL, ROOTVSMALL); cellCentreTreePtr_ = new indexedOctree<treeDataPoint> ( treeDataPoint(mesh_.cellCentres()), overallBb, // overall search domain 10, // max levels 10.0, // maximum ratio of cubes v.s. cells 100.0 // max. duplicity; n/a since no bounding boxes. ); } return *cellCentreTreePtr_; } // Is the point in the cell // Works by checking if there is a face inbetween the point and the cell // centre. // Check for internal uses proper face decomposition or just average normal. bool Foam::meshSearch::pointInCell(const point& p, label cellI) const { if (faceDecomp_) { const point& ctr = mesh_.cellCentres()[cellI]; vector dir(p - ctr); scalar magDir = mag(dir); // Check if any faces are hit by ray from cell centre to p. // If none -> p is in cell. const labelList& cFaces = mesh_.cells()[cellI]; // Make sure half_ray does not pick up any faces on the wrong // side of the ray. scalar oldTol = intersection::setPlanarTol(0.0); forAll(cFaces, i) { label faceI = cFaces[i]; pointHit inter = mesh_.faces()[faceI].ray ( ctr, dir, mesh_.points(), intersection::HALF_RAY, intersection::VECTOR ); if (inter.hit()) { scalar dist = inter.distance(); if (dist < magDir) { // Valid hit. Hit face so point is not in cell. intersection::setPlanarTol(oldTol); return false; } } } intersection::setPlanarTol(oldTol); // No face inbetween point and cell centre so point is inside. return true; } else { const labelList& f = mesh_.cells()[cellI]; const labelList& owner = mesh_.faceOwner(); const vectorField& cf = mesh_.faceCentres(); const vectorField& Sf = mesh_.faceAreas(); forAll(f, facei) { label nFace = f[facei]; vector proj = p - cf[nFace]; vector normal = Sf[nFace]; if (owner[nFace] == cellI) { if ((normal & proj) > 0) { return false; } } else { if ((normal & proj) < 0) { return false; } } } return true; } } Foam::label Foam::meshSearch::findNearestCell ( const point& location, const label seedCellI, const bool useTreeSearch ) const { if (seedCellI == -1) { if (useTreeSearch) { return findNearestCellTree(location); } else { return findNearestCellLinear(location); } } else { return findNearestCellWalk(location, seedCellI); } } Foam::label Foam::meshSearch::findNearestFace ( const point& location, const label seedFaceI, const bool useTreeSearch ) const { if (seedFaceI == -1) { if (useTreeSearch) { return findNearestFaceTree(location); } else { return findNearestFaceLinear(location); } } else { return findNearestFaceWalk(location, seedFaceI); } } Foam::label Foam::meshSearch::findCell ( const point& location, const label seedCellI, const bool useTreeSearch ) const { // Find the nearest cell centre to this location label nearCellI = findNearestCell(location, seedCellI, useTreeSearch); if (debug) { Pout<< "findCell : nearCellI:" << nearCellI << " ctr:" << mesh_.cellCentres()[nearCellI] << endl; } if (pointInCell(location, nearCellI)) { return nearCellI; } else { if (useTreeSearch) { // Start searching from cell centre of nearCell point curPoint = mesh_.cellCentres()[nearCellI]; vector edgeVec = location - curPoint; edgeVec /= mag(edgeVec); do { // Walk neighbours (using tracking) to get closer passiveParticle tracker(cloud_, curPoint, nearCellI); if (debug) { Pout<< "findCell : tracked from curPoint:" << curPoint << " nearCellI:" << nearCellI; } tracker.track(location); if (debug) { Pout<< " to " << tracker.position() << " need:" << location << " onB:" << tracker.onBoundary() << " cell:" << tracker.cell() << " face:" << tracker.face() << endl; } if (!tracker.onBoundary()) { // stopped not on boundary -> reached location return tracker.cell(); } // stopped on boundary face. Compare positions scalar typDim = sqrt(mag(mesh_.faceAreas()[tracker.face()])); if ((mag(tracker.position() - location)/typDim) < SMALL) { return tracker.cell(); } // tracking stopped at boundary. Find next boundary // intersection from current point (shifted out a little bit) // in the direction of the destination curPoint = tracker.position() + offset(tracker.position(), tracker.face(), edgeVec); if (debug) { Pout<< "Searching for next boundary from curPoint:" << curPoint << " to location:" << location << endl; } pointIndexHit curHit = intersection(curPoint, location); if (debug) { Pout<< "Returned from line search with "; curHit.write(Pout); Pout<< endl; } if (!curHit.hit()) { return -1; } else { nearCellI = mesh_.faceOwner()[curHit.index()]; curPoint = curHit.hitPoint() + offset(curHit.hitPoint(), curHit.index(), edgeVec); } } while(true); } else { return findCellLinear(location); } } return -1; } Foam::label Foam::meshSearch::findNearestBoundaryFace ( const point& location, const label seedFaceI, const bool useTreeSearch ) const { if (seedFaceI == -1) { if (useTreeSearch) { const indexedOctree<treeDataFace>& tree = boundaryTree(); scalar span = tree.bb().mag(); pointIndexHit info = boundaryTree().findNearest ( location, Foam::sqr(span) ); if (!info.hit()) { info = boundaryTree().findNearest ( location, Foam::sqr(GREAT) ); } return tree.shapes().faceLabels()[info.index()]; } else { scalar minDist = GREAT; label minFaceI = -1; for ( label faceI = mesh_.nInternalFaces(); faceI < mesh_.nFaces(); faceI++ ) { const face& f = mesh_.faces()[faceI]; pointHit curHit = f.nearestPoint ( location, mesh_.points() ); if (curHit.distance() < minDist) { minDist = curHit.distance(); minFaceI = faceI; } } return minFaceI; } } else { return findNearestBoundaryFaceWalk(location, seedFaceI); } } Foam::pointIndexHit Foam::meshSearch::intersection ( const point& pStart, const point& pEnd ) const { pointIndexHit curHit = boundaryTree().findLine(pStart, pEnd); if (curHit.hit()) { // Change index into octreeData into face label curHit.setIndex(boundaryTree().shapes().faceLabels()[curHit.index()]); } return curHit; } Foam::List<Foam::pointIndexHit> Foam::meshSearch::intersections ( const point& pStart, const point& pEnd ) const { DynamicList<pointIndexHit> hits; vector edgeVec = pEnd - pStart; edgeVec /= mag(edgeVec); point pt = pStart; pointIndexHit bHit; do { bHit = intersection(pt, pEnd); if (bHit.hit()) { hits.append(bHit); const vector& area = mesh_.faceAreas()[bHit.index()]; scalar typDim = Foam::sqrt(mag(area)); if ((mag(bHit.hitPoint() - pEnd)/typDim) < SMALL) { break; } // Restart from hitPoint shifted a little bit in the direction // of the destination pt = bHit.hitPoint() + offset(bHit.hitPoint(), bHit.index(), edgeVec); } } while(bHit.hit()); hits.shrink(); return hits; } bool Foam::meshSearch::isInside(const point& p) const { return boundaryTree().getVolumeType(p) == indexedOctree<treeDataFace>::INSIDE; } // Delete all storage void Foam::meshSearch::clearOut() { deleteDemandDrivenData(boundaryTreePtr_); deleteDemandDrivenData(cellTreePtr_); deleteDemandDrivenData(cellCentreTreePtr_); } void Foam::meshSearch::correct() { clearOut(); } // ************************************************************************* //
OpenCFD/OpenFOAM-1.7.x
src/meshTools/meshSearch/meshSearch.C
C++
gpl-3.0
22,990
#include "simulation/Elements.h" //#TPT-Directive ElementClass Element_FRZZ PT_FRZZ 100 Element_FRZZ::Element_FRZZ() { Identifier = "DEFAULT_PT_FRZZ"; Name = "FRZZ"; Colour = PIXPACK(0xC0E0FF); MenuVisible = 1; MenuSection = SC_POWDERS; Enabled = 1; Advection = 0.7f; AirDrag = 0.01f * CFDS; AirLoss = 0.96f; Loss = 0.90f; Collision = -0.1f; Gravity = 0.05f; Diffusion = 0.01f; HotAir = -0.00005f* CFDS; Falldown = 1; Flammable = 0; Explosive = 0; Meltable = 0; Hardness = 20; Weight = 50; Temperature = 253.15f; HeatConduct = 46; Description = "Freeze powder. When melted, forms ice that always cools. Spreads with regular water."; State = ST_SOLID; Properties = TYPE_PART; LowPressure = IPL; LowPressureTransition = NT; HighPressure = 1.8f; HighPressureTransition = PT_SNOW; LowTemperature = 50.0f; LowTemperatureTransition = PT_ICEI; HighTemperature = 273.15; HighTemperatureTransition = PT_WATR; Update = &Element_FRZZ::update; } //#TPT-Directive ElementHeader Element_FRZZ static int update(UPDATE_FUNC_ARGS) int Element_FRZZ::update(UPDATE_FUNC_ARGS) { int r, rx, ry; for (rx=-1; rx<2; rx++) for (ry=-1; ry<2; ry++) if (x+rx>=0 && y+ry>0 && x+rx<XRES && y+ry<YRES && (rx || ry)) { r = pmap[y+ry][x+rx]; if (!r) continue; if ((r&0xFF)==PT_WATR&&5>rand()%100) { sim->part_change_type(r>>8,x+rx,y+ry,PT_FRZW); parts[r>>8].life = 100; parts[i].type = PT_NONE; } } if (parts[i].type==PT_NONE) { sim->kill_part(i); return 1; } return 0; } Element_FRZZ::~Element_FRZZ() {}
jacksonmj/Powder-Toy-Mods
src/simulation/elements/FRZZ.cpp
C++
gpl-3.0
1,712
package net.minecraft.inventory; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.util.IIcon; // CraftBukkit start import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S2FPacketSetSlot; import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit end public class ContainerPlayer extends Container { public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2); public IInventory craftResult = new InventoryCraftResult(); public boolean isLocalWorld; private final EntityPlayer thePlayer; // CraftBukkit start private CraftInventoryView bukkitEntity = null; private InventoryPlayer player; // CraftBukkit end private static final String __OBFID = "CL_00001754"; public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_) { this.isLocalWorld = p_i1819_2_; this.thePlayer = p_i1819_3_; this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot this.player = p_i1819_1_; // CraftBukkit - save player this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36)); int i; int j; for (i = 0; i < 2; ++i) { for (j = 0; j < 2; ++j) { this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18)); } } for (i = 0; i < 4; ++i) { final int k = i; this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18) { private static final String __OBFID = "CL_00001755"; public int getSlotStackLimit() { return 1; } public boolean isItemValid(ItemStack p_75214_1_) { if (p_75214_1_ == null) return false; return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer); } @SideOnly(Side.CLIENT) public IIcon getBackgroundIconIndex() { return ItemArmor.func_94602_b(k); } }); } for (i = 0; i < 3; ++i) { for (j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18)); } } for (i = 0; i < 9; ++i) { this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142)); } // this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty } public void onCraftMatrixChanged(IInventory p_75130_1_) { // CraftBukkit start (Note: the following line would cause an error if called during construction) CraftingManager.getInstance().lastCraftView = getBukkitView(); ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj); this.craftResult.setInventorySlotContents(0, craftResult); if (super.crafters.size() < 1) { return; } EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it. player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult)); // CraftBukkit end } public void onContainerClosed(EntityPlayer p_75134_1_) { super.onContainerClosed(p_75134_1_); for (int i = 0; i < 4; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); if (itemstack != null) { p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false); } } this.craftResult.setInventorySlotContents(0, (ItemStack)null); } public boolean canInteractWith(EntityPlayer p_75145_1_) { return true; } public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(p_82846_2_); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (p_82846_2_ == 0) { if (!this.mergeItemStack(itemstack1, 9, 45, true)) { return null; } slot.onSlotChange(itemstack1, itemstack); } else if (p_82846_2_ >= 1 && p_82846_2_ < 5) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (p_82846_2_ >= 5 && p_82846_2_ < 9) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack()) { int j = 5 + ((ItemArmor)itemstack.getItem()).armorType; if (!this.mergeItemStack(itemstack1, j, j + 1, false)) { return null; } } else if (p_82846_2_ >= 9 && p_82846_2_ < 36) { if (!this.mergeItemStack(itemstack1, 36, 45, false)) { return null; } } else if (p_82846_2_ >= 36 && p_82846_2_ < 45) { if (!this.mergeItemStack(itemstack1, 9, 36, false)) { return null; } } else if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(p_82846_1_, itemstack1); } return itemstack; } public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_) { return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_); } // CraftBukkit start public CraftInventoryView getBukkitView() { if (bukkitEntity != null) { return bukkitEntity; } CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult); bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); return bukkitEntity; } // CraftBukkit end }
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/net/minecraft/inventory/ContainerPlayer.java
Java
gpl-3.0
7,916
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2005, Herve Drolon, FreeImage Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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. */ #include "opj_includes.h" opj_image_t* opj_image_create0(void) { opj_image_t *image = (opj_image_t*)opj_calloc(1, sizeof(opj_image_t)); return image; } opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc) { int compno; opj_image_t *image = NULL; image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t)); if (image) { image->color_space = clrspc; image->numcomps = numcmpts; /* allocate memory for the per-component information */ image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof( opj_image_comp_t)); if (!image->comps) { fprintf(stderr, "Unable to allocate memory for image.\n"); opj_image_destroy(image); return NULL; } /* create the individual image components */ for (compno = 0; compno < numcmpts; compno++) { opj_image_comp_t *comp = &image->comps[compno]; comp->dx = cmptparms[compno].dx; comp->dy = cmptparms[compno].dy; comp->w = cmptparms[compno].w; comp->h = cmptparms[compno].h; comp->x0 = cmptparms[compno].x0; comp->y0 = cmptparms[compno].y0; comp->prec = cmptparms[compno].prec; comp->bpp = cmptparms[compno].bpp; comp->sgnd = cmptparms[compno].sgnd; comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int)); if (!comp->data) { fprintf(stderr, "Unable to allocate memory for image.\n"); opj_image_destroy(image); return NULL; } } } return image; } void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) { int i; if (image) { if (image->comps) { /* image components */ for (i = 0; i < image->numcomps; i++) { opj_image_comp_t *image_comp = &image->comps[i]; if (image_comp->data) { opj_free(image_comp->data); } } opj_free(image->comps); } opj_free(image); } }
AlienCowEatCake/ImageViewer
src/ThirdParty/OpenJPEG/openjpeg-2.4.0/src/lib/openmj2/image.c
C
gpl-3.0
3,859
#include "spammer.h" SpammerType Settings::Spammer::type = SpammerType::SPAMMER_NONE; bool Settings::Spammer::say_team = false; bool Settings::Spammer::KillSpammer::enabled = false; bool Settings::Spammer::KillSpammer::sayTeam = false; std::vector<std::string> Settings::Spammer::KillSpammer::messages = { "$nick owned by ELITE4", "$nick suck's again" }; bool Settings::Spammer::RadioSpammer::enabled = false; std::vector<std::string> Settings::Spammer::NormalSpammer::messages = { "I'AM BAD CODER", "DON'T LIKE TOMATOES", "SUPREME HACK", "ELITE4 OWNS U AND ALL", "ELITE4LEGIT.TK", "ELITE4HVH.TK" }; int Settings::Spammer::PositionSpammer::team = 1; bool Settings::Spammer::PositionSpammer::showName = true; bool Settings::Spammer::PositionSpammer::showWeapon = true; bool Settings::Spammer::PositionSpammer::showRank = true; bool Settings::Spammer::PositionSpammer::showWins = true; bool Settings::Spammer::PositionSpammer::showHealth = true; bool Settings::Spammer::PositionSpammer::showMoney = true; bool Settings::Spammer::PositionSpammer::showLastplace = true; std::vector<int> killedPlayerQueue; void Spammer::BeginFrame(float frameTime) { if (!engine->IsInGame()) return; // Grab the current time in milliseconds long currentTime_ms = Util::GetEpochTime(); static long timeStamp = currentTime_ms; if (currentTime_ms - timeStamp < 850) return; // Kill spammer if (Settings::Spammer::KillSpammer::enabled && killedPlayerQueue.size() > 0) { IEngineClient::player_info_t playerInfo; engine->GetPlayerInfo(killedPlayerQueue[0], &playerInfo); // Prepare dead player's nickname without ';' & '"' characters // as they might cause user to execute a command. std::string dead_player_name = std::string(playerInfo.name); dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), ';'), dead_player_name.end()); dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '"'), dead_player_name.end()); // Remove end line character dead_player_name.erase(std::remove(dead_player_name.begin(), dead_player_name.end(), '\n'), dead_player_name.end()); // Construct a command with our message pstring str; str << (Settings::Spammer::KillSpammer::sayTeam ? "say_team" : "say"); std::string message = Settings::Spammer::KillSpammer::messages[std::rand() % Settings::Spammer::KillSpammer::messages.size()]; str << " \"" << Util::ReplaceString(message, "$nick", dead_player_name) << "\""; // Execute our constructed command engine->ExecuteClientCmd(str.c_str()); // Remove the first element from the vector killedPlayerQueue.erase(killedPlayerQueue.begin(), killedPlayerQueue.begin() + 1); return; } if (Settings::Spammer::RadioSpammer::enabled) { const char* radioCommands[] = { "coverme", "takepoint", "holdpos", "regroup", "followme", "takingfire", "go", "fallback", "sticktog", "report", "roger", "enemyspot", "needbackup", "sectorclear", "inposition", "reportingin", "getout", "negative", "enemydown", }; engine->ClientCmd_Unrestricted(radioCommands[std::rand() % IM_ARRAYSIZE(radioCommands)]); } if (Settings::Spammer::type == SpammerType::SPAMMER_NORMAL) { if (Settings::Spammer::NormalSpammer::messages.empty()) return; // Grab a random message string std::string message = Settings::Spammer::NormalSpammer::messages[std::rand() % Settings::Spammer::NormalSpammer::messages.size()]; // Construct a command with our message pstring str; str << (Settings::Spammer::say_team ? "say_team" : "say") << " "; str << message; // Execute our constructed command engine->ExecuteClientCmd(str.c_str()); } else if (Settings::Spammer::type == SpammerType::SPAMMER_POSITIONS) { C_BasePlayer* localplayer = (C_BasePlayer*) entityList->GetClientEntity(engine->GetLocalPlayer()); static int lastId = 1; for (int i = lastId; i < engine->GetMaxClients(); i++) { C_BasePlayer* player = (C_BasePlayer*) entityList->GetClientEntity(i); lastId++; if (lastId == engine->GetMaxClients()) lastId = 1; if (!player || player->GetDormant() || !player->GetAlive()) continue; if (Settings::Spammer::PositionSpammer::team == 0 && player->GetTeam() != localplayer->GetTeam()) continue; if (Settings::Spammer::PositionSpammer::team == 1 && player->GetTeam() == localplayer->GetTeam()) continue; IEngineClient::player_info_t entityInformation; engine->GetPlayerInfo(i, &entityInformation); C_BaseCombatWeapon* activeWeapon = (C_BaseCombatWeapon*) entityList->GetClientEntityFromHandle(player->GetActiveWeapon()); // Prepare player's nickname without ';' & '"' characters // as they might cause user to execute a command. std::string playerName = std::string(entityInformation.name); playerName.erase(std::remove(playerName.begin(), playerName.end(), ';'), playerName.end()); playerName.erase(std::remove(playerName.begin(), playerName.end(), '"'), playerName.end()); // Remove end line character playerName.erase(std::remove(playerName.begin(), playerName.end(), '\n'), playerName.end()); // Construct a command with our message pstring str; str << (Settings::Spammer::say_team ? "say_team" : "say") << " \""; if (Settings::Spammer::PositionSpammer::showName) str << playerName << " | "; if (Settings::Spammer::PositionSpammer::showWeapon) str << Util::Items::GetItemDisplayName(*activeWeapon->GetItemDefinitionIndex()) << " | "; if (Settings::Spammer::PositionSpammer::showRank) str << ESP::ranks[*(*csPlayerResource)->GetCompetitiveRanking(i)] << " | "; if (Settings::Spammer::PositionSpammer::showWins) str << *(*csPlayerResource)->GetCompetitiveWins(i) << " wins | "; if (Settings::Spammer::PositionSpammer::showHealth) str << player->GetHealth() << "HP | "; if (Settings::Spammer::PositionSpammer::showMoney) str << "$" << player->GetMoney() << " | "; if (Settings::Spammer::PositionSpammer::showLastplace) str << player->GetLastPlaceName(); str << "\""; // Execute our constructed command engine->ExecuteClientCmd(str.c_str()); break; } } // Update the time stamp timeStamp = currentTime_ms; } void Spammer::FireGameEvent(IGameEvent* event) { if (!Settings::Spammer::KillSpammer::enabled) return; if (!engine->IsInGame()) return; if (strcmp(event->GetName(), "player_death") != 0) return; int attacker_id = engine->GetPlayerForUserID(event->GetInt("attacker")); int deadPlayer_id = engine->GetPlayerForUserID(event->GetInt("userid")); // Make sure it's not a suicide.x if (attacker_id == deadPlayer_id) return; // Make sure we're the one who killed someone... if (attacker_id != engine->GetLocalPlayer()) return; killedPlayerQueue.push_back(deadPlayer_id); }
sneakyevilSK/sneakyevil.win
src/Hacks/spammer.cpp
C++
gpl-3.0
6,876
package com.app.server.repository; import com.athena.server.repository.SearchInterface; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import java.util.List; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; @SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW) public interface TitleRepository<T> extends SearchInterface { public List<T> findAll() throws SpartanPersistenceException; public T save(T entity) throws SpartanPersistenceException; public List<T> save(List<T> entity) throws SpartanPersistenceException; public void delete(String id) throws SpartanPersistenceException; public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException; public void update(List<T> entity) throws SpartanPersistenceException; public T findById(String titleId) throws Exception, SpartanPersistenceException; }
applifireAlgo/appDemoApps201115
bloodbank/src/main/java/com/app/server/repository/TitleRepository.java
Java
gpl-3.0
1,156
body { background: #EEE; font-family: arial, helvetica, sans-serif; } .controls { position: relative; width: 640px; } #seek { width: 400px; position: absolute; right: 0; top: 0; }
kawtakwar/ExtJSSummit
Training/Topics/HTML5CSS3/HTML5-Demo/chapters/chapter-4/css/app.css
CSS
gpl-3.0
197
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>RebeccaAIML: Class Members</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.5 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li id="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> </ul></div> <div class="tabs"> <ul> <li><a href="namespaces.html"><span>Namespace List</span></a></li> <li id="current"><a href="namespacemembers.html"><span>Namespace&nbsp;Members</span></a></li> </ul></div> <div class="tabs"> <ul> <li id="current"><a href="namespacemembers.html"><span>All</span></a></li> <li><a href="namespacemembers_func.html"><span>Functions</span></a></li> <li><a href="namespacemembers_type.html"><span>Typedefs</span></a></li> </ul> </div> Here is a list of all documented namespace members with links to the namespaces they belong to: <p> <ul> <li>MapStringLinks : <a class="el" href="namespacecustom_tag_1_1impl.html#ea8a448ca159d020766f77fdb2b41580">customTag::impl</a><li>MapWebPageMapStringLinks : <a class="el" href="namespacecustom_tag_1_1impl.html#31022de1a67c828d770e09c75caa835c">customTag::impl</a><li>operator&lt;() : <a class="el" href="namespacecustom_tag_1_1impl.html#9950795db5c5a7018096dfb22494a6a5">customTag::impl</a><li>sanitizeString() : <a class="el" href="namespacecustom_tag_1_1impl.html#8063ee0dbe5e9d96d9dd4933210f9cbb">customTag::impl</a></ul> <hr size="1"><address style="align: right;"><small>Generated on Tue Feb 14 22:44:55 2006 for RebeccaAIML by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.5 </small></address> </body> </html>
hallowname/librebecca
doc/web/doxygen/098/api+framework+samples/html/namespacemembers.html
HTML
gpl-3.0
2,174
/* * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com> * * This file is part of CasparCG (www.casparcg.com). * * CasparCG 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. * * CasparCG 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 CasparCG. If not, see <http://www.gnu.org/licenses/>. * * Author: Robert Nagy, ronag89@gmail.com */ #pragma once #include <common/except.h> #include <string> namespace caspar { namespace ffmpeg { struct ffmpeg_error : virtual caspar_exception{}; struct averror_bsf_not_found : virtual ffmpeg_error{}; struct averror_decoder_not_found : virtual ffmpeg_error{}; struct averror_demuxer_not_found : virtual ffmpeg_error{}; struct averror_encoder_not_found : virtual ffmpeg_error{}; struct averror_eof : virtual ffmpeg_error{}; struct averror_exit : virtual ffmpeg_error{}; struct averror_filter_not_found : virtual ffmpeg_error{}; struct averror_muxer_not_found : virtual ffmpeg_error{}; struct averror_option_not_found : virtual ffmpeg_error{}; struct averror_patchwelcome : virtual ffmpeg_error{}; struct averror_protocol_not_found : virtual ffmpeg_error{}; struct averror_stream_not_found : virtual ffmpeg_error{}; std::string av_error_str(int errn); void throw_on_ffmpeg_error(int ret, const char* source, const char* func, const char* local_func, const char* file, int line); void throw_on_ffmpeg_error(int ret, const std::wstring& source, const char* func, const char* local_func, const char* file, int line); //#define THROW_ON_ERROR(ret, source, func) throw_on_ffmpeg_error(ret, source, __FUNC__, __FILE__, __LINE__) #define THROW_ON_ERROR_STR_(call) #call #define THROW_ON_ERROR_STR(call) THROW_ON_ERROR_STR_(call) #define THROW_ON_ERROR(ret, func, source) \ throw_on_ffmpeg_error(ret, source, func, __FUNCTION__, __FILE__, __LINE__); #define THROW_ON_ERROR2(call, source) \ [&]() -> int \ { \ int ret = call; \ throw_on_ffmpeg_error(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \ return ret; \ }() #define LOG_ON_ERROR2(call, source) \ [&]() -> int \ { \ int ret = -1;\ try{ \ ret = call; \ throw_on_ffmpeg_error(ret, source, THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \ return ret; \ }catch(...){CASPAR_LOG_CURRENT_EXCEPTION();} \ return ret; \ }() #define FF_RET(ret, func) \ caspar::ffmpeg::throw_on_ffmpeg_error(ret, L"", func, __FUNCTION__, __FILE__, __LINE__); #define FF(call) \ [&]() -> int \ { \ auto ret = call; \ caspar::ffmpeg::throw_on_ffmpeg_error(static_cast<int>(ret), L"", THROW_ON_ERROR_STR(call), __FUNCTION__, __FILE__, __LINE__); \ return ret; \ }() }}
mimiyang/Server
modules/ffmpeg/ffmpeg_error.h
C
gpl-3.0
3,300
# # Makefile Makefile for the systemV init suite. # Targets: all compiles everything # install installs the binaries (not the scripts) # clean cleans up object files # clobber really cleans up # # Version: @(#)Makefile 2.85-13 23-Mar-2004 miquels@cistron.nl # CPPFLAGS = CFLAGS ?= -ansi -O2 -fomit-frame-pointer override CFLAGS += -W -Wall -D_GNU_SOURCE override CFLAGS += $(shell getconf LFS_CFLAGS) STATIC = # For some known distributions we do not build all programs, otherwise we do. BIN = SBIN = init halt shutdown runlevel killall5 fstab-decode USRBIN = last mesg MAN1 = last.1 lastb.1 mesg.1 MAN5 = initscript.5 inittab.5 MAN8 = halt.8 init.8 killall5.8 pidof.8 poweroff.8 reboot.8 runlevel.8 MAN8 += shutdown.8 telinit.8 fstab-decode.8 ifeq ($(DISTRO),) BIN += mountpoint SBIN += sulogin bootlogd USRBIN += utmpdump wall MAN1 += utmpdump.1 mountpoint.1 wall.1 MAN8 += sulogin.8 bootlogd.8 endif ifeq ($(DISTRO),Debian) CPPFLAGS+= -DACCTON_OFF BIN += mountpoint SBIN += sulogin bootlogd MAN1 += mountpoint.1 MAN8 += sulogin.8 bootlogd.8 endif ifeq ($(DISTRO),Owl) USRBIN += wall MAN1 += wall.1 endif ifeq ($(DISTRO),SuSE) CPPFLAGS+= -DUSE_SYSFS -DSANE_TIO -DSIGINT_ONLYONCE -DUSE_ONELINE BIN += mountpoint SBIN += sulogin USRBIN += utmpdump MAN1 += utmpdump.1 mountpoint.1 MAN8 += sulogin.8 endif ID = $(shell id -u) BIN_OWNER = root BIN_GROUP = root BIN_COMBO = $(BIN_OWNER):$(BIN_GROUP) ifeq ($(ID),0) INSTALL_EXEC = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 755 INSTALL_DATA = install -o $(BIN_OWNER) -g $(BIN_GROUP) -m 644 else INSTALL_EXEC = install -m 755 INSTALL_DATA = install -m 644 endif INSTALL_DIR = install -m 755 -d MANDIR = /usr/share/man ifeq ($(WITH_SELINUX),yes) SELINUX_DEF = -DWITH_SELINUX INITLIBS += -lsepol -lselinux SULOGINLIBS = -lselinux else SELINUX_DEF = INITLIBS = SULOGINLIBS = endif # Additional libs for GNU libc. ifneq ($(wildcard /usr/lib*/libcrypt.a),) SULOGINLIBS += -lcrypt endif all: $(BIN) $(SBIN) $(USRBIN) #%: %.o # $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS) #%.o: %.c # $(CC) $(CFLAGS) $(CPPFLAGS) -c $^ -o $@ init: LDLIBS += $(INITLIBS) $(STATIC) init: init.o init_utmp.o halt: halt.o ifdown.o hddown.o utmp.o reboot.h last: last.o oldutmp.h mesg: mesg.o mountpoint: mountpoint.o utmpdump: utmpdump.o runlevel: runlevel.o sulogin: LDLIBS += $(SULOGINLIBS) $(STATIC) sulogin: sulogin.o wall: dowall.o wall.o shutdown: dowall.o shutdown.o utmp.o reboot.h bootlogd: LDLIBS += -lutil bootlogd: bootlogd.o sulogin.o: CPPFLAGS += $(SELINUX_DEF) sulogin.o: sulogin.c init.o: CPPFLAGS += $(SELINUX_DEF) init.o: init.c init.h set.h reboot.h initreq.h utmp.o: utmp.c init.h init_utmp.o: CPPFLAGS += -DINIT_MAIN init_utmp.o: utmp.c init.h $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $< cleanobjs: rm -f *.o *.bak clean: cleanobjs @echo Type \"make clobber\" to really clean up. clobber: cleanobjs rm -f $(BIN) $(SBIN) $(USRBIN) distclean: clobber install: $(INSTALL_DIR) $(ROOT)/bin/ $(ROOT)/sbin/ $(INSTALL_DIR) $(ROOT)/usr/bin/ for i in $(BIN); do \ $(INSTALL_EXEC) $$i $(ROOT)/bin/ ; \ done for i in $(SBIN); do \ $(INSTALL_EXEC) $$i $(ROOT)/sbin/ ; \ done for i in $(USRBIN); do \ $(INSTALL_EXEC) $$i $(ROOT)/usr/bin/ ; \ done # $(INSTALL_DIR) $(ROOT)/etc/ # $(INSTALL_EXEC) initscript.sample $(ROOT)/etc/ ln -sf halt $(ROOT)/sbin/reboot ln -sf halt $(ROOT)/sbin/poweroff ln -sf init $(ROOT)/sbin/telinit ln -sf /sbin/killall5 $(ROOT)/bin/pidof if [ ! -f $(ROOT)/usr/bin/lastb ]; then \ ln -sf last $(ROOT)/usr/bin/lastb; \ fi $(INSTALL_DIR) $(ROOT)/usr/include/ $(INSTALL_DATA) initreq.h $(ROOT)/usr/include/ $(INSTALL_DIR) $(ROOT)$(MANDIR)/man1/ $(INSTALL_DIR) $(ROOT)$(MANDIR)/man5/ $(INSTALL_DIR) $(ROOT)$(MANDIR)/man8/ for i in $(MAN1); do \ $(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man1/; \ done for i in $(MAN5); do \ $(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man5/; \ done for i in $(MAN8); do \ $(INSTALL_DATA) ../man/$$i $(ROOT)$(MANDIR)/man8/; \ done ifeq ($(ROOT),) # # This part is skipped on Debian systems, the # debian.preinst script takes care of it. @if [ ! -p /dev/initctl ]; then \ echo "Creating /dev/initctl"; \ rm -f /dev/initctl; \ mknod -m 600 /dev/initctl p; fi endif
KubaKaszycki/kubux
sysvinit/.pc/40_multiarch_libcrypt.patch/src/Makefile
Makefile
gpl-3.0
4,367
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @copyright (C) OXID eSales AG 2003-2016 * @version OXID eShop CE */ namespace OxidEsales\EshopCommunity\Tests\Integration\Seo; use OxidEsales\Eshop\Application\Model\Article; use OxidEsales\Eshop\Application\Model\Category; use OxidEsales\Eshop\Application\Model\Object2Category; use OxidEsales\Eshop\Core\DatabaseProvider; use OxidEsales\Eshop\Core\Field; /** * Class PaginationSeoTest * * @package OxidEsales\EshopCommunity\Tests\Integration\Seo */ class PaginationSeoTest extends \OxidEsales\TestingLibrary\UnitTestCase { /** @var string Original theme */ private $origTheme; /** * @var string */ private $seoUrl = ''; /** * @var string */ private $categoryOxid = ''; /** * Sets up test */ protected function setUp(): void { parent::setUp(); $this->origTheme = $this->getConfig()->getConfigParam('sTheme'); $this->activateTheme('azure'); $this->getConfig()->saveShopConfVar('bool', 'blEnableSeoCache', false); $this->cleanRegistry(); $this->cleanSeoTable(); $facts = new \OxidEsales\Facts\Facts(); $this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/'; $this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637'; oxNew(\OxidEsales\Eshop\Application\Model\ArticleList::class)->renewPriceUpdateTime(); oxNew(\OxidEsales\Eshop\Core\SystemEventHandler::class)->onShopEnd(); } /** * Tear down test. */ protected function tearDown(): void { //restore theme, do it directly in database as it might be dummy 'basic' theme $query = "UPDATE `oxconfig` SET `OXVARVALUE` = '" . $this->origTheme . "' WHERE `OXVARNAME` = 'sTheme'"; \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query); $this->cleanRegistry(); $this->cleanSeoTable(); $_GET = []; parent::tearDown(); } /** * Call with a seo url that is not yet stored in oxseo table. * Category etc exists. * We hit the 404 as no entry for this url exists in oxseo table. * But when shop shows the 404 page, it creates the main category seo urls. */ public function testCallWithSeoUrlNoEntryInTableExists() { $this->callCurl(''); $this->callCurl($this->seoUrl); $this->cleanRegistry(); $this->cleanSeoTable(); $this->clearProxyCache(); $seoUrl = $this->seoUrl; $checkResponse = '404 Not Found'; //before $query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` like '%" . $seoUrl . "%'" . " AND oxtype = 'oxcategory'"; $res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query); $this->assertEmpty($res); //check what shop does $response = $this->callCurl($seoUrl); $this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse"); } /** * Call with a standard url that is not yet stored in oxseo table. * Category etc exists. No pgNr is provided. * * */ public function testCallWithStdUrlNoEntryExists() { $urlToCall = 'index.php?cl=alist&cnid=' . $this->categoryOxid; $checkResponse = 'HTTP/1.1 200 OK'; //Check entries in oxseo table for oxtype = 'oxcategory' $query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" . " AND oxtype = 'oxcategory'"; $res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query); $this->assertEmpty($res); $response = $this->callCurl($urlToCall); $this->assertStringContainsString($checkResponse, $response, "Should get $checkResponse"); } /** * Call shop with standard url, no matching entry in seo table exists atm. */ public function testStandardUrlNoMatchingSeoUrlSavedYet() { $requestUrl = 'index.php?cl=alist&amp;cnid=' . $this->categoryOxid; //No match in oxseo table $redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl); $this->assertFalse($redirectUrl); $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->never())->method('redirect'); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl')); $request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl)); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request); $controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); $controller->init(); $this->assertEquals(VIEW_INDEXSTATE_NOINDEXFOLLOW, $controller->noIndex()); $this->assertEmpty($this->getCategorySeoEntries()); } /** * Call shop with standard url, a matching entry in seo table already exists. */ public function testStandardUrlMatchingSeoUrlAvailable() { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $requestUrl = 'index.php?cl=alist&amp;cnid=' . $this->categoryOxid; $shopUrl = $this->getConfig()->getCurrentShopUrl(); $redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl); $this->assertEquals($this->seoUrl, $redirectUrl); $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->once())->method('redirect') ->with( $this->equalTo($shopUrl . $redirectUrl), $this->equalTo(false), $this->equalTo('301') ); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl')); $request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl)); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request); $controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); $controller->init(); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); $this->assertEquals(1, count($this->getCategorySeoEntries())); } /** * Call shop with standard url and append pgNr request parameter. * Blank seo url already is stored in oxseo table. * Case that pgNr should exist as there are sufficient items in that category. */ public function testSeoUrlWithPgNr() { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $requestUrl = 'index.php?cl=alist&amp;cnid=' . $this->categoryOxid . '&amp;pgNr=2'; //base seo url is found in database and page part appended $shopUrl = $this->getConfig()->getCurrentShopUrl(); $redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl); $this->assertEquals($this->seoUrl . '?pgNr=2', $redirectUrl); $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->once())->method('redirect') ->with( $this->equalTo($shopUrl . $redirectUrl), $this->equalTo(false), $this->equalTo('301') ); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl')); $request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl)); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request); $controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); $controller->init(); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); } /** * Test paginated entries. Call with standard url with appended pgNr parameter. */ public function testExistingPaginatedSeoEntries() { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages $this->assertGeneratedPages(); //Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case. $shopUrl = $this->getConfig()->getCurrentShopUrl(); $requestUrl = 'index.php?cl=alist&amp;cnid=' . $this->categoryOxid . '&amp;pgNr=1'; $redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl); $this->assertEquals($this->seoUrl . '?pgNr=1', $redirectUrl); $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->once())->method('redirect') ->with( $this->equalTo($shopUrl . $redirectUrl), $this->equalTo(false), $this->equalTo('301') ); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $request = $this->getMock(\OxidEsales\Eshop\Core\Request::class, array('getRequestUrl')); $request->expects($this->any())->method('getRequestUrl')->will($this->returnValue($requestUrl)); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request); $controller = oxNew(\OxidEsales\Eshop\Application\Controller\FrontendController::class); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); $controller->init(); $this->assertEquals(VIEW_INDEXSTATE_INDEX, $controller->noIndex()); } /** * Test paginated entries. Call with standard url with appended pgNr parameter. * Dofference to test case before: call with ot existing page Nr. */ public function testNotExistingPaginatedSeoEntries() { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages $this->assertGeneratedPages(); //Call with standard url that has a pgNr parameter attached, paginated seo url will be found in this case. $requestUrl = 'index.php?cl=alist&amp;cnid=' . $this->categoryOxid . '&amp;pgNr=20'; //The paginated page url is created on the fly. This seo page would not contain any data. $redirectUrl = \OxidEsales\Eshop\Core\Registry::getSeoEncoder()->fetchSeoUrl($requestUrl); $this->assertEquals($this->seoUrl . '?pgNr=20', $redirectUrl); } public function providerTestDecodeNewSeoUrl() { $facts = new \OxidEsales\Facts\Facts(); $this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/'; $this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637'; $data = []; $data['plain_seo_url'] = ['params' => $this->seoUrl, 'expected' => ['cl' => 'alist', 'cnid' => $this->categoryOxid, 'lang' => '0'] ]; $data['old_style_paginated_page'] = ['params' => $this->seoUrl . '2/', 'expected' => ['cl' => 'alist', 'cnid' => $this->categoryOxid, 'lang' => '0', 'pgNr' => 1] ]; return $data; } /** * Test decoding seo calls. * * @param string $params * @param array $expected * * @dataProvider providerTestDecodeNewSeoUrl */ public function testDecodeNewSeoUrl($params, $expected) { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $this->callCurl($this->seoUrl); //call shop seo page, this will create all paginated pages $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->never())->method('redirect'); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class); $decoded = $seoDecoder->decodeUrl($params); //decoded new url $this->assertEquals($expected, $decoded); } public function providerTestProcessingSeoCallNewSeoUrl() { $facts = new \OxidEsales\Facts\Facts(); $this->seoUrl = ('EE' == $facts->getEdition()) ? 'Party/Bar-Equipment/' : 'Geschenke/'; $this->categoryOxid = ('EE' == $facts->getEdition()) ? '30e44ab8593023055.23928895' : '8a142c3e4143562a5.46426637'; $data = []; $data['plain_seo_url'] = ['request' => $this->seoUrl, 'get' => [], 'expected' => ['cl' => 'alist', 'cnid' => $this->categoryOxid, 'lang' => '0'] ]; $data['paginated_page'] = ['request' => $this->seoUrl . '2/', 'get' => ['pgNr' => '1'], 'expected' => ['cl' => 'alist', 'cnid' => $this->categoryOxid, 'lang' => '0', 'pgNr' => '1'] ]; $data['pgnr_as_get'] = ['params' => $this->seoUrl . '?pgNr=2', 'get' => ['pgNr' => '2'], 'expected' => ['cl' => 'alist', 'cnid' => $this->categoryOxid, 'lang' => '0', 'pgNr' => '2'] ]; return $data; } /** * Test decoding seo calls. Call shop with seo main page plus pgNr parameter. * No additional paginated pages are stored in oxseo table. pgNr parameter * come in via GET and all other needed parameters for processing the call * are extracted via decodeUrl. * To be able to correctly decode an url like 'Geschenke/2/' without having * a matching entry stored in oxseo table, we need to parse this url into * 'Geschenke/' plus pgNr parameter. * * @param string $params * @param array $get * @param array $expected * * @dataProvider providerTestProcessingSeoCallNewSeoUrl */ public function testProcessingSeoCallNewSeoUrl($request, $get, $expected) { $this->callCurl(''); //call shop start page to have all seo urls for main categories generated $utils = $this->getMock(\OxidEsales\Eshop\Core\Utils::class, array('redirect')); $utils->expects($this->never())->method('redirect'); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class); $_GET = $get; $seoDecoder->processSeoCall($request, '/'); $this->assertEquals($expected, $_GET); $this->assertGeneratedPages(); } /** * Test SeoEncoderCategory::getCategoryPageUrl() */ public function testGetCategoryPageUrl() { $shopUrl = $this->getConfig()->getCurrentShopUrl(); $category = oxNew(\OxidEsales\Eshop\Application\Model\Category::class); $category->load($this->categoryOxid); $seoEncoderCategory = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class); $result = $seoEncoderCategory->getCategoryPageUrl($category, 2); $this->assertEquals($shopUrl . $this->seoUrl . '?pgNr=2', $result); //unpaginated seo url is now stored in database and should not be saved again. $seoEncoderCategory = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderCategory::class, ['_saveToDb']); $seoEncoderCategory->expects($this->never())->method('_saveToDb'); $seoEncoderCategory->getCategoryPageUrl($category, 0); $seoEncoderCategory->getCategoryPageUrl($category, 1); $seoEncoderCategory->getCategoryPageUrl($category, 2); } /** * Test SeoEncoderVendor::getVendorPageUrl() */ public function testGetVendorPageUrl() { $facts = new \OxidEsales\Facts\Facts(); if ('EE' != $facts->getEdition()) { $this->markTestSkipped('missing testdata'); } $shopUrl = $this->getConfig()->getCurrentShopUrl(); $vendorOxid = 'd2e44d9b31fcce448.08890330'; $seoUrl = 'Nach-Lieferant/Hersteller-1/'; $vendor = oxNew(\OxidEsales\Eshop\Application\Model\Vendor::class); $vendor->load($vendorOxid); $seoEncoderVendor = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class); $result = $seoEncoderVendor->getVendorPageUrl($vendor, 2); $this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result); //unpaginated seo url is now stored in database and should not be saved again. $seoEncoderVendor = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderVendor::class, ['_saveToDb']); $seoEncoderVendor->expects($this->never())->method('_saveToDb'); $seoEncoderVendor->getVendorPageUrl($vendor, 0); $seoEncoderVendor->getVendorPageUrl($vendor, 1); $seoEncoderVendor->getVendorPageUrl($vendor, 2); } /** * Test SeoEncoderManufacturer::getManufacturerPageUrl() */ public function testGetManufacturerPageUrl() { $facts = new \OxidEsales\Facts\Facts(); if ('EE' != $facts->getEdition()) { $this->markTestSkipped('missing testdata'); } $languageId = 1; //en $shopUrl = $this->getConfig()->getCurrentShopUrl(); $manufacturerOxid = '2536d76675ebe5cb777411914a2fc8fb'; $seoUrl = 'en/By-manufacturer/Manufacturer-2/'; $manufacturer = oxNew(\OxidEsales\Eshop\Application\Model\Manufacturer::class); $manufacturer->load($manufacturerOxid); $seoEncoderManufacturer = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderManufacturer::class); $result = $seoEncoderManufacturer->getManufacturerPageUrl($manufacturer, 2, $languageId); $this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result); } /** * Test SeoEncoderRecomm::getRecommPageUrl() */ public function testGetRecommPageUrl() { $shopUrl = $this->getConfig()->getCurrentShopUrl(); $seoUrl = 'testTitle/'; $recomm = $this->getMock(\OxidEsales\Eshop\Application\Model\RecommendationList::class, ['getId', 'getBaseStdLink']); $recomm->expects($this->any())->method('getId')->will($this->returnValue('testRecommId')); $recomm->expects($this->any())->method('getBaseStdLink')->will($this->returnValue('testStdLink')); $recomm->oxrecommlists__oxtitle = new \OxidEsales\Eshop\Core\Field('testTitle'); $seoEncoderRecomm = oxNew(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class); $result = $seoEncoderRecomm->getRecommPageUrl($recomm, 2); $this->assertEquals($shopUrl . $seoUrl . '?pgNr=2', $result); //unpaginated seo url is now stored in database and should not be saved again. $seoEncoderRecomm = $this->getMock(\OxidEsales\Eshop\Application\Model\SeoEncoderRecomm::class, ['_saveToDb']); $seoEncoderRecomm->expects($this->never())->method('_saveToDb'); $seoEncoderRecomm->getRecommPageUrl($recomm, 0); $seoEncoderRecomm->getRecommPageUrl($recomm, 1); $seoEncoderRecomm->getRecommPageUrl($recomm, 2); } public function providerCheckSeoUrl() { $facts = new \OxidEsales\Facts\Facts(); $oxidLiving = ('EE' != $facts->getEdition()) ? '8a142c3e44ea4e714.31136811' : '30e44ab83b6e585c9.63147165'; $data = [ ['Eco-Fashion/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []], ['Eco-Fashion/3/', ['404 Not Found'], [], ['Eco-Fashion/']], ['Eco-Fashion/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], []], ['Eco-Fashion/?pgNr=34', ['404 Not Found'],[], []], ['index.php?cl=alist&cnid=oxmore', ['HTTP/1.1 200 OK'], ['Location'], []], ['index.php?cl=alist&cnid=oxmore&pgNr=0', ['HTTP/1.1 200 OK'], ['Location'], []], ['index.php?cl=alist&cnid=oxmore&pgNr=10', ['HTTP/1.1 200 OK'], ['Location'], []], ['index.php?cl=alist&cnid=oxmore&pgNr=20', ['HTTP/1.1 200 OK'], ['Location'], []], ['index.php?cl=alist&cnid=' . $oxidLiving, ['HTTP/1.1 200 OK'], ['ROBOTS'], []], ['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS'], []], ['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=100', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]], ['index.php?cl=alist&cnid=' . $oxidLiving . '&pgNr=200', ['HTTP/1.1 302 Found'], [], ['index.php?cl=alist&cnid=' . $oxidLiving]] ]; if (('EE' == $facts->getEdition())) { $data[] = ['Fuer-Sie/', ['HTTP/1.1 200 OK'], ['ROBOTS'], []]; $data[] = ['Fuer-Sie/45/', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']]; $data[] = ['Fuer-Sie/?pgNr=0', ['HTTP/1.1 200 OK'], [ 'Location', 'ROBOTS'], []]; $data[] = ['Fuer-Sie/?pgNr=34', ['HTTP/1.1 302 Found', 'Location'], ['ROBOTS'], ['Fuer-Sie/']]; } else { $data[] = ['Geschenke/', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving]]; $data[] = ['Geschenke/?pgNr=0', ['HTTP/1.1 200 OK'], ['ROBOTS', 'Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/?pgNr=100', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/30/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/?pgNr=1', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/?pgNr=3', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/?pgNr=4', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/']]; $data[] = ['Geschenke/4/', ['HTTP/1.1 200 OK', 'ROBOTS', 'NOINDEX'], ['Location'], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1',]]; $data[] = ['Geschenke/10/', ['HTTP/1.1 302 Found', 'Location'], [], ['index.php?cl=alist&cnid=' . $oxidLiving, 'Geschenke/', 'Geschenke/?pgNr=0', 'Geschenke/?pgNr=1', 'Geschenke/4/']]; } return $data; } /** * Calling not existing pagenumbers must not result in additional entries in oxseo table. * * @dataProvider providerCheckSeoUrl * * @param string $urlToCall Url to call * @param array $responseContains Curl call response must contain. * @param array $responseNotContains Curl call response must not contain. * @param array $prepareUrls To make test cases independent, call this url first. */ public function testCheckSeoUrl( $urlToCall, $responseContains, $responseNotContains, $prepareUrls ) { $this->initSeoUrlGeneration(); foreach ($prepareUrls as $url) { $this->callCurl($url); } $response = $this->callCurl($urlToCall); foreach ($responseContains as $checkFor) { $this->assertStringContainsString($checkFor, $response, "Should get $checkFor"); } foreach ($responseNotContains as $checkFor) { $this->assertStringNotContainsString($checkFor, $response, "Should not get $checkFor"); } } public function testCreateProductSeoUrlsOnProductListPageRequest() { $this->prepareSeoUrlTestData(); $this->initSeoUrlGeneration(); $seoUrl = 'testSeoUrl/'; $productSeoUrlsCountBeforeRequest = $this->getProductSeoUrlsCount($seoUrl); $this->callCurl($seoUrl . '?pgNr=0'); $this->clearProxyCache(); $this->callCurl($seoUrl . '?pgNr=0'); $productSeoUrlsCountAfterRequest = $this->getProductSeoUrlsCount($seoUrl); $productsPerPage = 10; $this->assertEquals( $productSeoUrlsCountBeforeRequest + $productsPerPage, $productSeoUrlsCountAfterRequest ); } public function testDoNotCreateAnotherCategorySeoUrlsOnProductListPageRequest() { $this->prepareSeoUrlTestData(); $seoUrl = 'testSeoUrl/'; $this->callCurl($seoUrl); $this->assertCount( 1, $this->getCategorySeoUrls($seoUrl) ); $this->callCurl($seoUrl . '?pgNr=0'); $this->callCurl($seoUrl . '1'); $this->assertCount( 1, $this->getCategorySeoUrls($seoUrl) ); } private function initSeoUrlGeneration() { $this->clearProxyCache(); $this->callCurl(''); //call shop startpage $this->clearProxyCache(); } private function getProductSeoUrlsCount($url) { $query = " SELECT count(*) FROM `oxseo` WHERE oxseourl LIKE '%" . $url . "%' AND oxtype = 'oxarticle' "; return DatabaseProvider::getDb()->getOne($query); } private function getCategorySeoUrls($url) { $query = " SELECT oxseourl FROM `oxseo` WHERE oxseourl LIKE '%" . $url . "%' AND oxtype = 'oxcategory' "; return DatabaseProvider::getDb()->getAll($query); } private function prepareSeoUrlTestData() { $seoUrl = 'testSeoUrl'; $shopId = $this->getConfig()->getBaseShopId(); $category = oxNew(Category::class); $category->oxcategories__oxactive = new Field(1, Field::T_RAW); $category->oxcategories__oxparentid = new Field('oxrootid', Field::T_RAW); $category->oxcategories__oxshopid = new Field($shopId, Field::T_RAW); $category->oxcategories__oxtitle = new Field($seoUrl, Field::T_RAW); $category->save(); for ($i = 1; $i <= 20; $i++) { $product = oxNew(Article::class); $product->oxarticles__oxtitle = new Field($seoUrl, Field::T_RAW); $product->save(); $relation = oxNew(Object2Category::class); $relation->setCategoryId($category->getId()); $relation->setProductId($product->getId()); $relation->save(); } } /** * Clean oxseo for testing. */ private function cleanSeoTable() { $query = "DELETE FROM oxseo WHERE oxtype in ('oxcategory', 'oxarticle')"; \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->execute($query); } /** * Ensure that whatever mocks were added are removed from Registry. */ private function cleanRegistry() { $seoEncoder = oxNew(\OxidEsales\Eshop\Core\SeoEncoder::class); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoEncoder::class, $seoEncoder); $seoDecoder = oxNew(\OxidEsales\Eshop\Core\SeoDecoder::class); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\SeoDecoder::class, $seoDecoder); $utils = oxNew(\OxidEsales\Eshop\Core\Utils::class); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Utils::class, $utils); $request = oxNew(\OxidEsales\Eshop\Core\Request::class); \OxidEsales\Eshop\Core\Registry::set(\OxidEsales\Eshop\Core\Request::class, $request); } /** * @param string $fileUrlPart Shop url part to call. * * @return string */ private function callCurl($fileUrlPart) { $url = $this->getConfig()->getShopMainUrl() . $fileUrlPart; $curl = oxNew(\OxidEsales\Eshop\Core\Curl::class); $curl->setOption('CURLOPT_HEADER', true); $curl->setOption('CURLOPT_RETURNTRANSFER', true); $curl->setUrl($url); $return = $curl->execute(); sleep(0.5); // for master slave: please wait before checking the results. return $return; } /** * Test helper to check for paginated seo pages. */ private function assertGeneratedPages() { $query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSEOURL` LIKE '{$this->seoUrl}'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}%pgNr%'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}1/'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}2/'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}3/'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}4/'" . " OR `OXSEOURL` LIKE '{$this->seoUrl}5/'" . " AND oxtype = 'oxcategory'"; $res = \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query); $this->assertEquals(1, count($res)); } /** * Test helper. * * @return array */ private function getCategorySeoEntries() { $query = "SELECT oxstdurl, oxseourl FROM `oxseo` WHERE `OXSTDURL` like '%" . $this->categoryOxid . "%'" . " AND oxtype = 'oxcategory'"; return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getAll($query); } /** * Test helper. */ private function clearProxyCache() { $cacheService = oxNew(\OxidEsales\TestingLibrary\Services\Library\Cache::class); $cacheService->clearReverseProxyCache(); } }
flow-control/oxideshop_ce
tests/Integration/Seo/PaginationSeoTest.php
PHP
gpl-3.0
31,918
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include <vgui/IBorder.h> #include <vgui/IInputInternal.h> #include <vgui/IPanel.h> #include <vgui/IScheme.h> #include <vgui/IVGui.h> #include <vgui/KeyCode.h> #include <KeyValues.h> #include <vgui/MouseCode.h> #include <vgui/ISurface.h> #include <vgui_controls/Button.h> #include <vgui_controls/Controls.h> #include <vgui_controls/Label.h> #include <vgui_controls/PropertySheet.h> #include <vgui_controls/ComboBox.h> #include <vgui_controls/Panel.h> #include <vgui_controls/ToolWindow.h> #include <vgui_controls/TextImage.h> #include <vgui_controls/ImagePanel.h> #include <vgui_controls/PropertyPage.h> #include "vgui_controls/AnimationController.h" #include "strtools_local.h" // TODO: temp // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui2; namespace vgui2 { class ContextLabel : public Label { DECLARE_CLASS_SIMPLE(ContextLabel, Label); public: ContextLabel(Button *parent, char const *panelName, char const *text) : BaseClass((Panel *)parent, panelName, text), m_pTabButton(parent) { SetBlockDragChaining(true); } virtual void OnMousePressed(MouseCode code) { if(m_pTabButton) { m_pTabButton->FireActionSignal(); } } virtual void OnMouseReleased(MouseCode code) { BaseClass::OnMouseReleased(code); if(GetParent()) { GetParent()->OnCommand("ShowContextMenu"); } } virtual void ApplySchemeSettings(IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); HFont marlett = pScheme->GetFont("Marlett"); SetFont(marlett); SetTextInset(0, 0); SetContentAlignment(Label::a_northwest); if(GetParent()) { SetFgColor(pScheme->GetColor("Button.TextColor", GetParent()->GetFgColor())); SetBgColor(GetParent()->GetBgColor()); } } private: Button *m_pTabButton; }; //----------------------------------------------------------------------------- // Purpose: Helper for drag drop // Input : msglist - // Output : static PropertySheet //----------------------------------------------------------------------------- static PropertySheet *IsDroppingSheet(CUtlVector<KeyValues *> &msglist) { if(msglist.Count() == 0) return NULL; KeyValues *data = msglist[0]; PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet")); if(sheet) return sheet; return NULL; } //----------------------------------------------------------------------------- // Purpose: A single tab //----------------------------------------------------------------------------- class PageTab : public Button { DECLARE_CLASS_SIMPLE(PageTab, Button); private: bool _active; SDK_Color _textColor; SDK_Color _dimTextColor; int m_bMaxTabWidth; IBorder *m_pActiveBorder; IBorder *m_pNormalBorder; PropertySheet *m_pParent; Panel *m_pPage; ImagePanel *m_pImage; char *m_pszImageName; bool m_bShowContextLabel; ContextLabel *m_pContextLabel; public: PageTab(PropertySheet *parent, const char *panelName, const char *text, char const *imageName, int maxTabWidth, Panel *page, bool showContextButton) : Button((Panel *)parent, panelName, text), m_pParent(parent), m_pPage(page), m_pImage(0), m_pszImageName(0), m_bShowContextLabel(showContextButton) { SetCommand(new KeyValues("TabPressed")); _active = false; m_bMaxTabWidth = maxTabWidth; SetDropEnabled(true); SetDragEnabled(m_pParent->IsDraggableTab()); if(imageName) { m_pImage = new ImagePanel(this, text); int buflen = Q_strlen(imageName) + 1; m_pszImageName = new char[buflen]; Q_strncpy(m_pszImageName, imageName, buflen); } SetMouseClickEnabled(MOUSE_RIGHT, true); m_pContextLabel = m_bShowContextLabel ? new ContextLabel(this, "Context", "9") : NULL; REGISTER_COLOR_AS_OVERRIDABLE(_textColor, "selectedcolor"); REGISTER_COLOR_AS_OVERRIDABLE(_dimTextColor, "unselectedcolor"); } ~PageTab() { delete[] m_pszImageName; } virtual void Paint() { BaseClass::Paint(); } virtual bool IsDroppable(CUtlVector<KeyValues *> &msglist) { // It's never droppable, but should activate FireActionSignal(); SetSelected(true); Repaint(); if(!GetParent()) return false; PropertySheet *sheet = IsDroppingSheet(msglist); if(sheet) { return GetParent()->IsDroppable(msglist); } // Defer to active page... Panel *active = m_pParent->GetActivePage(); if(!active || !active->IsDroppable(msglist)) return false; return active->IsDroppable(msglist); } virtual void OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels) { PropertySheet *sheet = IsDroppingSheet(msglist); if(sheet) { Panel *target = GetParent()->GetDropTarget(msglist); if(target) { // Fixme, mouse pos could be wrong... target->OnDroppablePanelPaint(msglist, dragPanels); return; } } // Just highlight the tab if dropping onto active page via the tab BaseClass::OnDroppablePanelPaint(msglist, dragPanels); } virtual void OnPanelDropped(CUtlVector<KeyValues *> &msglist) { PropertySheet *sheet = IsDroppingSheet(msglist); if(sheet) { Panel *target = GetParent()->GetDropTarget(msglist); if(target) { // Fixme, mouse pos could be wrong... target->OnPanelDropped(msglist); } } // Defer to active page... Panel *active = m_pParent->GetActivePage(); if(!active || !active->IsDroppable(msglist)) return; active->OnPanelDropped(msglist); } virtual void OnDragFailed(CUtlVector<KeyValues *> &msglist) { PropertySheet *sheet = IsDroppingSheet(msglist); if(!sheet) return; // Create a new property sheet if(m_pParent->IsDraggableTab()) { if(msglist.Count() == 1) { KeyValues *data = msglist[0]; int screenx = data->GetInt("screenx"); int screeny = data->GetInt("screeny"); // m_pParent->ScreenToLocal( screenx, screeny ); if(!m_pParent->IsWithin(screenx, screeny)) { Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage")); PropertySheet *sheet = reinterpret_cast<PropertySheet *>(data->GetPtr("propertysheet")); char const *title = data->GetString("tabname", ""); if(!page || !sheet) return; // Can only create if sheet was part of a ToolWindow derived object ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent()); if(tw) { IToolWindowFactory *factory = tw->GetToolWindowFactory(); if(factory) { bool hasContextMenu = sheet->PageHasContextMenu(page); sheet->RemovePage(page); factory->InstanceToolWindow(tw->GetParent(), sheet->ShouldShowContextButtons(), page, title, hasContextMenu); if(sheet->GetNumPages() == 0) { tw->MarkForDeletion(); } } } } } } } virtual void OnCreateDragData(KeyValues *msg) { Assert(m_pParent->IsDraggableTab()); msg->SetPtr("propertypage", m_pPage); msg->SetPtr("propertysheet", m_pParent); char sz[256]; GetText(sz, sizeof(sz)); msg->SetString("tabname", sz); msg->SetString("text", sz); } virtual void ApplySchemeSettings(IScheme *pScheme) { // set up the scheme settings Button::ApplySchemeSettings(pScheme); _textColor = GetSchemeColor("PropertySheet.SelectedTextColor", GetFgColor(), pScheme); _dimTextColor = GetSchemeColor("PropertySheet.TextColor", GetFgColor(), pScheme); m_pActiveBorder = pScheme->GetBorder("TabActiveBorder"); m_pNormalBorder = pScheme->GetBorder("TabBorder"); if(m_pImage) { ClearImages(); m_pImage->SetImage(scheme()->GetImage(m_pszImageName, false)); AddImage(m_pImage->GetImage(), 2); int w, h; m_pImage->GetSize(w, h); w += m_pContextLabel ? 10 : 0; if(m_pContextLabel) { m_pImage->SetPos(10, 0); } SetSize(w + 4, h + 2); } else { int wide, tall; int contentWide, contentTall; GetSize(wide, tall); GetContentSize(contentWide, contentTall); wide = std::max(m_bMaxTabWidth, contentWide + 10); // 10 = 5 pixels margin on each side wide += m_pContextLabel ? 10 : 0; SetSize(wide, tall); } if(m_pContextLabel) { SetTextInset(12, 0); } } virtual void OnCommand(char const *cmd) { if(!Q_stricmp(cmd, "ShowContextMenu")) { KeyValues *kv = new KeyValues("OpenContextMenu"); kv->SetPtr("page", m_pPage); kv->SetPtr("contextlabel", m_pContextLabel); PostActionSignal(kv); return; } BaseClass::OnCommand(cmd); } IBorder *GetBorder(bool depressed, bool armed, bool selected, bool keyfocus) { if(_active) { return m_pActiveBorder; } return m_pNormalBorder; } virtual SDK_Color GetButtonFgColor() { if(_active) { return _textColor; } else { return _dimTextColor; } } virtual void SetActive(bool state) { _active = state; InvalidateLayout(); Repaint(); } virtual bool CanBeDefaultButton(void) { return false; } //Fire action signal when mouse is pressed down instead of on release. virtual void OnMousePressed(MouseCode code) { // check for context menu open if(!IsEnabled()) return; if(!IsMouseClickEnabled(code)) return; if(IsUseCaptureMouseEnabled()) { { RequestFocus(); FireActionSignal(); SetSelected(true); Repaint(); } // lock mouse input to going to this button input()->SetMouseCapture(GetVPanel()); } } virtual void OnMouseReleased(MouseCode code) { // ensure mouse capture gets released if(IsUseCaptureMouseEnabled()) { input()->SetMouseCapture(NULL_HANDLE); } // make sure the button gets unselected SetSelected(false); Repaint(); if(code == MOUSE_RIGHT) { KeyValues *kv = new KeyValues("OpenContextMenu"); kv->SetPtr("page", m_pPage); kv->SetPtr("contextlabel", m_pContextLabel); PostActionSignal(kv); } } virtual void PerformLayout() { BaseClass::PerformLayout(); if(m_pContextLabel) { int w, h; GetSize(w, h); m_pContextLabel->SetBounds(0, 0, 10, h); } } }; }; // namespace vgui2 //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- PropertySheet::PropertySheet( Panel *parent, const char *panelName, bool draggableTabs /*= false*/) : BaseClass(parent, panelName) { _activePage = NULL; _activeTab = NULL; _tabWidth = 64; _activeTabIndex = 0; _showTabs = true; _combo = NULL; _tabFocus = false; m_flPageTransitionEffectTime = 0.0f; m_bSmallTabs = false; m_tabFont = 0; m_bDraggableTabs = draggableTabs; if(m_bDraggableTabs) { SetDropEnabled(true); } m_bKBNavigationEnabled = true; } //----------------------------------------------------------------------------- // Purpose: Constructor, associates pages with a combo box //----------------------------------------------------------------------------- PropertySheet::PropertySheet(Panel *parent, const char *panelName, ComboBox *combo) : BaseClass(parent, panelName) { _activePage = NULL; _activeTab = NULL; _tabWidth = 64; _activeTabIndex = 0; _combo = combo; _combo->AddActionSignalTarget(this); _showTabs = false; _tabFocus = false; m_flPageTransitionEffectTime = 0.0f; m_bSmallTabs = false; m_tabFont = 0; m_bDraggableTabs = false; } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- PropertySheet::~PropertySheet() { } //----------------------------------------------------------------------------- // Purpose: ToolWindow uses this to drag tools from container to container by dragging the tab // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PropertySheet::IsDraggableTab() const { return m_bDraggableTabs; } void PropertySheet::SetDraggableTabs(bool state) { m_bDraggableTabs = state; } //----------------------------------------------------------------------------- // Purpose: Lower profile tabs // Input : state - //----------------------------------------------------------------------------- void PropertySheet::SetSmallTabs(bool state) { m_bSmallTabs = state; m_tabFont = scheme()->GetIScheme(GetScheme())->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default"); int c = m_PageTabs.Count(); for(int i = 0; i < c; ++i) { PageTab *tab = m_PageTabs[i]; Assert(tab); tab->SetFont(m_tabFont); } } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PropertySheet::IsSmallTabs() const { return m_bSmallTabs; } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- void PropertySheet::ShowContextButtons(bool state) { m_bContextButton = state; } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PropertySheet::ShouldShowContextButtons() const { return m_bContextButton; } int PropertySheet::FindPage(Panel *page) const { int c = m_Pages.Count(); for(int i = 0; i < c; ++i) { if(m_Pages[i].page == page) return i; } return m_Pages.InvalidIndex(); } //----------------------------------------------------------------------------- // Purpose: adds a page to the sheet //----------------------------------------------------------------------------- void PropertySheet::AddPage(Panel *page, const char *title, char const *imageName /*= NULL*/, bool bHasContextMenu /*= false*/) { if(!page) return; // don't add the page if we already have it if(FindPage(page) != m_Pages.InvalidIndex()) return; PageTab *tab = new PageTab(this, "tab", title, imageName, _tabWidth, page, m_bContextButton && bHasContextMenu); if(m_bDraggableTabs) { tab->SetDragEnabled(true); } tab->SetFont(m_tabFont); if(_showTabs) { tab->AddActionSignalTarget(this); } else if(_combo) { _combo->AddItem(title, NULL); } m_PageTabs.AddToTail(tab); Page_t info; info.page = page; info.contextMenu = m_bContextButton && bHasContextMenu; m_Pages.AddToTail(info); page->SetParent(this); page->AddActionSignalTarget(this); PostMessage(page, new KeyValues("ResetData")); page->SetVisible(false); InvalidateLayout(); if(!_activePage) { // first page becomes the active page ChangeActiveTab(0); if(_activePage) { _activePage->RequestFocus(0); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::SetActivePage(Panel *page) { // walk the list looking for this page int index = FindPage(page); if(!m_Pages.IsValidIndex(index)) return; ChangeActiveTab(index); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::SetTabWidth(int pixels) { _tabWidth = pixels; InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: reloads the data in all the property page //----------------------------------------------------------------------------- void PropertySheet::ResetAllData() { // iterate all the dialogs resetting them for(int i = 0; i < m_Pages.Count(); i++) { ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ResetData"), GetVPanel()); } } //----------------------------------------------------------------------------- // Purpose: Applies any changes made by the dialog //----------------------------------------------------------------------------- void PropertySheet::ApplyChanges() { // iterate all the dialogs resetting them for(int i = 0; i < m_Pages.Count(); i++) { ipanel()->SendMessage(m_Pages[i].page->GetVPanel(), new KeyValues("ApplyChanges"), GetVPanel()); } } //----------------------------------------------------------------------------- // Purpose: gets a pointer to the currently active page //----------------------------------------------------------------------------- Panel *PropertySheet::GetActivePage() { return _activePage; } //----------------------------------------------------------------------------- // Purpose: gets a pointer to the currently active tab //----------------------------------------------------------------------------- Panel *PropertySheet::GetActiveTab() { return _activeTab; } //----------------------------------------------------------------------------- // Purpose: returns the number of panels in the sheet //----------------------------------------------------------------------------- int PropertySheet::GetNumPages() { return m_Pages.Count(); } //----------------------------------------------------------------------------- // Purpose: returns the name contained in the active tab // Input : a text buffer to contain the output //----------------------------------------------------------------------------- void PropertySheet::GetActiveTabTitle(char *textOut, int bufferLen) { if(_activeTab) _activeTab->GetText(textOut, bufferLen); } //----------------------------------------------------------------------------- // Purpose: returns the name contained in the active tab // Input : a text buffer to contain the output //----------------------------------------------------------------------------- bool PropertySheet::GetTabTitle(int i, char *textOut, int bufferLen) { if(i < 0 && i > m_PageTabs.Count()) { return false; } m_PageTabs[i]->GetText(textOut, bufferLen); return true; } //----------------------------------------------------------------------------- // Purpose: Returns the index of the currently active page //----------------------------------------------------------------------------- int PropertySheet::GetActivePageNum() { for(int i = 0; i < m_Pages.Count(); i++) { if(m_Pages[i].page == _activePage) { return i; } } return -1; } //----------------------------------------------------------------------------- // Purpose: Forwards focus requests to current active page //----------------------------------------------------------------------------- void PropertySheet::RequestFocus(int direction) { if(direction == -1 || direction == 0) { if(_activePage) { _activePage->RequestFocus(direction); _tabFocus = false; } } else { if(_showTabs && _activeTab) { _activeTab->RequestFocus(direction); _tabFocus = true; } else if(_activePage) { _activePage->RequestFocus(direction); _tabFocus = false; } } } //----------------------------------------------------------------------------- // Purpose: moves focus back //----------------------------------------------------------------------------- bool PropertySheet::RequestFocusPrev(VPANEL panel) { if(_tabFocus || !_showTabs || !_activeTab) { _tabFocus = false; return BaseClass::RequestFocusPrev(panel); } else { if(GetVParent()) { PostMessage(GetVParent(), new KeyValues("FindDefaultButton")); } _activeTab->RequestFocus(-1); _tabFocus = true; return true; } } //----------------------------------------------------------------------------- // Purpose: moves focus forward //----------------------------------------------------------------------------- bool PropertySheet::RequestFocusNext(VPANEL panel) { if(!_tabFocus || !_activePage) { return BaseClass::RequestFocusNext(panel); } else { if(!_activeTab) { return BaseClass::RequestFocusNext(panel); } else { _activePage->RequestFocus(1); _tabFocus = false; return true; } } } //----------------------------------------------------------------------------- // Purpose: Gets scheme settings //----------------------------------------------------------------------------- void PropertySheet::ApplySchemeSettings(IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); // a little backwards-compatibility with old scheme files IBorder *pBorder = pScheme->GetBorder("PropertySheetBorder"); if(pBorder == pScheme->GetBorder("Default")) { // get the old name pBorder = pScheme->GetBorder("RaisedBorder"); } SetBorder(pBorder); m_flPageTransitionEffectTime = atof(pScheme->GetResourceString("PropertySheet.TransitionEffectTime")); m_tabFont = pScheme->GetFont(m_bSmallTabs ? "DefaultVerySmall" : "Default"); } //----------------------------------------------------------------------------- // Purpose: Paint our border specially, with the tabs in mind //----------------------------------------------------------------------------- void PropertySheet::PaintBorder() { IBorder *border = GetBorder(); if(!border) return; // draw the border, but with a break at the active tab int px = 0, py = 0, pwide = 0, ptall = 0; if(_activeTab) { _activeTab->GetBounds(px, py, pwide, ptall); ptall -= 1; } // draw the border underneath the buttons, with a break int wide, tall; GetSize(wide, tall); border->Paint(0, py + ptall, wide, tall, IBorder::SIDE_TOP, px + 1, px + pwide - 1); } //----------------------------------------------------------------------------- // Purpose: Lays out the dialog //----------------------------------------------------------------------------- void PropertySheet::PerformLayout() { BaseClass::PerformLayout(); int x, y, wide, tall; GetBounds(x, y, wide, tall); if(_activePage) { int tabHeight = IsSmallTabs() ? 14 : 28; if(_showTabs) { _activePage->SetBounds(0, tabHeight, wide, tall - tabHeight); } else { _activePage->SetBounds(0, 0, wide, tall); } _activePage->InvalidateLayout(); } int xtab; int limit = m_PageTabs.Count(); xtab = 0; // draw the visible tabs if(_showTabs) { for(int i = 0; i < limit; i++) { int tabHeight = IsSmallTabs() ? 13 : 27; int width, tall; m_PageTabs[i]->GetSize(width, tall); if(m_PageTabs[i] == _activeTab) { // active tab is taller _activeTab->SetBounds(xtab, 2, width, tabHeight); } else { m_PageTabs[i]->SetBounds(xtab, 4, width, tabHeight - 2); } m_PageTabs[i]->SetVisible(true); xtab += (width + 1); } } else { for(int i = 0; i < limit; i++) { m_PageTabs[i]->SetVisible(false); } } // ensure draw order (page drawing over all the tabs except one) if(_activePage) { _activePage->MoveToFront(); _activePage->Repaint(); } if(_activeTab) { _activeTab->MoveToFront(); _activeTab->Repaint(); } } //----------------------------------------------------------------------------- // Purpose: Switches the active panel //----------------------------------------------------------------------------- void PropertySheet::OnTabPressed(Panel *panel) { // look for the tab in the list for(int i = 0; i < m_PageTabs.Count(); i++) { if(m_PageTabs[i] == panel) { // flip to the new tab ChangeActiveTab(i); return; } } } //----------------------------------------------------------------------------- // Purpose: returns the panel associated with index i // Input : the index of the panel to return //----------------------------------------------------------------------------- Panel *PropertySheet::GetPage(int i) { if(i < 0 && i > m_Pages.Count()) { return NULL; } return m_Pages[i].page; } //----------------------------------------------------------------------------- // Purpose: disables page by name //----------------------------------------------------------------------------- void PropertySheet::DisablePage(const char *title) { SetPageEnabled(title, false); } //----------------------------------------------------------------------------- // Purpose: enables page by name //----------------------------------------------------------------------------- void PropertySheet::EnablePage(const char *title) { SetPageEnabled(title, true); } //----------------------------------------------------------------------------- // Purpose: enabled or disables page by name //----------------------------------------------------------------------------- void PropertySheet::SetPageEnabled(const char *title, bool state) { for(int i = 0; i < m_PageTabs.Count(); i++) { if(_showTabs) { char tmp[50]; m_PageTabs[i]->GetText(tmp, 50); if(!strnicmp(title, tmp, strlen(tmp))) { m_PageTabs[i]->SetEnabled(state); } } else { _combo->SetItemEnabled(title, state); } } } void PropertySheet::RemoveAllPages() { int c = m_Pages.Count(); for(int i = c - 1; i >= 0; --i) { RemovePage(m_Pages[i].page); } } //----------------------------------------------------------------------------- // Purpose: deletes the page associated with panel // Input : *panel - the panel of the page to remove //----------------------------------------------------------------------------- void PropertySheet::RemovePage(Panel *panel) { int location = FindPage(panel); if(location == m_Pages.InvalidIndex()) return; // Since it's being deleted, don't animate!!! m_hPreviouslyActivePage = NULL; _activeTab = NULL; // ASSUMPTION = that the number of pages equals number of tabs if(_showTabs) { m_PageTabs[location]->RemoveActionSignalTarget(this); } // now remove the tab PageTab *tab = m_PageTabs[location]; m_PageTabs.Remove(location); tab->MarkForDeletion(); // Remove from page list m_Pages.Remove(location); // Unparent panel->SetParent((Panel *)NULL); if(_activePage == panel) { _activePage = NULL; // if this page is currently active, backup to the page before this. ChangeActiveTab(std::max(location - 1, 0)); } PerformLayout(); } //----------------------------------------------------------------------------- // Purpose: deletes the page associated with panel // Input : *panel - the panel of the page to remove //----------------------------------------------------------------------------- void PropertySheet::DeletePage(Panel *panel) { Assert(panel); RemovePage(panel); panel->MarkForDeletion(); } //----------------------------------------------------------------------------- // Purpose: flips to the new tab, sending out all the right notifications // flipping to a tab activates the tab. //----------------------------------------------------------------------------- void PropertySheet::ChangeActiveTab(int index) { if(!m_Pages.IsValidIndex(index)) { _activeTab = NULL; if(m_Pages.Count() > 0) { _activePage = NULL; ChangeActiveTab(0); } return; } if(m_Pages[index].page == _activePage) { if(_activeTab) { _activeTab->RequestFocus(); } _tabFocus = true; return; } int c = m_Pages.Count(); for(int i = 0; i < c; ++i) { m_Pages[i].page->SetVisible(false); } m_hPreviouslyActivePage = _activePage; // notify old page if(_activePage) { ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageHide"), GetVPanel()); KeyValues *msg = new KeyValues("PageTabActivated"); msg->SetPtr("panel", (Panel *)NULL); ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel()); } if(_activeTab) { //_activeTabIndex=index; _activeTab->SetActive(false); // does the old tab have the focus? _tabFocus = _activeTab->HasFocus(); } else { _tabFocus = false; } // flip page _activePage = m_Pages[index].page; _activeTab = m_PageTabs[index]; _activeTabIndex = index; _activePage->SetVisible(true); _activePage->MoveToFront(); _activeTab->SetVisible(true); _activeTab->MoveToFront(); _activeTab->SetActive(true); if(_tabFocus) { // if a tab already has focused,give the new tab the focus _activeTab->RequestFocus(); } else { // otherwise, give the focus to the page _activePage->RequestFocus(); } if(!_showTabs) { _combo->ActivateItemByRow(index); } _activePage->MakeReadyForUse(); // transition effect if(m_flPageTransitionEffectTime) { if(m_hPreviouslyActivePage.Get()) { // fade out the previous page GetAnimationController()->RunAnimationCommand(m_hPreviouslyActivePage, "Alpha", 0.0f, 0.0f, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR); } // fade in the new page _activePage->SetAlpha(0); GetAnimationController()->RunAnimationCommand(_activePage, "Alpha", 255.0f, m_flPageTransitionEffectTime / 2, m_flPageTransitionEffectTime / 2, AnimationController::INTERPOLATOR_LINEAR); } else { if(m_hPreviouslyActivePage.Get()) { // no transition, just hide the previous page m_hPreviouslyActivePage->SetVisible(false); } _activePage->SetAlpha(255); } // notify ivgui()->PostMessage(_activePage->GetVPanel(), new KeyValues("PageShow"), GetVPanel()); KeyValues *msg = new KeyValues("PageTabActivated"); msg->SetPtr("panel", (Panel *)_activeTab); ivgui()->PostMessage(_activePage->GetVPanel(), msg, GetVPanel()); // tell parent PostActionSignal(new KeyValues("PageChanged")); // Repaint InvalidateLayout(); Repaint(); } //----------------------------------------------------------------------------- // Purpose: Gets the panel with the specified hotkey, from the current page //----------------------------------------------------------------------------- Panel *PropertySheet::HasHotkey(wchar_t key) { if(!_activePage) return NULL; for(int i = 0; i < _activePage->GetChildCount(); i++) { Panel *hot = _activePage->GetChild(i)->HasHotkey(key); if(hot) { return hot; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: catches the opencontextmenu event //----------------------------------------------------------------------------- void PropertySheet::OnOpenContextMenu(KeyValues *params) { // tell parent KeyValues *kv = params->MakeCopy(); PostActionSignal(kv); Panel *page = reinterpret_cast<Panel *>(params->GetPtr("page")); if(page) { PostMessage(page->GetVPanel(), params->MakeCopy()); } } //----------------------------------------------------------------------------- // Purpose: Handle key presses, through tabs. //----------------------------------------------------------------------------- void PropertySheet::OnKeyCodeTyped(KeyCode code) { bool shift = (input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT)); bool ctrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL)); bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT)); if(ctrl && shift && alt && code == KEY_B) { // enable build mode EditablePanel *ep = dynamic_cast<EditablePanel *>(GetActivePage()); if(ep) { ep->ActivateBuildMode(); return; } } if(IsKBNavigationEnabled()) { switch(code) { // for now left and right arrows just open or close submenus if they are there. case KEY_RIGHT: { ChangeActiveTab(_activeTabIndex + 1); break; } case KEY_LEFT: { ChangeActiveTab(_activeTabIndex - 1); break; } default: BaseClass::OnKeyCodeTyped(code); break; } } else { BaseClass::OnKeyCodeTyped(code); } } //----------------------------------------------------------------------------- // Purpose: Called by the associated combo box (if in that mode), changes the current panel //----------------------------------------------------------------------------- void PropertySheet::OnTextChanged(Panel *panel, const wchar_t *wszText) { if(panel == _combo) { wchar_t tabText[30]; for(int i = 0; i < m_PageTabs.Count(); i++) { tabText[0] = 0; m_PageTabs[i]->GetText(tabText, 30); if(!wcsicmp(wszText, tabText)) { ChangeActiveTab(i); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::OnCommand(const char *command) { // propogate the close command to our parent if(!stricmp(command, "Close") && GetVParent()) { CallParentFunction(new KeyValues("Command", "command", command)); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::OnApplyButtonEnable() { // tell parent PostActionSignal(new KeyValues("ApplyButtonEnable")); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::OnCurrentDefaultButtonSet(Panel *defaultButton) { // forward the message up if(GetVParent()) { KeyValues *msg = new KeyValues("CurrentDefaultButtonSet"); msg->SetPtr("button", defaultButton); PostMessage(GetVParent(), msg); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::OnDefaultButtonSet(Panel *defaultButton) { // forward the message up if(GetVParent()) { KeyValues *msg = new KeyValues("DefaultButtonSet"); msg->SetPtr("button", defaultButton); PostMessage(GetVParent(), msg); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void PropertySheet::OnFindDefaultButton() { if(GetVParent()) { PostMessage(GetVParent(), new KeyValues("FindDefaultButton")); } } bool PropertySheet::PageHasContextMenu(Panel *page) const { int pageNum = FindPage(page); if(pageNum == m_Pages.InvalidIndex()) return false; return m_Pages[pageNum].contextMenu; } void PropertySheet::OnPanelDropped(CUtlVector<KeyValues *> &msglist) { if(msglist.Count() != 1) { return; } PropertySheet *sheet = IsDroppingSheet(msglist); if(!sheet) { // Defer to active page if(_activePage && _activePage->IsDropEnabled()) { return _activePage->OnPanelDropped(msglist); } return; } KeyValues *data = msglist[0]; Panel *page = reinterpret_cast<Panel *>(data->GetPtr("propertypage")); char const *title = data->GetString("tabname", ""); if(!page || !sheet) return; // Can only create if sheet was part of a ToolWindow derived object ToolWindow *tw = dynamic_cast<ToolWindow *>(sheet->GetParent()); if(tw) { IToolWindowFactory *factory = tw->GetToolWindowFactory(); if(factory) { bool showContext = sheet->PageHasContextMenu(page); sheet->RemovePage(page); if(sheet->GetNumPages() == 0) { tw->MarkForDeletion(); } AddPage(page, title, NULL, showContext); } } } bool PropertySheet::IsDroppable(CUtlVector<KeyValues *> &msglist) { if(!m_bDraggableTabs) return false; if(msglist.Count() != 1) { return false; } int mx, my; input()->GetCursorPos(mx, my); ScreenToLocal(mx, my); int tabHeight = IsSmallTabs() ? 14 : 28; if(my > tabHeight) return false; PropertySheet *sheet = IsDroppingSheet(msglist); if(!sheet) { return false; } if(sheet == this) return false; return true; } // Mouse is now over a droppable panel void PropertySheet::OnDroppablePanelPaint(CUtlVector<KeyValues *> &msglist, CUtlVector<Panel *> &dragPanels) { // Convert this panel's bounds to screen space int x, y, w, h; GetSize(w, h); int tabHeight = IsSmallTabs() ? 14 : 28; h = tabHeight + 4; x = y = 0; LocalToScreen(x, y); surface()->DrawSetColor(GetDropFrameColor()); // Draw 2 pixel frame surface()->DrawOutlinedRect(x, y, x + w, y + h); surface()->DrawOutlinedRect(x + 1, y + 1, x + w - 1, y + h - 1); if(!IsDroppable(msglist)) { return; } if(!_showTabs) { return; } // Draw a fake new tab... x = 0; y = 2; w = 1; h = tabHeight; int last = m_PageTabs.Count(); if(last != 0) { m_PageTabs[last - 1]->GetBounds(x, y, w, h); } // Compute left edge of "fake" tab x += (w + 1); // Compute size of new panel KeyValues *data = msglist[0]; char const *text = data->GetString("tabname", ""); Assert(text); PageTab *fakeTab = new PageTab(this, "FakeTab", text, NULL, _tabWidth, NULL, false); fakeTab->SetBounds(x, 4, w, tabHeight - 4); fakeTab->SetFont(m_tabFont); SETUP_PANEL(fakeTab); fakeTab->Repaint(); surface()->SolveTraverse(fakeTab->GetVPanel(), true); surface()->PaintTraverse(fakeTab->GetVPanel()); delete fakeTab; } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- void PropertySheet::SetKBNavigationEnabled(bool state) { m_bKBNavigationEnabled = state; } //----------------------------------------------------------------------------- // Purpose: // Input : - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool PropertySheet::IsKBNavigationEnabled() const { return m_bKBNavigationEnabled; }
projectogs/OpenGoldSrc
goldsrc/vgui2/controls/PropertySheet.cpp
C++
gpl-3.0
37,352
import gtk class ExtensionFeatures: SYSTEM_WIDE = 0 class MountManagerExtension: """Base class for mount manager extensions. Mount manager has only one instance and is created on program startup. Methods defined in this class are called automatically by the mount manager so you need to implement them. """ # features extension supports features = () def __init__(self, parent, window): self._parent = parent self._window = window self._application = self._parent._application # create user interface self._container = gtk.VBox(False, 5) self._controls = gtk.HBox(False, 5) separator = gtk.HSeparator() # pack interface self._container.pack_end(separator, False, False, 0) self._container.pack_end(self._controls, False, False, 0) def can_handle(self, uri): """Returns boolean denoting if specified URI can be handled by this extension""" return False def get_container(self): """Return container widget""" return self._container def get_information(self): """Returns information about extension""" icon = None name = None return icon, name def unmount(self, uri): """Method called by the mount manager for unmounting the selected URI""" pass def focus_object(self): """Method called by the mount manager for focusing main object""" pass @classmethod def get_features(cls): """Returns set of features supported by extension""" return cls.features
Azulinho/sunflower-file-manager-with-tmsu-tagging-support
application/plugin_base/mount_manager_extension.py
Python
gpl-3.0
1,433
<?php // content="text/plain; charset=utf-8" require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_gantt.php'); $graph = new GanttGraph(); $graph->SetBox(); $graph->SetShadow(); // Add title and subtitle $graph->title->Set("Example of captions"); $graph->title->SetFont(FF_ARIAL,FS_BOLD,12); $graph->subtitle->Set("(ganttex16.php)"); // Show day, week and month scale $graph->ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH); // Set table title $graph->scale->tableTitle->Set("(Rev: 1.22)"); $graph->scale->tableTitle->SetFont(FF_FONT1,FS_BOLD); $graph->scale->SetTableTitleBackground("silver"); $graph->scale->tableTitle->Show(); // Use the short name of the month together with a 2 digit year // on the month scale $graph->scale->month->SetStyle(MONTHSTYLE_SHORTNAMEYEAR2); $graph->scale->month->SetFontColor("white"); $graph->scale->month->SetBackgroundColor("blue"); // 0 % vertical label margin $graph->SetLabelVMarginFactor(1); // Format the bar for the first activity // ($row,$title,$startdate,$enddate) $activity = new GanttBar(0,"Project","2001-12-21","2002-01-07","[50%]"); // Yellow diagonal line pattern on a red background $activity->SetPattern(BAND_RDIAG,"yellow"); $activity->SetFillColor("red"); // Set absolute height $activity->SetHeight(10); // Specify progress to 60% $activity->progress->Set(0.6); $activity->progress->SetPattern(BAND_HVCROSS,"blue"); // Format the bar for the second activity // ($row,$title,$startdate,$enddate) $activity2 = new GanttBar(1,"Project","2001-12-21","2002-01-02","[30%]"); // Yellow diagonal line pattern on a red background $activity2->SetPattern(BAND_RDIAG,"yellow"); $activity2->SetFillColor("red"); // Set absolute height $activity2->SetHeight(10); // Specify progress to 30% $activity2->progress->Set(0.3); $activity2->progress->SetPattern(BAND_HVCROSS,"blue"); // Finally add the bar to the graph $graph->Add($activity); $graph->Add($activity2); // Add a vertical line $vline = new GanttVLine("2001-12-24","Phase 1"); $vline->SetDayOffset(0.5); //$graph->Add($vline); // ... and display it $graph->Stroke(); ?>
boabo/pxp
lib/jpgraph/src/Examples/ganttex16.php
PHP
gpl-3.0
2,180
/*! @license Firebase v4.3.1 Build: rev-b4fe95f Terms: https://firebase.google.com/terms/ */ "use strict"; //# sourceMappingURL=requestmaker.js.map
chidelmun/Zikki
node_modules/firebase/storage/implementation/requestmaker.js
JavaScript
gpl-3.0
149
package cn.nukkit.math; /** * author: MagicDroidX * Nukkit Project */ public class Vector3 implements Cloneable { public double x; public double y; public double z; public Vector3() { this(0, 0, 0); } public Vector3(double x) { this(x, 0, 0); } public Vector3(double x, double y) { this(x, y, 0); } public Vector3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return this.x; } public double getY() { return this.y; } public double getZ() { return this.z; } public int getFloorX() { return (int) Math.floor(this.x); } public int getFloorY() { return (int) Math.floor(this.y); } public int getFloorZ() { return (int) Math.floor(this.z); } public double getRight() { return this.x; } public double getUp() { return this.y; } public double getForward() { return this.z; } public double getSouth() { return this.x; } public double getWest() { return this.z; } public Vector3 add(double x) { return this.add(x, 0, 0); } public Vector3 add(double x, double y) { return this.add(x, y, 0); } public Vector3 add(double x, double y, double z) { return new Vector3(this.x + x, this.y + y, this.z + z); } public Vector3 add(Vector3 x) { return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ()); } public Vector3 subtract() { return this.subtract(0, 0, 0); } public Vector3 subtract(double x) { return this.subtract(x, 0, 0); } public Vector3 subtract(double x, double y) { return this.subtract(x, y, 0); } public Vector3 subtract(double x, double y, double z) { return this.add(-x, -y, -z); } public Vector3 subtract(Vector3 x) { return this.add(-x.getX(), -x.getY(), -x.getZ()); } public Vector3 multiply(double number) { return new Vector3(this.x * number, this.y * number, this.z * number); } public Vector3 divide(double number) { return new Vector3(this.x / number, this.y / number, this.z / number); } public Vector3 ceil() { return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z)); } public Vector3 floor() { return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ()); } public Vector3 round() { return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); } public Vector3 abs() { return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z)); } public Vector3 getSide(BlockFace face) { return this.getSide(face, 1); } public Vector3 getSide(BlockFace face, int step) { return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step); } public Vector3 up() { return up(1); } public Vector3 up(int step) { return getSide(BlockFace.UP, step); } public Vector3 down() { return down(1); } public Vector3 down(int step) { return getSide(BlockFace.DOWN, step); } public Vector3 north() { return north(1); } public Vector3 north(int step) { return getSide(BlockFace.NORTH, step); } public Vector3 south() { return south(1); } public Vector3 south(int step) { return getSide(BlockFace.SOUTH, step); } public Vector3 east() { return east(1); } public Vector3 east(int step) { return getSide(BlockFace.EAST, step); } public Vector3 west() { return west(1); } public Vector3 west(int step) { return getSide(BlockFace.WEST, step); } public double distance(Vector3 pos) { return Math.sqrt(this.distanceSquared(pos)); } public double distanceSquared(Vector3 pos) { return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2); } public double maxPlainDistance() { return this.maxPlainDistance(0, 0); } public double maxPlainDistance(double x) { return this.maxPlainDistance(x, 0); } public double maxPlainDistance(double x, double z) { return Math.max(Math.abs(this.x - x), Math.abs(this.z - z)); } public double maxPlainDistance(Vector2 vector) { return this.maxPlainDistance(vector.x, vector.y); } public double maxPlainDistance(Vector3 x) { return this.maxPlainDistance(x.x, x.z); } public double length() { return Math.sqrt(this.lengthSquared()); } public double lengthSquared() { return this.x * this.x + this.y * this.y + this.z * this.z; } public Vector3 normalize() { double len = this.lengthSquared(); if (len > 0) { return this.divide(Math.sqrt(len)); } return new Vector3(0, 0, 0); } public double dot(Vector3 v) { return this.x * v.x + this.y * v.y + this.z * v.z; } public Vector3 cross(Vector3 v) { return new Vector3( this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y * v.x ); } /** * Returns a new vector with x value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithXValue(Vector3 v, double x) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (xDiff * xDiff < 0.0000001) { return null; } double f = (x - this.x) / xDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } /** * Returns a new vector with y value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithYValue(Vector3 v, double y) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (yDiff * yDiff < 0.0000001) { return null; } double f = (y - this.y) / yDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } /** * Returns a new vector with z value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithZValue(Vector3 v, double z) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (zDiff * zDiff < 0.0000001) { return null; } double f = (z - this.z) / zDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } public Vector3 setComponents(double x, double y, double z) { this.x = x; this.y = y; this.z = z; return this; } @Override public String toString() { return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; } @Override public boolean equals(Object obj) { if (!(obj instanceof Vector3)) { return false; } Vector3 other = (Vector3) obj; return this.x == other.x && this.y == other.y && this.z == other.z; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32); hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32); hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32); return hash; } public int rawHashCode() { return super.hashCode(); } @Override public Vector3 clone() { try { return (Vector3) super.clone(); } catch (CloneNotSupportedException e) { return null; } } public Vector3f asVector3f() { return new Vector3f((float) this.x, (float) this.y, (float) this.z); } public BlockVector3 asBlockVector3() { return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ()); } }
JupiterDevelopmentTeam/JupiterDevelopmentTeam
src/main/java/cn/nukkit/math/Vector3.java
Java
gpl-3.0
9,009
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== class FileListTreeItem : public TreeViewItem, private TimeSliceClient, private AsyncUpdater, private ChangeListener { public: FileListTreeItem (FileTreeComponent& treeComp, DirectoryContentsList* parentContents, int indexInContents, const File& f, TimeSliceThread& t) : file (f), owner (treeComp), parentContentsList (parentContents), indexInContentsList (indexInContents), subContentsList (nullptr, false), thread (t) { DirectoryContentsList::FileInfo fileInfo; if (parentContents != nullptr && parentContents->getFileInfo (indexInContents, fileInfo)) { fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize); modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M"); isDirectory = fileInfo.isDirectory; } else { isDirectory = true; } } ~FileListTreeItem() override { thread.removeTimeSliceClient (this); clearSubItems(); removeSubContentsList(); } //============================================================================== bool mightContainSubItems() override { return isDirectory; } String getUniqueName() const override { return file.getFullPathName(); } int getItemHeight() const override { return owner.getItemHeight(); } var getDragSourceDescription() override { return owner.getDragAndDropDescription(); } void itemOpennessChanged (bool isNowOpen) override { if (isNowOpen) { clearSubItems(); isDirectory = file.isDirectory(); if (isDirectory) { if (subContentsList == nullptr) { jassert (parentContentsList != nullptr); auto l = new DirectoryContentsList (parentContentsList->getFilter(), thread); l->setDirectory (file, parentContentsList->isFindingDirectories(), parentContentsList->isFindingFiles()); setSubContentsList (l, true); } changeListenerCallback (nullptr); } } } void removeSubContentsList() { if (subContentsList != nullptr) { subContentsList->removeChangeListener (this); subContentsList.reset(); } } void setSubContentsList (DirectoryContentsList* newList, const bool canDeleteList) { removeSubContentsList(); subContentsList = OptionalScopedPointer<DirectoryContentsList> (newList, canDeleteList); newList->addChangeListener (this); } bool selectFile (const File& target) { if (file == target) { setSelected (true, true); return true; } if (target.isAChildOf (file)) { setOpen (true); for (int maxRetries = 500; --maxRetries > 0;) { for (int i = 0; i < getNumSubItems(); ++i) if (auto* f = dynamic_cast<FileListTreeItem*> (getSubItem (i))) if (f->selectFile (target)) return true; // if we've just opened and the contents are still loading, wait for it.. if (subContentsList != nullptr && subContentsList->isStillLoading()) { Thread::sleep (10); rebuildItemsFromContentList(); } else { break; } } } return false; } void changeListenerCallback (ChangeBroadcaster*) override { rebuildItemsFromContentList(); } void rebuildItemsFromContentList() { clearSubItems(); if (isOpen() && subContentsList != nullptr) { for (int i = 0; i < subContentsList->getNumFiles(); ++i) addSubItem (new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread)); } } void paintItem (Graphics& g, int width, int height) override { ScopedLock lock (iconUpdate); if (file != File()) { updateIcon (true); if (icon.isNull()) thread.addTimeSliceClient (this); } owner.getLookAndFeel().drawFileBrowserRow (g, width, height, file, file.getFileName(), &icon, fileSize, modTime, isDirectory, isSelected(), indexInContentsList, owner); } void itemClicked (const MouseEvent& e) override { owner.sendMouseClickMessage (file, e); } void itemDoubleClicked (const MouseEvent& e) override { TreeViewItem::itemDoubleClicked (e); owner.sendDoubleClickMessage (file); } void itemSelectionChanged (bool) override { owner.sendSelectionChangeMessage(); } int useTimeSlice() override { updateIcon (false); return -1; } void handleAsyncUpdate() override { owner.repaint(); } const File file; private: FileTreeComponent& owner; DirectoryContentsList* parentContentsList; int indexInContentsList; OptionalScopedPointer<DirectoryContentsList> subContentsList; bool isDirectory; TimeSliceThread& thread; CriticalSection iconUpdate; Image icon; String fileSize, modTime; void updateIcon (const bool onlyUpdateIfCached) { if (icon.isNull()) { auto hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode(); auto im = ImageCache::getFromHashCode (hashCode); if (im.isNull() && ! onlyUpdateIfCached) { im = juce_createIconForFile (file); if (im.isValid()) ImageCache::addImageToCache (im, hashCode); } if (im.isValid()) { { ScopedLock lock (iconUpdate); icon = im; } triggerAsyncUpdate(); } } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem) }; //============================================================================== FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow) : DirectoryContentsDisplayComponent (listToShow), itemHeight (22) { setRootItemVisible (false); refresh(); } FileTreeComponent::~FileTreeComponent() { deleteRootItem(); } void FileTreeComponent::refresh() { deleteRootItem(); auto root = new FileListTreeItem (*this, nullptr, 0, directoryContentsList.getDirectory(), directoryContentsList.getTimeSliceThread()); root->setSubContentsList (&directoryContentsList, false); setRootItem (root); } //============================================================================== File FileTreeComponent::getSelectedFile (const int index) const { if (auto* item = dynamic_cast<const FileListTreeItem*> (getSelectedItem (index))) return item->file; return {}; } void FileTreeComponent::deselectAllFiles() { clearSelectedItems(); } void FileTreeComponent::scrollToTop() { getViewport()->getVerticalScrollBar().setCurrentRangeStart (0); } void FileTreeComponent::setDragAndDropDescription (const String& description) { dragAndDropDescription = description; } void FileTreeComponent::setSelectedFile (const File& target) { if (auto* t = dynamic_cast<FileListTreeItem*> (getRootItem())) if (! t->selectFile (target)) clearSelectedItems(); } void FileTreeComponent::setItemHeight (int newHeight) { if (itemHeight != newHeight) { itemHeight = newHeight; if (auto* root = getRootItem()) root->treeHasChanged(); } } } // namespace juce
danielrothmann/Roth-AIR
JuceLibraryCode/modules/juce_gui_basics/filebrowser/juce_FileTreeComponent.cpp
C++
gpl-3.0
9,810
<?php /** * * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Newsletter\Controller\Adminhtml\Template; class NewAction extends \Magento\Newsletter\Controller\Adminhtml\Template { /** * Create new Newsletter Template * * @return void */ public function execute() { $this->_forward('edit'); } }
rajmahesh/magento2-master
vendor/magento/module-newsletter/Controller/Adminhtml/Template/NewAction.php
PHP
gpl-3.0
403
// // StyleDressApp.h // DressApp // // Created by Javier Sanchez Sierra on 12/24/11. // Copyright (c) 2011 Javier Sanchez Sierra. All rights reserved. // // This file is part of DressApp. // DressApp 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. // // DressApp 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/>. // // 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. //https://github.com/jsanchezsierra/DressApp #import <Foundation/Foundation.h> typedef enum { StyleTypeVintage = 1, StyleTypeModern =2, } StyleType; typedef enum { StyleColorMainNavigationBar, StyleColorMainToolBar, StyleColorPREmptyCategoria, StyleColorPRHeader, StyleColorPRBackground, StyleColorPRSectionSeparator, StyleColorPRDetailHeader, StyleColorPRDetailMarcaTitle, StyleColorPRDetailMarcaName, StyleColorPRDetailPrecio, StyleColorPRDetailEtiqueta, StyleColorPRDetailBackground, StyleColorPRDetailBackgroundPrenda, StyleColorPRNotasSectionTitle, StyleColorPRNotasCell, StyleColorPRNotasBtnFont, StyleColorPREtiquetasSectionTitle, StyleColorPREtiquetasCell, StyleColorPRCategoriaHeader, StyleColorPRCategoriaSectionTitle, StyleColorPRCategoriaCell, StyleColorPRCategoriaCellBackground, StyleColorPRCategoriaCellSeparatorLine, StyleColorPRPrecioHeader, StyleColorPRPrecioCell, StyleColorPRTallaHeader, StyleColorPRTallaSectionTitle, StyleColorPRTallaCell, StyleColorPRTallaResetBtn, StyleColorPRCompHeader, StyleColorPRCompCell, StyleColorPRMisMarcasHeader, StyleColorPRMisMarcasEmptySectionTitle, StyleColorPRMisMarcasCell, StyleColorPRMisMarcasCellBackground, StyleColorPRMisMarcasCellSeparatorLine, StyleColorPRMarcasHeader, StyleColorPRMarcasCell, StyleColorPRMarcasCellBackground, StyleColorPRMarcasCellSeparatorLine, StyleColorMainMenuBackground, StyleColorMainMenuHeader, StyleColorMainMenuSection, StyleColorMainMenuSectionBackground, StyleColorMainMenuCell, StyleColorMainMenuCellBackground, StyleColorMainMenuCellForegroundView, StyleColorCOEmptyConjunto, StyleColorCOHeader, StyleColorCOBackground, StyleColorCODetailHeader, StyleColorCODetailBackground, StyleColorCODetailTollBarButtons, StyleColorCOCategoriaHeader, StyleColorCOCategoriaCell, StyleColorCOCategoriaCellBackground, StyleColorCOCategoriaCellSeparatorLine, StyleColorCONotasHeader, StyleColorCONotasSectionTitle, StyleColorCONotasCell, StyleColorActionViewBackground, StyleColorActionViewTitle, StyleColorActionViewCell, StyleColorActionViewCellSelected, StyleColorHelpCell, StyleColorHelpCellBackground, StyleColorHelpCellSeparatorLine, StyleColorHelpVersion, StyleColorHelpDetailTitle, StyleColorHelpDetailText, StyleColorProfileBtnTitle, StyleColorProfileBtnRecoverPwdTitle, StyleColorProfileBtnRecoverPwdTitleInverse, StyleColorProfileDetailBtnTitle, StyleColorProfileDetailTextView, StyleColorRegisterWelcomeTitle, StyleColorRegisterWelcomeBtn, StyleColorFechaHeader, StyleColorYourStyleHeader, StyleColorYourStyleBtnTitle, StyleColorYourStyleCualEsBackground, StyleColorYourStyleCualEsHeader, StyleColorYourStyleCualEsTitle, StyleColorYourStyleCualEsText, StyleColorYourStyleFashionBackground, StyleColorYourStyleFashionHeader, StyleColorYourStyleFashionTitle, StyleColorYourStyleFashionText, StyleColorCalendarBackground, StyleColorCalendarMonthTitle, StyleColorCalendarWeekDayTitle, StyleColorCalendarDay, StyleColorCalendarOtherMonthDay, StyleColorCalendarWeekendDay, StyleColorCalendarFillToday, StyleColorCalendarFillNormalDay, StyleColorCalendarFillOtherMonthDay, StyleColorCalendarSelectedDay, StyleColorCalendarDetailHeader, StyleColorCalendarDetailBackground, StyleColorStylesHeader, StyleColorStylesTitle, StyleColorStylesDetailHeader, StyleColorStyleST01DetailInAppHeaderColor, StyleColorStyleST02DetailInAppHeaderColor, StyleColorStyleST01DetailInAppHeaderTextColor, StyleColorStyleST02DetailInAppHeaderTextColor, StyleColorStyleST01DetailInAppText, StyleColorStyleST02DetailInAppText, StyleColorSortBackground, StyleColorSortTitleColor, StyleColorSortCellText, StyleColorSortCellBackground, StyleColorSortNotesBackground, StyleColorSortNotesCellText } StyleColorType; typedef enum { StyleFontMainType, StyleFontFlat, StyleFontBottomBtns, StyleFontActionView, StyleFontAparienciaST01, StyleFontAparienciaST02, } StyleFontType; @interface StyleDressApp : NSObject +(void) setStyle:(StyleType)newAppStyle; +(StyleType) getStyle; +(UIImage*) imageWithStyleNamed:(NSString*)imageName; +(UIColor*) colorWithStyleForObject:(StyleColorType)styleColor; +(UIFont*) fontWithStyleNamed:(StyleFontType)newFontType AndSize:(CGFloat)newFontSize; @end
domix/DressApp
DressApp/DressApp/StyleDressApp.h
C
gpl-3.0
6,669
/***************************************************************************** * Copyright (c) 2014-2019 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ #include "TileElement.h" #include "../core/Guard.hpp" #include "../interface/Window.h" #include "../localisation/Localisation.h" #include "../ride/Track.h" #include "Banner.h" #include "LargeScenery.h" #include "Scenery.h" uint8_t TileElementBase::GetType() const { return this->type & TILE_ELEMENT_TYPE_MASK; } void TileElementBase::SetType(uint8_t newType) { this->type &= ~TILE_ELEMENT_TYPE_MASK; this->type |= (newType & TILE_ELEMENT_TYPE_MASK); } Direction TileElementBase::GetDirection() const { return this->type & TILE_ELEMENT_DIRECTION_MASK; } void TileElementBase::SetDirection(Direction direction) { this->type &= ~TILE_ELEMENT_DIRECTION_MASK; this->type |= (direction & TILE_ELEMENT_DIRECTION_MASK); } Direction TileElementBase::GetDirectionWithOffset(uint8_t offset) const { return ((this->type & TILE_ELEMENT_DIRECTION_MASK) + offset) & TILE_ELEMENT_DIRECTION_MASK; } bool TileElementBase::IsLastForTile() const { return (this->flags & TILE_ELEMENT_FLAG_LAST_TILE) != 0; } void TileElementBase::SetLastForTile(bool on) { if (on) flags |= TILE_ELEMENT_FLAG_LAST_TILE; else flags &= ~TILE_ELEMENT_FLAG_LAST_TILE; } bool TileElementBase::IsGhost() const { return (this->flags & TILE_ELEMENT_FLAG_GHOST) != 0; } void TileElementBase::SetGhost(bool isGhost) { if (isGhost) { this->flags |= TILE_ELEMENT_FLAG_GHOST; } else { this->flags &= ~TILE_ELEMENT_FLAG_GHOST; } } bool tile_element_is_underground(TileElement* tileElement) { do { tileElement++; if ((tileElement - 1)->IsLastForTile()) return false; } while (tileElement->GetType() != TILE_ELEMENT_TYPE_SURFACE); return true; } BannerIndex tile_element_get_banner_index(TileElement* tileElement) { rct_scenery_entry* sceneryEntry; switch (tileElement->GetType()) { case TILE_ELEMENT_TYPE_LARGE_SCENERY: sceneryEntry = tileElement->AsLargeScenery()->GetEntry(); if (sceneryEntry->large_scenery.scrolling_mode == SCROLLING_MODE_NONE) return BANNER_INDEX_NULL; return tileElement->AsLargeScenery()->GetBannerIndex(); case TILE_ELEMENT_TYPE_WALL: sceneryEntry = tileElement->AsWall()->GetEntry(); if (sceneryEntry == nullptr || sceneryEntry->wall.scrolling_mode == SCROLLING_MODE_NONE) return BANNER_INDEX_NULL; return tileElement->AsWall()->GetBannerIndex(); case TILE_ELEMENT_TYPE_BANNER: return tileElement->AsBanner()->GetIndex(); default: return BANNER_INDEX_NULL; } } void tile_element_set_banner_index(TileElement* tileElement, BannerIndex bannerIndex) { switch (tileElement->GetType()) { case TILE_ELEMENT_TYPE_WALL: tileElement->AsWall()->SetBannerIndex(bannerIndex); break; case TILE_ELEMENT_TYPE_LARGE_SCENERY: tileElement->AsLargeScenery()->SetBannerIndex(bannerIndex); break; case TILE_ELEMENT_TYPE_BANNER: tileElement->AsBanner()->SetIndex(bannerIndex); break; default: log_error("Tried to set banner index on unsuitable tile element!"); Guard::Assert(false); } } void tile_element_remove_banner_entry(TileElement* tileElement) { auto bannerIndex = tile_element_get_banner_index(tileElement); auto banner = GetBanner(bannerIndex); if (banner != nullptr) { window_close_by_number(WC_BANNER, bannerIndex); *banner = {}; } } uint8_t tile_element_get_ride_index(const TileElement* tileElement) { switch (tileElement->GetType()) { case TILE_ELEMENT_TYPE_TRACK: return tileElement->AsTrack()->GetRideIndex(); case TILE_ELEMENT_TYPE_ENTRANCE: return tileElement->AsEntrance()->GetRideIndex(); case TILE_ELEMENT_TYPE_PATH: return tileElement->AsPath()->GetRideIndex(); default: return RIDE_ID_NULL; } } void TileElement::ClearAs(uint8_t newType) { type = newType; flags = 0; base_height = 2; clearance_height = 2; std::fill_n(pad_04, sizeof(pad_04), 0x00); std::fill_n(pad_08, sizeof(pad_08), 0x00); } void TileElementBase::Remove() { tile_element_remove((TileElement*)this); } // Rotate both of the values amount const QuarterTile QuarterTile::Rotate(uint8_t amount) const { switch (amount) { case 0: return QuarterTile{ *this }; break; case 1: { auto rotVal1 = _val << 1; auto rotVal2 = rotVal1 >> 4; // Clear the bit from the tileQuarter rotVal1 &= 0b11101110; // Clear the bit from the zQuarter rotVal2 &= 0b00010001; return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) }; } case 2: { auto rotVal1 = _val << 2; auto rotVal2 = rotVal1 >> 4; // Clear the bit from the tileQuarter rotVal1 &= 0b11001100; // Clear the bit from the zQuarter rotVal2 &= 0b00110011; return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) }; } case 3: { auto rotVal1 = _val << 3; auto rotVal2 = rotVal1 >> 4; // Clear the bit from the tileQuarter rotVal1 &= 0b10001000; // Clear the bit from the zQuarter rotVal2 &= 0b01110111; return QuarterTile{ static_cast<uint8_t>(rotVal1 | rotVal2) }; } default: log_error("Tried to rotate QuarterTile invalid amount."); return QuarterTile{ 0 }; } } uint8_t TileElementBase::GetOccupiedQuadrants() const { return flags & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK; } void TileElementBase::SetOccupiedQuadrants(uint8_t quadrants) { flags &= ~TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK; flags |= (quadrants & TILE_ELEMENT_OCCUPIED_QUADRANTS_MASK); } int32_t TileElementBase::GetBaseZ() const { return base_height * 8; } void TileElementBase::SetBaseZ(int32_t newZ) { base_height = (newZ / 8); } int32_t TileElementBase::GetClearanceZ() const { return clearance_height * 8; } void TileElementBase::SetClearanceZ(int32_t newZ) { clearance_height = (newZ / 8); }
IntelOrca/OpenRCT2
src/openrct2/world/TileElement.cpp
C++
gpl-3.0
6,843
/* FreeRTOS V7.3.0 - Copyright (C) 2012 Real Time Engineers Ltd. FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! *************************************************************************** * * * Having a problem? Start by reading the FAQ "My application does * * not run, what could be wrong?" * * * * http://www.FreeRTOS.org/FAQHelp.html * * * *************************************************************************** http://www.FreeRTOS.org - Documentation, training, latest versions, license and contact details. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool. Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell the code with commercial support, indemnification, and middleware, under the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also provide a safety engineered and independently SIL3 certified version under the SafeRTOS brand: http://www.SafeRTOS.com. */ /*----------------------------------------------------------- * Implementation of functions defined in portable.h for the PIC32MX port. *----------------------------------------------------------*/ /* Scheduler include files. */ #include "FreeRTOS.h" #include "task.h" /* Hardware specifics. */ #define portTIMER_PRESCALE 8 /* Bits within various registers. */ #define portIE_BIT ( 0x00000001 ) #define portEXL_BIT ( 0x00000002 ) /* The EXL bit is set to ensure interrupts do not occur while the context of the first task is being restored. */ #define portINITIAL_SR ( portIE_BIT | portEXL_BIT ) #ifndef configTICK_INTERRUPT_VECTOR #define configTICK_INTERRUPT_VECTOR _TIMER_1_VECTOR #endif /* Records the interrupt nesting depth. This starts at one as it will be decremented to 0 when the first task starts. */ volatile unsigned portBASE_TYPE uxInterruptNesting = 0x01; /* Stores the task stack pointer when a switch is made to use the system stack. */ unsigned portBASE_TYPE uxSavedTaskStackPointer = 0; /* The stack used by interrupt service routines that cause a context switch. */ portSTACK_TYPE xISRStack[ configISR_STACK_SIZE ] = { 0 }; /* The top of stack value ensures there is enough space to store 6 registers on the callers stack, as some functions seem to want to do this. */ const portSTACK_TYPE * const xISRStackTop = &( xISRStack[ configISR_STACK_SIZE - 7 ] ); /* * Place the prototype here to ensure the interrupt vector is correctly installed. * Note that because the interrupt is written in assembly, the IPL setting in the * following line of code has no effect. The interrupt priority is set by the * call to ConfigIntTimer1() in vApplicationSetupTickTimerInterrupt(). */ extern void __attribute__( (interrupt(ipl1), vector( configTICK_INTERRUPT_VECTOR ))) vPortTickInterruptHandler( void ); /* * The software interrupt handler that performs the yield. Note that, because * the interrupt is written in assembly, the IPL setting in the following line of * code has no effect. The interrupt priority is set by the call to * mConfigIntCoreSW0() in xPortStartScheduler(). */ void __attribute__( (interrupt(ipl1), vector(_CORE_SOFTWARE_0_VECTOR))) vPortYieldISR( void ); /*-----------------------------------------------------------*/ /* * See header file for description. */ portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ) { /* Ensure byte alignment is maintained when leaving this function. */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) 0xDEADBEEF; pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) 0x12345678; /* Word to which the stack pointer will be left pointing after context restore. */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) _CP0_GET_CAUSE(); pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) portINITIAL_SR; /* CP0_STATUS */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) pxCode; /* CP0_EPC */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) NULL; /* ra */ pxTopOfStack -= 15; *pxTopOfStack = (portSTACK_TYPE) pvParameters; /* Parameters to pass in */ pxTopOfStack -= 14; *pxTopOfStack = (portSTACK_TYPE) 0x00000000; /* critical nesting level - no longer used. */ pxTopOfStack--; return pxTopOfStack; } /*-----------------------------------------------------------*/ /* * Setup a timer for a regular tick. This function uses peripheral timer 1. * The function is declared weak so an application writer can use a different * timer by redefining this implementation. If a different timer is used then * configTICK_INTERRUPT_VECTOR must also be defined in FreeRTOSConfig.h to * ensure the RTOS provided tick interrupt handler is installed on the correct * vector number. When Timer 1 is used the vector number is defined as * _TIMER_1_VECTOR. */ __attribute__(( weak )) void vApplicationSetupTickTimerInterrupt( void ) { const unsigned long ulCompareMatch = ( (configPERIPHERAL_CLOCK_HZ / portTIMER_PRESCALE) / configTICK_RATE_HZ ) - 1; OpenTimer1( ( T1_ON | T1_PS_1_8 | T1_SOURCE_INT ), ulCompareMatch ); ConfigIntTimer1( T1_INT_ON | configKERNEL_INTERRUPT_PRIORITY ); } /*-----------------------------------------------------------*/ void vPortEndScheduler(void) { /* It is unlikely that the scheduler for the PIC port will get stopped once running. If required disable the tick interrupt here, then return to xPortStartScheduler(). */ for( ;; ); } /*-----------------------------------------------------------*/ portBASE_TYPE xPortStartScheduler( void ) { extern void vPortStartFirstTask( void ); extern void *pxCurrentTCB; /* Setup the software interrupt. */ mConfigIntCoreSW0( CSW_INT_ON | configKERNEL_INTERRUPT_PRIORITY | CSW_INT_SUB_PRIOR_0 ); /* Setup the timer to generate the tick. Interrupts will have been disabled by the time we get here. */ vApplicationSetupTickTimerInterrupt(); /* Kick off the highest priority task that has been created so far. Its stack location is loaded into uxSavedTaskStackPointer. */ uxSavedTaskStackPointer = *( unsigned portBASE_TYPE * ) pxCurrentTCB; vPortStartFirstTask(); /* Should never get here as the tasks will now be executing. */ return pdFALSE; } /*-----------------------------------------------------------*/ void vPortIncrementTick( void ) { unsigned portBASE_TYPE uxSavedStatus; uxSavedStatus = uxPortSetInterruptMaskFromISR(); vTaskIncrementTick(); vPortClearInterruptMaskFromISR( uxSavedStatus ); /* If we are using the preemptive scheduler then we might want to select a different task to execute. */ #if configUSE_PREEMPTION == 1 SetCoreSW0(); #endif /* configUSE_PREEMPTION */ /* Clear timer 0 interrupt. */ mT1ClearIntFlag(); } /*-----------------------------------------------------------*/ unsigned portBASE_TYPE uxPortSetInterruptMaskFromISR( void ) { unsigned portBASE_TYPE uxSavedStatusRegister; asm volatile ( "di" ); uxSavedStatusRegister = _CP0_GET_STATUS() | 0x01; /* This clears the IPL bits, then sets them to configMAX_SYSCALL_INTERRUPT_PRIORITY. This function should not be called from an interrupt that has a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY so, when used correctly, the action can only result in the IPL being unchanged or raised, and therefore never lowered. */ _CP0_SET_STATUS( ( ( uxSavedStatusRegister & ( ~portALL_IPL_BITS ) ) ) | ( configMAX_SYSCALL_INTERRUPT_PRIORITY << portIPL_SHIFT ) ); return uxSavedStatusRegister; } /*-----------------------------------------------------------*/ void vPortClearInterruptMaskFromISR( unsigned portBASE_TYPE uxSavedStatusRegister ) { _CP0_SET_STATUS( uxSavedStatusRegister ); } /*-----------------------------------------------------------*/
ilikecake/Rocket-controller
software/freertos/freertos/Source/portable/MPLAB/PIC32MX/port.c
C
gpl-3.0
10,779
/* * PktGen by Steffen Schulz © 2009 * * Braindead TCP server that waits for a packet and then * - replies with stream of packets * - with inter-packet delays read as integers from stdin * * Disables Nagle Algo to prevent buffering in local network stack * */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <stdarg.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <fcntl.h> #define DEBUG (1) /* Basic signal handler closes nfq hooks on exit */ static void sig_handler(int signum) { printf("\nCaught Signal ...\n\n"); exit(0); } int main(int argc, char **argv) { struct sockaddr_in sin; struct sockaddr_in sout; int s = socket(AF_INET,SOCK_STREAM,0); unsigned int slen = sizeof(sout); unsigned int len = 0; char line[500]; long delay = 0; unsigned int cntr = 0; int port = 1194; int tmp = 0; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = INADDR_ANY; /* make stdin non-blocking, i.e. optional */ int flags = fcntl(0, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(0, F_SETFL, flags); /* close nfq hooks on exit */ if (signal(SIGINT, sig_handler) == SIG_IGN) signal(SIGINT, SIG_IGN); if (signal(SIGHUP, sig_handler) == SIG_IGN) signal(SIGHUP, SIG_IGN); if (signal(SIGTERM, sig_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN); // wait for conn, store peer in sout bind(s, (struct sockaddr *)&sin, sizeof(sin)); listen(s, 2); int c = accept(s, (struct sockaddr *)&sout, &tmp); tmp=1; if (setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &tmp, sizeof(tmp)) < 0) fprintf(stderr, "Error when disabling buffer..\n"); printf("Got connection from %s:%d, start sending..\n", inet_ntoa(sout.sin_addr), ntohs(sout.sin_port)); len = snprintf(line, 499, "%010d\n",cntr++); send(c, line, len+1,0); while (1) { if (fgets(line, 49, stdin)) { delay = atol(line); } else { if (argc > 1) exit(0); delay = 5000; } if (delay < 0) delay = 0; usleep(delay); len = snprintf(line, 499, "%010d\n",cntr++); send(c, line, len+1,0); } }
chandanmogal/ipsec-tfc
code/perfect-hiding-cc/tcpgen.c
C
gpl-3.0
2,149
----------------------------------- -- Area: Sauromugue Champaign (S) (98) -- Mob: Goblin_Flagman ----------------------------------- -- require("scripts/zones/Sauromugue_Champaign_[S]/MobIDs"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
Fatalerror66/ffxi-a
scripts/zones/Sauromugue_Champaign_[S]/mobs/Goblin_Flagman.lua
Lua
gpl-3.0
830
/* Copyright 2013-2015 Skytechnology sp. z o.o. This file is part of LizardFS. LizardFS 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, version 3. LizardFS 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 LizardFS. If not, see <http://www.gnu.org/licenses/>. */ #include "common/platform.h" #include <gtest/gtest.h> #include "common/chunk_read_planner.h" #include "unittests/chunk_type_constants.h" #include "unittests/plan_tester.h" static ChunkPartType xor_part(int level, int part) { return slice_traits::xors::ChunkPartType(level, part); } static void checkReadingChunk(std::map<ChunkPartType, std::vector<uint8_t>> &part_data, int first_block, int block_count, const ChunkReadPlanner::PartsContainer &available_parts) { ChunkReadPlanner planner; planner.prepare(first_block, block_count, available_parts); ASSERT_TRUE(planner.isReadingPossible()); std::unique_ptr<ReadPlan> plan = planner.buildPlan(); unittests::ReadPlanTester tester; std::cout << to_string(*plan) << std::endl; ASSERT_TRUE(tester.executePlan(std::move(plan), part_data) >= 0); EXPECT_TRUE(unittests::ReadPlanTester::compareBlocks( tester.output_buffer_, 0, part_data[slice_traits::standard::ChunkPartType()], first_block * MFSBLOCKSIZE, block_count)); } static void checkReadingChunk(int first_block, int block_count, const ChunkReadPlanner::PartsContainer &available_parts) { std::map<ChunkPartType, std::vector<uint8_t>> part_data; unittests::ReadPlanTester::buildData(part_data, available_parts); unittests::ReadPlanTester::buildData( part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()}); checkReadingChunk(part_data, first_block, block_count, available_parts); } /* TEST(ChunkReadPlannerTests, Unrecoverable1) { checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4}); } TEST(ChunkReadPlannerTests, Unrecoverable2) { checkUnrecoverable(xor_p_of_4, {xor_1_of_4, xor_2_of_4, xor_3_of_4}); } TEST(ChunkReadPlannerTests, Unrecoverable3) { checkUnrecoverable(xor_p_of_2, {xor_1_of_4, xor_2_of_4, xor_p_of_4}); } TEST(ChunkReadPlannerTests, Unrecoverable4) { checkUnrecoverable(xor_p_of_4, {xor_p_of_2}); } */ TEST(ChunkReadPlannerTests, VerifyRead1) { std::map<ChunkPartType, std::vector<uint8_t>> part_data; unittests::ReadPlanTester::buildData( part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)}); unittests::ReadPlanTester::buildData( part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()}); for (int i = 1; i <= 10; ++i) { checkReadingChunk(part_data, 0, i, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2), xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)}); } } TEST(ChunkReadPlannerTests, VerifyRead2) { std::map<ChunkPartType, std::vector<uint8_t>> part_data; unittests::ReadPlanTester::buildData( part_data, std::vector<ChunkPartType>{slice_traits::xors::ChunkPartType(5, 1)}); unittests::ReadPlanTester::buildData( part_data, std::vector<ChunkPartType>{slice_traits::standard::ChunkPartType()}); for (int i = 1; i <= 10; ++i) { checkReadingChunk(part_data, i, 2, {xor_part(5, 0), xor_part(5, 1), xor_part(5, 2), xor_part(5, 3), xor_part(5, 4), xor_part(5, 5)}); } } TEST(ChunkReadPlannerTests, VerifyRead3) { checkReadingChunk(0, 10, {xor_p_of_4, xor_2_of_4, xor_3_of_4, xor_4_of_4}); } TEST(ChunkReadPlannerTests, VerifyRead4) { checkReadingChunk(10, 100, {xor_p_of_7, xor_1_of_7, xor_2_of_7, xor_3_of_7, xor_4_of_7, xor_5_of_7, xor_6_of_7, xor_7_of_7}); }
lizardfs/lizardfs
src/common/chunk_read_planner_unittest.cc
C++
gpl-3.0
4,029
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Library functions for WIRIS plugin for Atto. * * @package tinymce * @subpackage tiny_mce_wiris * @copyright Maths for More S.L. <info@wiris.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); class tinymce_tiny_mce_wiris extends editor_tinymce_plugin { protected $buttons = array('tiny_mce_wiris_formulaEditor', 'tiny_mce_wiris_CAS'); protected function update_init_params(array &$params, context $context, array $options = null) { global $PAGE, $CFG; $PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/baseURL.js', false); // Add button after emoticon button in advancedbuttons3. $added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditor', '', false); $added = $this->add_button_after($params, 3, 'tiny_mce_wiris_formulaEditorChemistry', '', false); $added = $this->add_button_after($params, 3, 'tiny_mce_wiris_CAS', '', false); // Add JS file, which uses default name. $this->add_js_plugin($params); $filterwiris = $CFG->dirroot . '/filter/wiris/filter.php'; if (!file_exists($filterwiris)) { $PAGE->requires->js('/lib/editor/tinymce/plugins/tiny_mce_wiris/js/message.js', false); } } }
nitro2010/moodle
lib/editor/tinymce/plugins/tiny_mce_wiris/lib.php
PHP
gpl-3.0
2,050
var searchData= [ ['save_5fcomments',['save_comments',['../useful__functions_8php.html#af56aec073a82606e9a7dac498de28d96',1,'useful_functions.php']]], ['save_5fexperiment_5flist',['save_experiment_list',['../choose__experiments_8php.html#a5d24f39ae6c336d7828523216bce6fae',1,'choose_experiments.php']]], ['save_5fsessions',['save_sessions',['../useful__functions_8php.html#a38a4632f417ceaa2f1c09c3ed0494d5e',1,'useful_functions.php']]], ['save_5fsignup_5fto_5fdb',['save_signup_to_db',['../useful__functions_8php.html#a0dca9d754b1a0d7b5401c446878844c5',1,'useful_functions.php']]], ['save_5fuser_5fexpt_5fchoices',['save_user_expt_choices',['../useful__functions_8php.html#a461a04526110df604708381a9eac7da8',1,'useful_functions.php']]], ['signup_5fexists',['signup_exists',['../useful__functions_8php.html#a7cf6d3ac90a6fca8c3f595e68b6e62cc',1,'useful_functions.php']]] ];
mnd22/chaos-signup
html/search/functions_7.js
JavaScript
gpl-3.0
884
<?php /** * * ThinkUp/webapp/_lib/model/class.UserMySQLDAO.php * * Copyright (c) 2009-2013 Gina Trapani * * LICENSE: * * This file is part of ThinkUp (http://thinkup.com). * * ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any * later version. * * ThinkUp 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 ThinkUp. If not, see * <http://www.gnu.org/licenses/>. * * * User Data Access Object MySQL Implementation * * @license http://www.gnu.org/licenses/gpl.html * @copyright 2009-2013 Gina Trapani * @author Gina Trapani <ginatrapani[at]gmail[dot]com> * */ class UserMySQLDAO extends PDODAO implements UserDAO { /** * Get the SQL to generate average_tweets_per_day number * @TODO rename "tweets" "posts" * @return str SQL calcuation */ private function getAverageTweetCount() { return "round(post_count/(datediff(curdate(), joined)), 2) as avg_tweets_per_day"; } public function isUserInDB($user_id, $network) { $q = "SELECT user_id "; $q .= "FROM #prefix#users "; $q .= "WHERE user_id = :user_id AND network = :network;"; $vars = array( ':user_id'=>(string)$user_id, ':network'=>$network ); if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__); $ps = $this->execute($q, $vars); return $this->getDataIsReturned($ps); } public function isUserInDBByName($username, $network) { $q = "SELECT user_id "; $q .= "FROM #prefix#users "; $q .= "WHERE user_name = :username AND network = :network"; $vars = array( ':username'=>$username, ':network'=>$network ); if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__); $ps = $this->execute($q, $vars); return $this->getDataIsReturned($ps); } public function updateUsers($users_to_update) { $count = 0; $status_message = ""; if (sizeof($users_to_update) > 0) { $status_message .= count($users_to_update)." users queued for insert or update; "; foreach ($users_to_update as $user) { $count += $this->updateUser($user); } $status_message .= "$count users affected."; } $this->logger->logInfo($status_message, __METHOD__.','.__LINE__); $status_message = ""; return $count; } public function updateUser($user) { if (!isset($user->username)) { return 0; } $status_message = ""; $has_friend_count = $user->friend_count != '' ? true : false; $has_favorites_count = $user->favorites_count != '' ? true : false; $has_last_post = $user->last_post != '' ? true : false; $has_last_post_id = $user->last_post_id != '' ? true : false; $network = $user->network != '' ? $user->network : 'twitter'; $user->follower_count = $user->follower_count != '' ? $user->follower_count : 0; $user->post_count = $user->post_count != '' ? $user->post_count : 0; $vars = array( ':user_id'=>(string)$user->user_id, ':username'=>$user->username, ':full_name'=>$user->full_name, ':avatar'=>$user->avatar, ':location'=>$user->location, ':description'=>$user->description, ':url'=>$user->url, ':is_protected'=>$this->convertBoolToDB($user->is_protected), ':follower_count'=>$user->follower_count, ':post_count'=>$user->post_count, ':found_in'=>$user->found_in, ':joined'=>$user->joined, ':network'=>$user->network ); $is_user_in_storage = false; $is_user_in_storage = $this->isUserInDB($user->user_id, $user->network); if (!$is_user_in_storage) { $q = "INSERT INTO #prefix#users (user_id, user_name, full_name, avatar, location, description, url, "; $q .= "is_protected, follower_count, post_count, ".($has_friend_count ? "friend_count, " : "")." ". ($has_favorites_count ? "favorites_count, " : "")." ". ($has_last_post ? "last_post, " : "")." found_in, joined, network ". ($has_last_post_id ? ", last_post_id" : "").") "; $q .= "VALUES ( :user_id, :username, :full_name, :avatar, :location, :description, :url, :is_protected, "; $q .= ":follower_count, :post_count, ".($has_friend_count ? ":friend_count, " : "")." ". ($has_favorites_count ? ":favorites_count, " : "")." ". ($has_last_post ? ":last_post, " : "")." :found_in, :joined, :network ". ($has_last_post_id ? ", :last_post_id " : "")." )"; } else { $q = "UPDATE #prefix#users SET full_name = :full_name, avatar = :avatar, location = :location, "; $q .= "user_name = :username, description = :description, url = :url, is_protected = :is_protected, "; $q .= "follower_count = :follower_count, post_count = :post_count, ". ($has_friend_count ? "friend_count= :friend_count, " : "")." ". ($has_favorites_count ? "favorites_count= :favorites_count, " : "")." ". ($has_last_post ? "last_post= :last_post, " : "")." last_updated = NOW(), found_in = :found_in, "; $q .= "joined = :joined, network = :network ". ($has_last_post_id ? ", last_post_id = :last_post_id" : "")." "; $q .= "WHERE user_id = :user_id AND network = :network;"; } if ($has_friend_count) { $vars[':friend_count'] = $user->friend_count; } if ($has_favorites_count) { $vars[':favorites_count'] = $user->favorites_count; } if ($has_last_post) { $vars[':last_post'] = $user->last_post; } if ($has_last_post_id) { $vars[':last_post_id'] = $user->last_post_id; } if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__); $ps = $this->execute($q, $vars); $results = $this->getUpdateCount($ps); return $results; } public function getDetails($user_id, $network) { $q = "SELECT * , ".$this->getAverageTweetCount()." "; $q .= "FROM #prefix#users u "; $q .= "WHERE u.user_id = :user_id AND u.network = :network;"; $vars = array( ':user_id'=>(string)$user_id, ':network'=>$network ); if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__); $ps = $this->execute($q, $vars); return $this->getDataRowAsObject($ps, "User"); } public function getUserByName($user_name, $network) { $q = "SELECT * , ".$this->getAverageTweetCount()." "; $q .= "FROM #prefix#users u "; $q .= "WHERE u.user_name = :user_name AND u.network = :network"; $vars = array( ':user_name'=>$user_name, ':network'=>$network ); if ($this->profiler_enabled) Profiler::setDAOMethod(__METHOD__); $ps = $this->execute($q, $vars); return $this->getDataRowAsObject($ps, "User"); } }
agilee/ThinkUp
webapp/_lib/dao/class.UserMySQLDAO.php
PHP
gpl-3.0
7,596
main = f `x y` g
roberth/uu-helium
test/parser/BackQuoteMessage.hs
Haskell
gpl-3.0
17
# NgrxSimpleLab4 This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.1. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
iproduct/course-angular2
ngrx-simple-lab4/README.md
Markdown
gpl-3.0
1,031
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package VerilogCompiler.SyntacticTree; import VerilogCompiler.SemanticCheck.ErrorHandler; import VerilogCompiler.SemanticCheck.ExpressionType; import VerilogCompiler.SyntacticTree.Expressions.Expression; /** * * @author Néstor A. Bermúdez < nestor.bermudezs@gmail.com > */ public class Range extends VNode { Expression minValue; Expression maxValue; public Range(Expression minValue, Expression maxValue, int line, int column) { super(line, column); this.minValue = minValue; this.maxValue = maxValue; } public Expression getMinValue() { return minValue; } public void setMinValue(Expression minValue) { this.minValue = minValue; } public Expression getMaxValue() { return maxValue; } public void setMaxValue(Expression maxValue) { this.maxValue = maxValue; } @Override public String toString() { return String.format("[%s:%s]", this.minValue, this.maxValue); } @Override public ExpressionType validateSemantics() { ExpressionType minReturnType = minValue.validateSemantics(); ExpressionType maxReturnType = maxValue.validateSemantics(); if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER) { ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer"); } return null; } @Override public VNode getCopy() { return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column); } }
CastellarFrank/ArchSim
src/VerilogCompiler/SyntacticTree/Range.java
Java
gpl-3.0
1,723
import random from google.appengine.api import memcache from google.appengine.ext import ndb SHARD_KEY_TEMPLATE = 'shard-{}-{:d}' class GeneralCounterShardConfig(ndb.Model): num_shards = ndb.IntegerProperty(default=20) @classmethod def all_keys(cls, name): config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings] class GeneralCounterShard(ndb.Model): count = ndb.IntegerProperty(default=0) def get_count(name): total = memcache.get(name) if total is None: total = 0 parent_key = ndb.Key('ShardCounterParent', name) shard_query = GeneralCounterShard.query(ancestor=parent_key) shard_counters = shard_query.fetch(limit=None) for counter in shard_counters: if counter is not None: total += counter.count memcache.add(name, total, 7200) # 2 hours to expire return total def increment(name): config = GeneralCounterShardConfig.get_or_insert(name) return _increment(name, config.num_shards) @ndb.transactional def _increment(name, num_shards): index = random.randint(0, num_shards - 1) shard_key_string = SHARD_KEY_TEMPLATE.format(name, index) parent_key = ndb.Key('ShardCounterParent', name) counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key) if counter is None: counter = GeneralCounterShard(parent = parent_key, id=shard_key_string) counter.count += 1 counter.put() rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache if rval is None: return get_count(name) return rval @ndb.transactional def increase_shards(name, num_shards): config = GeneralCounterShardConfig.get_or_insert(name) if config.num_shards < num_shards: config.num_shards = num_shards config.put()
VirtuosoChris/appengine
experimental/shardcounter_sync.py
Python
gpl-3.0
2,052
'use strict'; var async = require('async'); var nconf = require('nconf'); var querystring = require('querystring'); var meta = require('../meta'); var pagination = require('../pagination'); var user = require('../user'); var topics = require('../topics'); var plugins = require('../plugins'); var helpers = require('./helpers'); var unreadController = module.exports; unreadController.get = function (req, res, next) { var page = parseInt(req.query.page, 10) || 1; var results; var cid = req.query.cid; var filter = req.query.filter || ''; var settings; async.waterfall([ function (next) { plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next); }, function (data, _next) { if (!data.filters[filter]) { return next(); } async.parallel({ watchedCategories: function (next) { helpers.getWatchedCategories(req.uid, cid, next); }, settings: function (next) { user.getSettings(req.uid, next); }, }, _next); }, function (_results, next) { results = _results; settings = results.settings; var start = Math.max(0, (page - 1) * settings.topicsPerPage); var stop = start + settings.topicsPerPage - 1; var cutoff = req.session.unreadCutoff ? req.session.unreadCutoff : topics.unreadCutoff(); topics.getUnreadTopics({ cid: cid, uid: req.uid, start: start, stop: stop, filter: filter, cutoff: cutoff, }, next); }, function (data, next) { user.blocks.filter(req.uid, data.topics, function (err, filtered) { data.topics = filtered; next(err, data); }); }, function (data) { data.title = meta.config.homePageTitle || '[[pages:home]]'; data.pageCount = Math.max(1, Math.ceil(data.topicCount / settings.topicsPerPage)); data.pagination = pagination.create(page, data.pageCount, req.query); if (settings.usePagination && (page < 1 || page > data.pageCount)) { req.query.page = Math.max(1, Math.min(data.pageCount, page)); return helpers.redirect(res, '/unread?' + querystring.stringify(req.query)); } data.categories = results.watchedCategories.categories; data.allCategoriesUrl = 'unread' + helpers.buildQueryString('', filter, ''); data.selectedCategory = results.watchedCategories.selectedCategory; data.selectedCids = results.watchedCategories.selectedCids; if (req.originalUrl.startsWith(nconf.get('relative_path') + '/api/unread') || req.originalUrl.startsWith(nconf.get('relative_path') + '/unread')) { data.title = '[[pages:unread]]'; data.breadcrumbs = helpers.buildBreadcrumbs([{ text: '[[unread:title]]' }]); } data.filters = helpers.buildFilters('unread', filter, req.query); data.selectedFilter = data.filters.find(function (filter) { return filter && filter.selected; }); res.render('unread', data); }, ], next); }; unreadController.unreadTotal = function (req, res, next) { var filter = req.query.filter || ''; async.waterfall([ function (next) { plugins.fireHook('filter:unread.getValidFilters', { filters: Object.assign({}, helpers.validFilters) }, next); }, function (data, _next) { if (!data.filters[filter]) { return next(); } topics.getTotalUnread(req.uid, filter, _next); }, function (data) { res.json(data); }, ], next); };
An-dz/NodeBB
src/controllers/unread.js
JavaScript
gpl-3.0
3,327
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. class Serializer(object): schemaless = True encapsulate = True registry = {} def __init__(self, query_params, pretty=False, **kwargs): self.pretty = pretty self._query_params = query_params self._fileName = None self._lastModified = None self._extra_args = kwargs @classmethod def register(cls, tag, serializer): cls.registry[tag] = serializer @classmethod def getAllFormats(cls): return list(cls.registry) @classmethod def create(cls, dformat, query_params=None, **kwargs): """ A serializer factory """ query_params = query_params or {} serializer = cls.registry.get(dformat) if serializer: return serializer(query_params, **kwargs) else: raise Exception("Serializer for '%s' does not exist!" % dformat) def getMIMEType(self): return self._mime def set_headers(self, response): response.content_type = self.getMIMEType() def __call__(self, obj, *args, **kwargs): self._obj = obj self._data = self._execute(obj, *args, **kwargs) return self._data from indico.web.http_api.metadata.json import JSONSerializer from indico.web.http_api.metadata.xml import XMLSerializer
belokop/indico_bare
indico/web/http_api/metadata/serializer.py
Python
gpl-3.0
2,039
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Sales\Model\Spi; /** * Interface ResourceInterface */ interface OrderPaymentResourceInterface { /** * Save object data * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ public function save(\Magento\Framework\Model\AbstractModel $object); /** * Load an object * * @param mixed $value * @param \Magento\Framework\Model\AbstractModel $object * @param string|null $field field to load by (defaults to model id) * @return mixed */ public function load(\Magento\Framework\Model\AbstractModel $object, $value, $field = null); /** * Delete the object * * @param \Magento\Framework\Model\AbstractModel $object * @return mixed */ public function delete(\Magento\Framework\Model\AbstractModel $object); }
rajmahesh/magento2-master
vendor/magento/module-sales/Model/Spi/OrderPaymentResourceInterface.php
PHP
gpl-3.0
959
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. package android.renderscript.cts; import android.renderscript.Allocation; import android.renderscript.RSRuntimeException; import android.renderscript.Element; public class TestAsin extends RSBaseCompute { private ScriptC_TestAsin script; private ScriptC_TestAsinRelaxed scriptRelaxed; @Override protected void setUp() throws Exception { super.setUp(); script = new ScriptC_TestAsin(mRS); scriptRelaxed = new ScriptC_TestAsinRelaxed(mRS); } public class ArgumentsFloatFloat { public float inV; public Target.Floaty out; } private void checkAsinFloatFloat() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x80b5674ff98b5a12l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); script.forEach_testAsinFloatFloat(inV, out); verifyResultsAsinFloatFloat(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); scriptRelaxed.forEach_testAsinFloatFloat(inV, out); verifyResultsAsinFloatFloat(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString()); } } private void verifyResultsAsinFloatFloat(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 1]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 1]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 1 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 1 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 1 + j], Float.floatToRawIntBits(arrayOut[i * 1 + j]), arrayOut[i * 1 + j])); if (!args.out.couldBe(arrayOut[i * 1 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloatFloat" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat2Float2() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x9e11e5e823f7cce6l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); script.forEach_testAsinFloat2Float2(inV, out); verifyResultsAsinFloat2Float2(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat2Float2(inV, out); verifyResultsAsinFloat2Float2(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString()); } } private void verifyResultsAsinFloat2Float2(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 2]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 2]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 2 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 2 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 2 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 2 + j], Float.floatToRawIntBits(arrayOut[i * 2 + j]), arrayOut[i * 2 + j])); if (!args.out.couldBe(arrayOut[i * 2 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat2Float2" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat3Float3() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x9e13af031a12edc4l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); script.forEach_testAsinFloat3Float3(inV, out); verifyResultsAsinFloat3Float3(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat3Float3(inV, out); verifyResultsAsinFloat3Float3(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString()); } } private void verifyResultsAsinFloat3Float3(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 4]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 3 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat3Float3" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat4Float4() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x9e15781e102e0ea2l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); script.forEach_testAsinFloat4Float4(inV, out); verifyResultsAsinFloat4Float4(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat4Float4(inV, out); verifyResultsAsinFloat4Float4(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString()); } } private void verifyResultsAsinFloat4Float4(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 4]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 4 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat4Float4" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } public void testAsin() { checkAsinFloatFloat(); checkAsinFloat2Float2(); checkAsinFloat3Float3(); checkAsinFloat4Float4(); } }
s20121035/rk3288_android5.1_repo
cts/tests/tests/renderscript/src/android/renderscript/cts/TestAsin.java
Java
gpl-3.0
13,539
#!/usr/bin/perl # $Id: Chain.pm,v 1.12 2001/06/18 08:27:53 heikki Exp $ # # bioperl module for Bio::LiveSeq::Chain # # Cared for by Joseph Insana <insana@ebi.ac.uk> <jinsana@gmx.net> # # Copyright Joseph Insana # # You may distribute this module under the same terms as perl itself # # POD documentation - main docs before the code # =head1 NAME Bio::LiveSeq::Chain - DoubleChain DataStructure for Perl =head1 SYNOPSIS #documentation needed =head1 DESCRIPTION This is a general purpose module (that's why it's not in object-oriented form) that introduces a novel datastructure in PERL. It implements the "double linked chain". The elements of the chain can contain basically everything. From chars to strings, from object references to arrays or hashes. It is used in the LiveSequence project to create a dynamical DNA sequence, easier to manipulate and change. It's use is mainly for sequence variation analysis but it could be used - for example - in e-cell projects. The Chain module in itself doesn't have any biological bias, so can be used for any programming purpose. Each element of the chain (with the exclusion of the first and the last of the chain) is connected to other two elements (the PREVious and the NEXT one). There is no absolute position (like in an array), hence if positions are important, they need to be computed (methods are provided). Otherwise it's easy to keep track of the elements with their "LABELs". There is one LABEL (think of it as a pointer) to each ELEMENT. The labels won't change after insertions or deletions of the chain. So it's always possible to retrieve an element even if the chain has been modified by successive insertions or deletions. From this the high potential profit for bioinformatics: dealing with sequences in a way that doesn't have to rely on positions, without the need of constantly updating them if the sequence changes, even dramatically. =head1 AUTHOR - Joseph A.L. Insana Email: Insana@ebi.ac.uk, jinsana@gmx.net Address: EMBL Outstation, European Bioinformatics Institute Wellcome Trust Genome Campus, Hinxton Cambs. CB10 1SD, United Kingdom =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut # Let the code begin... # DoubleChain Data Structure for PERL # by Joseph A.L. Insana - Deathson - Filius Mortis - Fal Mortais # insana@ebi.ac.uk, jinsana@gmx.net package Bio::LiveSeq::Chain; # Version history: # Fri Mar 10 16:46:51 GMT 2000 v1.0 begun working on chains in perl # Sat Mar 11 05:47:21 GMT 2000 v.1.4 working on splice method # Sun Mar 12 14:08:31 GMT 2000 v.1.5 # Sun Mar 12 17:21:51 GMT 2000 v.2.0 splice method working, is_updownstream made # Sun Mar 12 18:11:22 GMT 2000 v.2.04 wrapped all in package Chain.pm # Sun Mar 12 18:49:23 GMT 2000 v.2.08 added elements() # Sun Mar 12 21:18:04 GMT 2000 v.2.1 done array2dchain, working on *insert* # Sun Mar 12 23:04:40 GMT 2000 v.2.16 done *insert*, up_element, create_elems # Sun Mar 12 23:45:32 GMT 2000 v.2.17 debugged and checked # Mon Mar 13 00:44:51 GMT 2000 v.2.2 added mutate() # Mon Mar 13 02:00:32 GMT 2000 v 2.21 added invert_dchain() # Mon Mar 13 03:01:21 GMT 2000 v 2.22 created updown_chain2string # Mon Mar 13 03:45:50 GMT 2000 v.2.24 added subchain_length() # Mon Mar 13 17:25:04 GMT 2000 v.2.26 added element_at_pos and pos_of_element # Wed Mar 15 23:05:06 GMT 2000 v.2.27 use strict enforced # Thu Mar 16 19:05:34 GMT 2000 v.2.3 changed dchain->chain everywhere # Fri Mar 17 01:48:36 GMT 2000 v.2.33 mutate_element renamed, created new # methods: set_value, get_value... # Fri Mar 17 05:03:15 GMT 2000 v.2.4 set_value_at_pos, get_value_at_pos # get_label_at_pos... # Fri Mar 17 15:51:07 GMT 2000 v.2.41 renamed pos_of_element -> get_pos_of_label # Fri Mar 17 18:10:36 GMT 2000 v.2.44 recoded subchain_length and pos_of_label # Fri Mar 17 20:12:27 GMT 2000 v.2.5 NAMING change: index->label everywhere # Mon Mar 20 18:33:10 GMT 2000 v.2.52 label_exists(), start(), end() # Mon Mar 20 23:10:28 GMT 2000 v.2.6 labels() created # Wed Mar 22 18:35:17 GMT 2000 v.2.61 chain2string() rewritten # Tue Dec 12 14:47:58 GMT 2000 v 2.66 optimized with /use integer/ # Tue Dec 12 16:28:45 GMT 2000 v 2.7 rewritten comments to methods in pod style # $VERSION=2.7; # # TODO_list: # **** cleanup code # **** performance concerns # *??* create hash2dchain ???? (with hashkeys used for label) # **????** how about using array of arrays instead than hash of arrays?? # # further strict complaints: # in verbose $string assignment around line 721 ??? # TERMINOLOGY update, naming convention: # "chain" the datastructure # "element" the individual units that compose a chain # "label" the unique name of a single element # "position" the position of an element into the chain according to a # particular coordinate system (e.g. counting from the start) # "value" what is stored in a single element use Carp qw(croak cluck carp); # as of 2.3 use strict; # as of 2.27 use integer; # WARNING: this is to increase performance # a little bit of attention has to be given if float need to # be stored as elements of the array # the use of this "integer" affects all operations but not # assignments. So float CAN be assigned as elements of the chain # BUT, if you assign $z=-1.8;, $z will be equal to -1 because # "-" counts as a unary operation! =head2 _updown_chain2string Title : chain2string Usage : $string = Bio::LiveSeq::Chain::chain2string("down",$chain,6,9) Function: reads the contents of the chain, outputting a string Returns : a string Examples: : down_chain2string($chain) -> all the chain from begin to end : down_chain2string($chain,6) -> from 6 to the end : down_chain2string($chain,6,4) -> from 6, going on 4 elements : down_chain2string($chain,6,"",10) -> from 6 to 10 : up_chain2string($chain,10,"",6) -> from 10 to 6 upstream Defaults: start=first element; if len undef, goes to last if last undef, goes to end if last defined, it overrides len (undefining it) Error code: -1 Args : "up"||"down" as first argument to specify the reading direction reference (to the chain) [first] [len] [last] optional integer arguments to specify how much and from (and to) where to read =cut # methods rewritten 2.61 sub up_chain2string { _updown_chain2string("up",@_); } sub down_chain2string { _updown_chain2string("down",@_); } sub _updown_chain2string { my ($direction,$chain,$first,$len,$last)=@_; unless($chain) { cluck "no chain input"; return (-1); } my $begin=$chain->{'begin'}; # the label of the BEGIN element my $end=$chain->{'end'}; # the label of the END element my $flow; if ($direction eq "up") { $flow=2; # used to determine the direction of chain navigation unless ($first) { $first=$end; } # if undef or 0, use $end } else { # defaults to "down" $flow=1; # used to determine the direction of chain navigation unless ($first) { $first=$begin; } # if undef or 0, use $begin } unless($chain->{$first}) { cluck "label for first not defined"; return (-1); } if ($last) { # if last is defined, it gets priority and len is not used unless($chain->{$last}) { cluck "label for last not defined"; return (-1); } if ($len) { warn "Warning chain2string: argument LAST:$last overriding LEN:$len!"; undef $len; } } else { if ($direction eq "up") { $last=$begin; # if last not defined, go 'till begin (or upto len elements) } else { $last=$end; # if last not defined, go 'till end (or upto len elements) } } my ($string,@array); my $label=$first; my $i=1; my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef unless (defined $afterlast) { $afterlast=0; } # keep strict happy # proceed for len elements or until last, whichever comes first # if $len undef goes till end while (($label) && ($label != $afterlast) && ($i <= ($len || $i + 1))) { @array=@{$chain->{$label}}; $string .= $array[0]; $label = $array[$flow]; $i++; } return ($string); # if chain is interrupted $string won't be complete } =head2 _updown_labels Title : labels Usage : @labels = Bio::LiveSeq::Chain::_updown_labels("down",$chain,4,16) Function: returns all the labels in a chain or those between two specified ones (termed "first" and "last") Returns : a reference to an array containing the labels Args : "up"||"down" as first argument to specify the reading direction reference (to the chain) [first] [last] (integer for the starting and eneding labels) =cut # arguments: CHAIN_REF [FIRSTLABEL] [LASTLABEL] # returns: reference to array containing the labels sub down_labels { my ($chain,$first,$last)=@_; _updown_labels("down",$chain,$first,$last); } sub up_labels { my ($chain,$first,$last)=@_; _updown_labels("up",$chain,$first,$last); } # arguments: "up"||"down" CHAIN_REF [FIRSTLABEL] [LASTLABEL] # returns: reference to array containing the labels sub _updown_labels { my ($direction,$chain,$first,$last)=@_; unless($chain) { cluck "no chain input"; return (0); } my $begin=$chain->{'begin'}; # the label of the BEGIN element my $end=$chain->{'end'}; # the label of the END element my $flow; if ($direction eq "up") { $flow=2; unless ($first) { $first=$end; } unless ($last) { $last=$begin; } } else { $flow=1; unless ($last) { $last=$end; } unless ($first) { $first=$begin; } } unless($chain->{$first}) { warn "not existing label $first"; return (0); } unless($chain->{$last}) { warn "not existing label $last"; return (0); } my $label=$first; my @labels; my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef unless (defined $afterlast) { $afterlast=0; } # keep strict happy while (($label)&&($label != $afterlast)) { push(@labels,$label); $label=$chain->{$label}[$flow]; } return (\@labels); # if chain is interrupted @labels won't be complete } =head2 start Title : start Usage : $start = Bio::LiveSeq::Chain::start() Returns : the label marking the start of the chain Errorcode: -1 Args : none =cut sub start { my $chain=$_[0]; unless($chain) { cluck "no chain input"; return (-1); } return ($chain->{'begin'}); } =head2 end Title : end Usage : $end = Bio::LiveSeq::Chain::end() Returns : the label marking the end of the chain Errorcode: -1 Args : none =cut sub end { my $chain=$_[0]; unless($chain) { cluck "no chain input"; return (-1); } return ($chain->{'end'}); } =head2 label_exists Title : label_exists Usage : $check = Bio::LiveSeq::Chain::label_exists($chain,$label) Function: It checks if a label is defined, i.e. if an element is there or is not there anymore Returns : 1 if the label exists, 0 if it is not there, -1 error Errorcode: -1 Args : reference to the chain, integer =cut sub label_exists { my ($chain,$label)=@_; unless($chain) { cluck "no chain input"; return (-1); } if ($label && $chain->{$label}) { return (1); } else { return (0) }; } =head2 down_get_pos_of_label Title : down_get_pos_of_label Usage : $position = Bio::LiveSeq::Chain::down_get_pos_of_label($chain,$label,$first) Function: returns the position of $label counting from $first, i.e. taking $first as 1 of coordinate system. If $first is not specified it will count from the start of the chain. Returns : Errorcode: 0 Args : reference to the chain, integer (the label of interest) optional: integer (a different label that will be taken as the first one, i.e. the one to count from) Note: It counts "downstream". To proceed backward use up_get_pos_of_label =cut sub down_get_pos_of_label { #down_chain2string($_[0],$_[2],undef,$_[1],"counting"); my ($chain,$label,$first)=@_; _updown_count("down",$chain,$first,$label); } sub up_get_pos_of_label { #up_chain2string($_[0],$_[2],undef,$_[1],"counting"); my ($chain,$label,$first)=@_; _updown_count("up",$chain,$first,$label); } =head2 down_subchain_length Title : down_subchain_length Usage : $length = Bio::LiveSeq::Chain::down_subchain_length($chain,$first,$last) Function: returns the length of the chain between the labels "first" and "last", included Returns : integer Errorcode: 0 Args : reference to the chain, integer, integer Note: It counts "downstream". To proceed backward use up_subchain_length =cut # arguments: chain_ref [first] [last] # returns the length of the chain between first and last (included) sub down_subchain_length { #down_chain2string($_[0],$_[1],undef,$_[2],"counting"); my ($chain,$first,$last)=@_; _updown_count("down",$chain,$first,$last); } sub up_subchain_length { #up_chain2string($_[0],$_[1],undef,$_[2],"counting"); my ($chain,$first,$last)=@_; _updown_count("up",$chain,$first,$last); } # arguments: DIRECTION CHAIN_REF FIRSTLABEL LASTLABEL # errorcode 0 sub _updown_count { my ($direction,$chain,$first,$last)=@_; unless($chain) { cluck "no chain input"; return (0); } my $begin=$chain->{'begin'}; # the label of the BEGIN element my $end=$chain->{'end'}; # the label of the END element my $flow; if ($direction eq "up") { $flow=2; unless ($first) { $first=$end; } unless ($last) { $last=$begin; } } else { $flow=1; unless ($last) { $last=$end; } unless ($first) { $first=$begin; } } unless($chain->{$first}) { warn "not existing label $first"; return (0); } unless($chain->{$last}) { warn "not existing label $last"; return (0); } my $label=$first; my $count; my $afterlast=$chain->{$last}[$flow]; # if last=end, afterlast is undef unless (defined $afterlast) { $afterlast=0; } # keep strict happy while (($label)&&($label != $afterlast)) { $count++; $label=$chain->{$label}[$flow]; } return ($count); # if chain is interrupted, $i will be up to the breaking point } =head2 invert_chain Title : invert_chain Usage : $errorcode=Bio::LiveSeq::Chain::invert_chain($chain) Function: completely inverts the order of the chain elements; begin is swapped with end and all links updated (PREV&NEXT fields swapped) Returns : 1 if all OK, 0 if errors Errorcode: 0 Args : reference to the chain =cut sub invert_chain { my $chain=$_[0]; unless($chain) { cluck "no chain input"; return (0); } my $begin=$chain->{'begin'}; # the name of the first element my $end=$chain->{'end'}; # the name of the last element my ($label,@array); $label=$begin; # starts from the beginning while ($label) { # proceed with linked elements, swapping PREV and NEXT @array=@{$chain->{$label}}; ($chain->{$label}[1],$chain->{$label}[2])=($array[2],$array[1]); # swap $label = $array[1]; # go to the next one } # now swap begin and end fields ($chain->{'begin'},$chain->{'end'})=($end,$begin); return (1); # that's it } # warning that method has changed name #sub mutate_element { #croak "Warning: old method name. Please update code to 'set_value_at_label'\n"; # &set_value_at_label; #} =head2 down_get_value_at_pos Title : down_get_value_at_pos Usage : $value = Bio::LiveSeq::Chain::down_get_value_at_pos($chain,$position,$first) Function: used to access the value of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified Returns : whatever is stored in the element of the chain Errorcode: 0 Args : reference to the chain, integer, [integer] Note: It works "downstream". To proceed backward use up_get_value_at_pos =cut #sub get_value_at_pos { #croak "Please use instead: down_get_value_at_pos"; ##&down_get_value_at_pos; #} sub down_get_value_at_pos { my ($chain,$position,$first)=@_; my $label=down_get_label_at_pos($chain,$position,$first); # check place of change if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist warn "not existing element $label"; return (0); } return _get_value($chain,$label); } sub up_get_value_at_pos { my ($chain,$position,$first)=@_; my $label=up_get_label_at_pos($chain,$position,$first); # check place of change if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist warn "not existing element $label"; return (0); } return _get_value($chain,$label); } =head2 down_set_value_at_pos Title : down_set_value_at_pos Usage : $errorcode = Bio::LiveSeq::Chain::down_set_value_at_pos($chain,$newvalue,$position,$first) Function: used to store a new value inside an element of the chain at a particular position instead than directly with a label pointer. It will count the position from the start of the chain or from the label $first, if $first is specified Returns : 1 Errorcode: 0 Args : reference to the chain, newvalue, integer, [integer] (newvalue can be: integer, string, object reference, hash ref) Note: It works "downstream". To proceed backward use up_set_value_at_pos Note2: If the $newvalue is undef, it will delete the contents of the element but it won't remove the element from the chain. =cut #sub set_value_at_pos { #croak "Please use instead: down_set_value_at_pos"; ##&down_set_value_at_pos; #} sub down_set_value_at_pos { my ($chain,$value,$position,$first)=@_; my $label=down_get_label_at_pos($chain,$position,$first); # check place of change if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist warn "not existing element $label"; return (0); } _set_value($chain,$label,$value); return (1); } sub up_set_value_at_pos { my ($chain,$value,$position,$first)=@_; my $label=up_get_label_at_pos($chain,$position,$first); # check place of change if (($label eq -1)||($label eq 0)) { # complain if label doesn't exist warn "not existing element $label"; return (0); } _set_value($chain,$label,$value); return (1); } =head2 down_set_value_at_label Title : down_set_value_at_label Usage : $errorcode = Bio::LiveSeq::Chain::down_set_value_at_label($chain,$newvalue,$label) Function: used to store a new value inside an element of the chain defined by its label. Returns : 1 Errorcode: 0 Args : reference to the chain, newvalue, integer (newvalue can be: integer, string, object reference, hash ref) Note: It works "downstream". To proceed backward use up_set_value_at_label Note2: If the $newvalue is undef, it will delete the contents of the element but it won't remove the element from the chain. =cut sub set_value_at_label { my ($chain,$value,$label)=@_; unless($chain) { cluck "no chain input"; return (0); } # check place of change unless($chain->{$label}) { # complain if label doesn't exist warn "not existing element $label"; return (0); } _set_value($chain,$label,$value); return (1); } =head2 down_get_value_at_label Title : down_get_value_at_label Usage : $value = Bio::LiveSeq::Chain::down_get_value_at_label($chain,$label) Function: used to access the value of the chain from one element defined by its label. Returns : whatever is stored in the element of the chain Errorcode: 0 Args : reference to the chain, integer Note: It works "downstream". To proceed backward use up_get_value_at_label =cut sub get_value_at_label { my $chain=$_[0]; unless($chain) { cluck "no chain input"; return (0); } my $label = $_[1]; # the name of the element # check place of change unless($chain->{$label}) { # complain if label doesn't exist warn "not existing label $label"; return (0); } return _get_value($chain,$label); } # arguments: CHAIN_REF LABEL VALUE sub _set_value { my ($chain,$label,$value)=@_; $chain->{$label}[0]=$value; } # arguments: CHAIN_REF LABEL sub _get_value { my ($chain,$label)=@_; return $chain->{$label}[0]; } =head2 down_get_label_at_pos Title : down_get_label_at_pos Usage : $label = Bio::LiveSeq::Chain::down_get_label_at_pos($chain,$position,$first) Function: used to retrieve the label of an an element of the chain at a particular position. It will count the position from the start of the chain or from the label $first, if $first is specified Returns : integer Errorcode: 0 Args : reference to the chain, integer, [integer] Note: It works "downstream". To proceed backward use up_get_label_at_pos =cut # arguments: CHAIN_REF POSITION [FIRST] # returns: LABEL of element found counting from FIRST sub down_get_label_at_pos { _updown_get_label_at_pos("down",@_); } sub up_get_label_at_pos { _updown_get_label_at_pos("up",@_); } # arguments: [DIRECTION] CHAIN_REF POSITION [FIRST] # Default DIRECTION="down" # if FIRST is undefined, FIRST=START (if DIRECTION=down) or FIRST=END (up) sub _updown_get_label_at_pos { my ($direction,$chain,$position,$first)=@_; unless($chain) { cluck "no chain input"; return (0); } my $begin=$chain->{'begin'}; # the label of the BEGIN element my $end=$chain->{'end'}; # the label of the END element my $flow; if ($direction eq "up") { $flow=2; unless ($first) { $first=$end; } } else { $flow=1; unless ($first) { $first=$begin; } } unless($chain->{$first}) { warn "not existing label $first"; return (0); } my $label=$first; my $i=1; while ($i < $position) { $label=$chain->{$label}[$flow]; $i++; unless ($label) { return (0); } # chain ended before position reached } return ($label); } # for english_concerned, latin_unconcerned people sub preinsert_string { &praeinsert_string } sub preinsert_array { &praeinsert_array } # praeinsert_string CHAIN_REF STRING [POSITION] # the chars of STRING are passed to praeinsert_array # the chars are inserted in CHAIN, before POSITION # if POSITION is undef, default is to prepend the string to the beginning # i.e. POSITION is START of CHAIN sub praeinsert_string { my @string=split(//,$_[1]); praeinsert_array($_[0],\@string,$_[2]); } # postinsert_string CHAIN_REF STRING [POSITION] # the chars of STRING are passed to postinsert_array # the chars are inserted in CHAIN, after POSITION # if POSITION is undef, default is to append the string to the end # i.e. POSITION is END of CHAIN sub postinsert_string { my @string=split(//,$_[1]); postinsert_array($_[0],\@string,$_[2]); } # praeinsert_array CHAIN_REF ARRAY_REF [POSITION] # the elements of ARRAY are inserted in CHAIN, before POSITION # if POSITION is undef, default is to prepend the elements to the beginning # i.e. POSITION is START of CHAIN sub praeinsert_array { _praepostinsert_array($_[0],"prae",$_[1],$_[2]); } # postinsert_array CHAIN_REF ARRAY_REF [POSITION] # the elements of ARRAY are inserted in CHAIN, after POSITION # if POSITION is undef, default is to append the elements to the end # i.e. POSITION is END of CHAIN sub postinsert_array { _praepostinsert_array($_[0],"post",$_[1],$_[2]); } =head2 _praepostinsert_array Title : _praepostinsert_array Usage : ($insbegin,$insend) = Bio::LiveSeq::Chain::_praepostinsert_array($chainref,"post",$arrayref,$position) Function: the elements of the array specified by $arrayref are inserted (creating a new subchain) in the chain specified by $chainref, before or after (depending on the "prae"||"post" keyword passed as second argument) the specified position. Returns : two labels: the first and the last of the inserted subchain Defaults: if no position is specified, the new chain will be inserted after (post) the first element of the chain Errorcode: 0 Args : chainref, "prae"||"post", arrayref, integer (position) =cut # returns: 0 if errors, otherwise returns references of begin and end of # the insertion sub _praepostinsert_array { my $chain=$_[0]; unless($chain) { cluck "no chain input"; return (0); } my $praepost=$_[1] || "post"; # defaults to post my ($prae,$post); my $position=$_[3]; my $begin=$chain->{'begin'}; # the name of the first element of the chain my $end=$chain->{'end'}; # the name of the the last element of the chain # check if prae or post insertion and prepare accordingly if ($praepost eq "prae") { $prae=1; unless (($position eq 0)||($position)) { $position=$begin; } # if undef, use $begin } else { $post=1; unless (($position eq 0)||($position)) { $position=$end; } # if undef, use $end } # check place of insertion unless($chain->{$position}) { # complain if position doesn't exist warn ("Warning _praepostinsert_array: not existing element $position"); return (0); } # check if there are elements to insert my $elements=$_[2]; # reference to the array containing the new elements my $elements_count=scalar(@{$elements}); unless ($elements_count) { warn ("Warning _praepostinsert_array: no elements input"); return (0); } # create new chainelements with offset=firstfree(chain) my ($insertbegin,$insertend)=_create_chain_elements($chain,$elements); # DEBUGGING #print "Executing ${praepost}insertion of $elements_count elements ('@{$elements}') at position: $position\n"; # attach the new chain to the old chain # 4 cases: prae@begin, prae@middle, post@middle, post@end # NOTE: in case of double joinings always join wisely so not to # delete the PREV/NEXT attribute before it is needed my $noerror=1; if ($prae) { if ($position==$begin) { # 1st case: prae@begin $noerror=_join_chain_elements($chain,$insertend,$begin); $chain->{'begin'}=$insertbegin; } else { # 2nd case: prae@middle $noerror=_join_chain_elements($chain,up_element($chain,$position),$insertbegin); $noerror=_join_chain_elements($chain,$insertend,$position); } } elsif ($post) { if ($position==$end) { # 4th case: post@end $noerror=_join_chain_elements($chain,$end,$insertbegin); $chain->{'end'}=$insertend; } else { # 3rd case: post@middle # note the order of joins (important) $noerror=_join_chain_elements($chain,$insertend,down_element($chain,$position)); $noerror=_join_chain_elements($chain,$position,$insertbegin); } } else { # this should never happen die "_praepostinsert_array: Something went very wrong"; } # check for errors and return begin,end of insertion if ($noerror) { return ($insertbegin,$insertend); } else { # something went wrong with the joinings warn "Warning _praepostinsert_array: Joining of insertion failed"; return (0); } } # create new chain elements with offset=firstfree # arguments: CHAIN_REF ARRAY_REF # returns: pointers to BEGIN and END of new chained elements created # returns 0 if error(s) encountered sub _create_chain_elements { my $chain=$_[0]; unless($chain) { warn ("Warning _create_chain_elements: no chain input"); return (0); } my $arrayref=$_[1]; my $array_count=scalar(@{$arrayref}); unless ($array_count) { warn ("Warning _create_chain_elements: no elements input"); return (0); } my $begin=$chain->{'firstfree'}; my $i=$begin-1; my $element; foreach $element (@{$arrayref}) { $i++; $chain->{$i}=[$element,$i+1,$i-1]; } my $end=$i; $chain->{'firstfree'}=$i+1; # what a new added element should be called $chain->{'size'} += $end-$begin+1; # increase size of chain # leave sticky edges (to be joined by whoever called this subroutine) $chain->{$begin}[2]=undef; $chain->{$end}[1]=undef; return ($begin,$end); # return pointers to first and last of the newelements } # argument: CHAIN_REF ELEMENT # returns: name of DOWN/NEXT element (the downstream one) # returns -1 if error encountered (e.g. chain or elements undefined) # returns 0 if there's no DOWN element sub down_element { _updown_element("down",@_); } # argument: CHAIN_REF ELEMENT # returns: name of UP/PREV element (the upstream one) # returns -1 if error encountered (e.g. chain or elements undefined) # returns 0 if there's no UP element sub up_element { _updown_element("up",@_); } # used by both is_up_element and down_element sub _updown_element { my $direction=$_[0] || "down"; # defaults to downstream my $flow; if ($direction eq "up") { $flow=2; # used to determine the direction of chain navigation } else { $flow=1; # used to determine the direction of chain navigation } my $chain=$_[1]; unless($chain) { warn ("Warning ${direction}_element: no chain input"); return (-1); } my $me = $_[2]; # the name of the element my $it = $chain->{$me}[$flow]; # the prev||next one, upstream||downstream if ($it) { return ($it); # return the name of prev||next element } else { return (0); # there is no prev||next element ($it is undef) } } # used by both is_downstream and is_upstream sub _is_updownstream { my $direction=$_[0] || "down"; # defaults to downstream my $flow; if ($direction eq "up") { $flow=2; # used to determine the direction of chain navigation } else { $flow=1; # used to determine the direction of chain navigation } my $chain=$_[1]; unless($chain) { warn ("Warning is_${direction}stream: no chain input"); return (-1); } my $first=$_[2]; # the name of the first element my $second=$_[3]; # the name of the first element if ($first==$second) { warn ("Warning is_${direction}stream: first==second!!"); return (0); } unless($chain->{$first}) { warn ("Warning is_${direction}stream: first element not defined"); return (-1); } unless($chain->{$second}) { warn ("Warning is_${direction}stream: second element not defined"); return (-1); } my ($label,@array); $label=$first; my $found=0; while (($label)&&(!($found))) { # searches till the end or till found if ($label==$second) { $found=1; } @array=@{$chain->{$label}}; $label = $array[$flow]; # go to the prev||next one, upstream||downstream } return $found; } =head2 is_downstream Title : is_downstream Usage : Bio::LiveSeq::Chain::is_downstream($chainref,$firstlabel,$secondlabel) Function: checks if SECONDlabel follows FIRSTlabel It runs downstream the elements of the chain from FIRST searching for SECOND. Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it reaches the end of the chain without having found it) Errorcode -1 Args : two labels (integer) =cut sub is_downstream { _is_updownstream("down",@_); } =head2 is_upstream Title : is_upstream Usage : Bio::LiveSeq::Chain::is_upstream($chainref,$firstlabel,$secondlabel) Function: checks if SECONDlabel follows FIRSTlabel It runs upstream the elements of the chain from FIRST searching for SECOND. Returns : 1 if SECOND is found /after/ FIRST; 0 otherwise (i.e. if it reaches the end of the chain without having found it) Errorcode -1 Args : two labels (integer) =cut sub is_upstream { _is_updownstream("up",@_); } =head2 check_chain Title : check_chain Usage : @errorcodes = Bio::LiveSeq::Chain::check_chain() Function: a wraparound to a series of check for consistency of the chain It will check for boundaries, size, backlinking and forwardlinking Returns : array of 4 warn codes, each can be 1 (all ok) or 0 (something wrong) Errorcode: 0 Args : none Note : this is slow and through. It is not really needed. It is mostly a code-developer tool. =cut sub check_chain { my $chain=$_[0]; unless($chain) { warn ("Warning check_chain: no chain input"); return (-1); } my ($warnbound,$warnsize,$warnbacklink,$warnforlink); $warnbound=&_boundcheck; # passes on the arguments of the subroutine $warnsize=&_sizecheck; $warnbacklink=&_downlinkcheck; $warnforlink=&_uplinkcheck; return ($warnbound,$warnsize,$warnbacklink,$warnforlink); } # consistency check for forwardlinks walking upstream # argument: a chain reference # returns: 1 all OK 0 problems sub _uplinkcheck { _updownlinkcheck("up",@_); } # consistency check for backlinks walking downstream # argument: a chain reference # returns: 1 all OK 0 problems sub _downlinkcheck { _updownlinkcheck("down",@_); } # consistency check for links, common to _uplinkcheck and _downlinkcheck # argument: "up"||"down", check_ref # returns: 1 all OK 0 problems sub _updownlinkcheck { my $direction=$_[0] || "down"; # defaults to downstream my ($flow,$wolf); my $chain=$_[1]; unless($chain) { warn ("Warning _${direction}linkcheck: no chain input"); return (0); } my $begin=$chain->{'begin'}; # the name of the first element my $end=$chain->{'end'}; # the name of the last element my ($label,@array,$me,$it,$itpoints); if ($direction eq "up") { $flow=2; # used to determine the direction of chain navigation $wolf=1; $label=$end; # start from end } else { $flow=1; # used to determine the direction of chain navigation $wolf=2; $label=$begin; # start from beginning } my $warncode=1; while ($label) { # proceed with linked elements, checking neighbours $me=$label; @array=@{$chain->{$label}}; $label = $array[$flow]; # go to the next one $it=$label; if ($it) { # no sense in checking if next one not defined (END element) @array=@{$chain->{$label}}; $itpoints=$array[$wolf]; unless ($me==$itpoints) { warn "Warning: ${direction}LinkCheck: LINK wrong in $it, that doesn't point back to me ($me). It points to $itpoints\n"; $warncode=0; } } } return $warncode; } # consistency check for size of chain # argument: a chain reference # returns: 1 all OK 0 wrong size sub _sizecheck { my $chain=$_[0]; unless($chain) { warn ("Warning _sizecheck: no chain input"); return (0); } my $begin=$chain->{'begin'}; # the name of the first element my $warncode=1; my ($label,@array); my $size=$chain->{'size'}; my $count=0; $label=$begin; while ($label) { # proceed with linked elements, counting @array=@{$chain->{$label}}; $label = $array[1]; # go to the next one $count++; } if ($size != $count) { warn "Size check reports error: assumed size: $size, real size: $count "; $warncode=0; } return $warncode; } # consistency check for begin and end (boundaries) # argument: a chain reference # returns: 1 all OK 0 problems sub _boundcheck { my $chain=$_[0]; unless($chain) { warn ("Warning _boundcheck: no chain input"); return (0); } my $begin=$chain->{'begin'}; # the name of the first element my $end=$chain->{'end'}; # the name of the (supposedly) last element my $warncode=1; # check SYNC of beginning if (($begin)&&($chain->{$begin})) { # if the BEGIN points to existing element if ($chain->{$begin}[2]) { # if BEGIN element has PREV not undef warn "Warning: BEGIN element has PREV field defined \n"; warn "\tWDEBUG begin: $begin\t"; warn "\tWDEBUG begin's PREV: $chain->{$begin}[2] \n"; $warncode=0; } } else { warn "Warning: BEGIN key of chain does not point to existing element!\n"; warn "\tWDEBUG begin: $begin\n"; $warncode=0; } # check SYNC of end if (($end)&&($chain->{$end})) { # if the END points to an existing element if ($chain->{$end}[1]) { # if END element has NEXT not undef warn "Warning: END element has NEXT field defined \n"; warn "\tWDEBUG end: $end\t"; warn "\tWDEBUG end's NEXT: $chain->{$end}[1] \n"; $warncode=0; } } else { warn "Warning: END key of chain does not point to existing element!\n"; warn "\tWDEBUG end: $end\n"; $warncode=0; } return $warncode; } # arguments: chain_ref # returns: the size of the chain (the number of elements) # return code -1: unexistant chain, errors... sub chain_length { my $chain=$_[0]; unless($chain) { warn ("Warning chain_length: no chain input"); return (-1); } my $size=$chain->{'size'}; if ($size) { return ($size); } else { return (-1); } } # arguments: chain ref, first element name, second element name # returns: 1 or 0 (1 ok, 0 errors) sub _join_chain_elements { my $chain=$_[0]; unless($chain) { warn ("Warning _join_chain_elements: no chain input"); return (0); } my $leftelem=$_[1]; my $rightelem=$_[2]; unless(($leftelem)&&($rightelem)) { warn ("Warning _join_chain_elements: element arguments??"); return (0); } if (($chain->{$leftelem})&&($chain->{$rightelem})) { # if the elements exist $chain->{$leftelem}[1]=$rightelem; $chain->{$rightelem}[2]=$leftelem; return 1; } else { warn ("Warning _join_chain_elements: elements not defined"); return 0; } } =head2 splice_chain Title : splice_chain Usage : @errorcodes = Bio::LiveSeq::Chain::splice_chain($chainref,$first,$length,$last) Function: removes the elements designated by FIRST and LENGTH from a chain. The chain shrinks accordingly. If LENGTH is omitted, removes everything from FIRST onward. If END is specified, LENGTH is ignored and instead the removal occurs from FIRST to LAST. Returns : the elements removed as a string Errorcode: -1 Args : chainref, integer, integer, integer =cut sub splice_chain { my $chain=$_[0]; unless($chain) { warn ("Warning splice_chain: no chain input"); return (-1); } my $begin=$chain->{'begin'}; # the name of the first element my $end=$chain->{'end'}; # the name of the (supposedly) last element my $first=$_[1]; unless (($first eq 0)||($first)) { $first=$begin; } # if undef, use $begin my $len=$_[2]; my $last=$_[3]; my (@array, $string); my ($beforecut,$aftercut); unless($chain->{$first}) { warn ("Warning splice_chain: first element not defined"); return (-1); } if ($last) { # if last is defined, it gets priority and len is not used unless($chain->{$last}) { warn ("Warning splice_chain: last element not defined"); return (-1); } if ($len) { warn ("Warning splice_chain: argument LAST:$last overriding LEN:$len!"); undef $len; } } else { $last=$end; # if last not defined, go 'till end (or to len, whichever 1st) } $beforecut=$chain->{$first}[2]; # what's the element before 1st deleted? # if it is undef then it means we are splicing since the beginning my $i=1; my $label=$first; my $afterlast=$chain->{$last}[1]; # if $last=$end $afterlast should be undef unless (defined $afterlast) { $afterlast=0; } # keep strict happy # proceed for len elements or until the end, whichever comes first # if len undef goes till last while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) { @array=@{$chain->{$label}}; $string .= $array[0]; $aftercut = $array[1]; # what's the element next last deleted? # also used as savevar to change label posdeletion delete $chain->{$label}; # this can be deleted now $label=$aftercut; # label is updated using the savevar $i++; } # Now fix the chain (sticky edges, fields) # 4 cases: cut in the middle, cut from beginning, cut till end, cut all #print "\n\tstickyDEBUG beforecut: $beforecut "; # DEBUG #print "\taftercut: $aftercut \n"; # DEBUG if ($beforecut) { if ($aftercut) { # 1st case, middle cut _join_chain_elements($chain,$beforecut,$aftercut); } else { # 3rd case, end cut $chain->{'end'}=$beforecut; # update the END field $chain->{$beforecut}[1]=undef; # since we cut till the end } } else { if ($aftercut) { # 2nd case, begin cut $chain->{'begin'}=$aftercut; # update the BEGIN field $chain->{$aftercut}[2]=undef; # since we cut from beginning } else { # 4th case, all has been cut $chain->{'begin'}=undef; $chain->{'end'}=undef; } } $chain->{'size'}=($chain->{'size'}) - $i + 1; # update the SIZE field return $string; } # arguments: CHAIN_REF POSITION [FIRST] # returns: element counting POSITION from FIRST or from START if FIRST undef # i.e. returns the element at POSITION counting from FIRST #sub element_at_pos { #croak "Warning: old method name. Please update code to 'down_get_label_at_position'\n"; ##&down_element_at_pos; #} #sub up_element_at_pos { ## old wraparound ##my @array=up_chain2string($_[0],$_[2],$_[1],undef,"elements"); ##return $array[-1]; #croak "old method name. Update code to: up_get_label_at_position"; ##&up_get_label_at_pos; #} #sub down_element_at_pos { ## old wraparound ##my @array=down_chain2string($_[0],$_[2],$_[1],undef,"elements"); ##return $array[-1]; #croak "old method name. Update code to: down_get_label_at_position"; ##&down_get_label_at_pos; #} # arguments: CHAIN_REF ELEMENT [FIRST] # returns: the position of ELEMENT counting from FIRST or from START #i if FIRST is undef # i.e. returns the Number of elements between FIRST and ELEMENT # i.e. returns the position of element taking FIRST as 1 of coordinate system #sub pos_of_element { #croak ("Warning: old and ambiguous method name. Please update code to 'down_get_pos_of_label'\n"); ##&down_pos_of_element; #} #sub up_pos_of_element { #croak ("Warning: old method name. Please update code to 'up_get_pos_of_label'\n"); ##up_chain2string($_[0],$_[2],undef,$_[1],"counting"); #} #sub down_pos_of_element { #croak ("Warning: old method name. Please update code to 'down_get_pos_of_label'\n"); ##down_chain2string($_[0],$_[2],undef,$_[1],"counting"); #} # wraparounds to calculate length of subchain from first to last # arguments: chain_ref [first] [last] #sub subchain_length { #croak "Warning: old method name. Please update code to 'down_subchain_length'\n"; ##&down_subchain_length; #} # wraparounds to have elements output # same arguments as chain2string # returns label|name of every element #sub elements { #croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n"); ##&down_elements; #} #sub up_elements { #croak ("Warning: method no more supported. Please update code to 'up_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n"); ##up_chain2string($_[0],$_[1],$_[2],$_[3],"elements"); #} #sub down_elements { #croak ("Warning: method no more supported. Please update code to 'down_labels' (NB: now it returns ref to array and doesn't allow length argument!)\n"); ##down_chain2string($_[0],$_[1],$_[2],$_[3],"elements"); #} # wraparounds to have verbose output # same arguments as chain2string # returns the chain in a very verbose way sub chain2string_verbose { carp "Warning: method no more supported.\n"; &old_down_chain2string_verbose; } sub up_chain2string_verbose { carp "Warning: method no more supported.\n"; old_up_chain2string($_[0],$_[1],$_[2],$_[3],"verbose"); } sub down_chain2string_verbose { carp "Warning: method no more supported.\n"; old_down_chain2string($_[0],$_[1],$_[2],$_[3],"verbose"); } #sub chain2string { #croak ("Warning: old method name. Please update code to 'down_chain2string'\n"); ##&down_chain2string; #} sub old_up_chain2string { old_updown_chain2string("up",@_); } sub old_down_chain2string { old_updown_chain2string("down",@_); } # common to up_chain2string and down_chain2string # arguments: "up"||"down" chain_ref [first] [len] [last] [option] # [option] can be any of "verbose", "counting", "elements" # error: return -1 # defaults: start = first element; if len undef, goes to last # if last undef, goes to end # if last def it overrides len (that gets undef) # returns: a string # example usage: down_chain2string($chain) -> all the chain from begin to end # example usage: down_chain2string($chain,6) -> from 6 to the end # example usage: down_chain2string($chain,6,4) -> from 6, going on 4 elements # example usage: down_chain2string($chain,6,"",10) -> from 6 to 10 # example usage: up_chain2string($chain,10,"",6) -> from 10 to 6 upstream sub old_updown_chain2string { my ($direction,$chain,$first,$len,$last,$option)=@_; unless($chain) { warn ("Warning chain2string: no chain input"); return (-1); } my $begin=$chain->{'begin'}; # the name of the BEGIN element my $end=$chain->{'end'}; # the name of the END element my $flow; if ($direction eq "up") { $flow=2; # used to determine the direction of chain navigation unless ($first) { $first=$end; } # if undef or 0, use $end } else { # defaults to "down" $flow=1; # used to determine the direction of chain navigation unless ($first) { $first=$begin; } # if undef or 0, use $begin } unless($chain->{$first}) { warn ("Warning chain2string: first element not defined"); return (-1); } if ($last) { # if last is defined, it gets priority and len is not used unless($chain->{$last}) { warn ("Warning chain2string: last element not defined"); return (-1); } if ($len) { warn ("Warning chain2string: argument LAST:$last overriding LEN:$len!"); undef $len; } } else { if ($direction eq "up") { $last=$begin; # if last not defined, go 'till begin (or upto len elements) } else { $last=$end; # if last not defined, go 'till end (or upto len elements) } } my (@array, $string, $count); # call for verbosity (by way of chain2string_verbose); my $verbose=0; my $elements=0; my @elements; my $counting=0; if ($option) { # keep strict happy if ($option eq "verbose") { $verbose=1; } if ($option eq "elements") { $elements=1; } if ($option eq "counting") { $counting=1; } } if ($verbose) { print "BEGIN=$begin"; print " END=$end"; print " SIZE=$chain->{'size'}"; print " FIRSTFREE=$chain->{'firstfree'} \n"; } my $i=1; my $label=$first; my $afterlast=$chain->{$last}[$flow]; # if $last=$end $afterlast should be undef unless (defined $afterlast) { $afterlast=0; } # keep strict happy # proceed for len elements or until last, whichever comes first # if $len undef goes till end while (($label)&&($label != $afterlast) && ($i <= ($len || $i + 1))) { @array=@{$chain->{$label}}; if ($verbose) { $string .= "$array[2]_${label}_$array[1]=$array[0] "; $count++; } elsif ($elements) { push (@elements,$label); # returning element names/references/identifiers } elsif ($counting) { $count++; } else { $string .= $array[0]; # returning element content } $label = $array[$flow]; # go to next||prev i.e. downstream||upstream $i++; } #DEBUG#print "len: $len, first: $first, last: $last, afterlast=$afterlast \n"; if ($verbose) { print "TOTALprinted: $count\n"; } if ($counting) { return $count; } elsif ($elements) { return @elements; } else { return $string; } } # sub string2schain # --------> deleted, no more supported <-------- # creation of a single linked list/chain from a string # basically could be recreated by taking the *2chain methods and # omitting to set the 3rd field (label 2) containing the back links # creation of a double linked list/chain from a string # returns reference to a hash containing the chain # arguments: STRING [OFFSET] # defaults: OFFSET defaults to 1 if undef # the chain will contain as elements the single characters in the string sub string2chain { my @string=split(//,$_[0]); array2chain(\@string,$_[1]); } =head2 array2chain Title : array2chain Usage : $chainref = Bio::LiveSeq::Chain::array2chain($arrayref,$offset) Function: creation of a double linked chain from an array Returns : reference to a hash containing the chain Defaults: OFFSET defaults to 1 if undef Error code: 0 Args : a reference to an array containing the elements to be chainlinked an optional integer > 0 (this will be the starting count for the chain labels instead than having them begin from "1") =cut sub array2chain { my $arrayref=$_[0]; my $array_count=scalar(@{$arrayref}); unless ($array_count) { warn ("Warning array2chain: no elements input"); return (0); } my $begin=$_[1]; if (defined $begin) { if ($begin < 1) { warn "Warning array2chain: Zero or Negative offsets not allowed"; return (0); } } else { $begin=1; } my ($element,%hash); $hash{'begin'}=$begin; my $i=$begin-1; foreach $element (@{$arrayref}) { $i++; # hash with keys begin..end pointing to the arrays $hash{$i}=[$element,$i+1,$i-1]; } my $end=$i; $hash{'end'}=$end; $hash{firstfree}=$i+1; # what a new added element should be called $hash{size}=$end-$begin+1; # how many elements in the chain # eliminate pointers to unexisting elements $hash{$begin}[2]=undef; $hash{$end}[1]=undef; return (\%hash); } 1; # returns 1
bjornwallner/proq2-server
apps/bioperl-live/blib/lib/Bio/LiveSeq/Chain.pm
Perl
gpl-3.0
48,885
(function () { 'use strict'; angular.module('driver.tools.export', [ 'ui.bootstrap', 'ui.router', 'driver.customReports', 'driver.resources', 'angular-spinkit', ]); })();
WorldBank-Transport/DRIVER
web/app/scripts/tools/export/module.js
JavaScript
gpl-3.0
225
"use strict"; exports.__esModule = true; var vueClient_1 = require("../../bibliotheque/vueClient"); console.log("* Chargement du script"); /* Test - déclaration d'une variable externe - Possible cf. declare */ function centreNoeud() { return JSON.parse(vueClient_1.contenuBalise(document, 'centre')); } function voisinsNoeud() { var v = JSON.parse(vueClient_1.contenuBalise(document, 'voisins')); var r = []; var id; for (id in v) { r.push(v[id]); } return r; } function adresseServeur() { return vueClient_1.contenuBalise(document, 'adresseServeur'); } /* type CanalChat = CanalClient<FormatMessageTchat>; // A initialiser var canal: CanalChat; var noeud: Noeud<FormatSommetTchat>; function envoyerMessage(texte: string, destinataire: Identifiant) { let msg: MessageTchat = creerMessageCommunication(noeud.centre().enJSON().id, destinataire, texte); console.log("- Envoi du message brut : " + msg.brut()); console.log("- Envoi du message net : " + msg.net()); canal.envoyerMessage(msg); initialiserEntree('message_' + destinataire, ""); } // A exécuter après chargement de la page function initialisation(): void { console.log("* Initialisation après chargement du DOM ...") noeud = creerNoeud<FormatSommetTchat>(centreNoeud(), voisinsNoeud(), creerSommetTchat); canal = new CanalClient<FormatMessageTchat>(adresseServeur()); canal.enregistrerTraitementAReception((m: FormatMessageTchat) => { let msg = new MessageTchat(m); console.log("- Réception du message brut : " + msg.brut()); console.log("- Réception du message net : " + msg.net()); posterNL('logChats', msg.net()); }); console.log("* ... du noeud et du canal côté client en liaison avec le serveur : " + adresseServeur()); // Gestion des événements pour les éléments du document. //document.getElementById("boutonEnvoi").addEventListener("click", <EventListenerOrEventListenerObject>(e => {alert("click!");}), true); let id: Identifiant; let v = noeud.voisins(); for (id in v) { console.log("id : " +id); let idVal = id; gererEvenementElement("boutonEnvoi_" + idVal, "click", e => { console.log("id message_" + idVal); console.log("entree : " + recupererEntree("message_" + idVal)); envoyerMessage(recupererEntree("message_" + idVal), idVal); }); } <form id="envoi"> <input type="text" id="message_id1"> <input class="button" type="button" id="boutonEnvoi_id1" value="Envoyer un message à {{nom id1}}." onClick="envoyerMessage(this.form.message.value, "id1")"> </form> console.log("* ... et des gestionnaires d'événements sur des éléments du document."); } // Gestion des événements pour le document console.log("* Enregistrement de l'initialisation"); gererEvenementDocument('DOMContentLoaded', initialisation); <script type="text/javascript"> document.addEventListener('DOMContentLoaded', initialisation()); </script> */ //# sourceMappingURL=clientChat.js.map
hgrall/merite
src/communication/v0/typeScript/build/tchat/client/clientChat.js
JavaScript
gpl-3.0
3,134
(function ($) { function FewbricksDevHelper() { var $this = this; /** * */ this.init = function() { $this.cssClassFull = 'fewbricks-info-pane--full'; if(!$this.initMainElm()) { return; } $this.initToggler(); $this.$mainElm.show(); } /** * */ this.initMainElm = function() { $this.$mainElm = $('#fewbricks-info-pane'); if($this.$mainElm.length === 0) { return false; } if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight !== 'undefined') { $this.toggleMainElm(fewbricksInfoPane.startHeight); } return true; } /** * */ this.initToggler = function() { $('[data-fewbricks-info-pane-toggler]') .unbind('click') .on('click', function() { let height = $(this).attr('data-fewbricks-info-pane-height'); $this.toggleMainElm(height); document.cookie = 'fewbricks_info_pane_height=' + height; }); } /** * */ this.toggleMainElm = function(height) { if(height === 'minimized') { $this.$mainElm.attr('style', function(i, style) { return style && style.replace(/height[^;]+;?/g, ''); }); } else { $this.$mainElm.height(height + 'vh'); } } /** * * @returns {*|boolean} */ this.mainElmIsFull = function() { return $this.$mainElm.hasClass($this.cssClassFull); } } $(document).ready(function () { (new FewbricksDevHelper()).init(); }); })(jQuery);
folbert/fewbricks
assets/scripts/info-pane.js
JavaScript
gpl-3.0
1,977
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_SVGPolylineElement_h #define mozilla_dom_SVGPolylineElement_h #include "nsSVGPolyElement.h" nsresult NS_NewSVGPolylineElement(nsIContent **aResult, already_AddRefed<nsINodeInfo> aNodeInfo); typedef nsSVGPolyElement SVGPolylineElementBase; namespace mozilla { namespace dom { class SVGPolylineElement MOZ_FINAL : public SVGPolylineElementBase { protected: SVGPolylineElement(already_AddRefed<nsINodeInfo> aNodeInfo); virtual JSObject* WrapNode(JSContext *cx, JSObject *scope) MOZ_OVERRIDE; friend nsresult (::NS_NewSVGPolylineElement(nsIContent **aResult, already_AddRefed<nsINodeInfo> aNodeInfo)); public: // nsIContent interface virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; }; } // namespace mozilla } // namespace dom #endif // mozilla_dom_SVGPolylineElement_h
DragonZX/fdm
Gecko.SDK/22/include/mozilla/dom/SVGPolylineElement.h
C
gpl-3.0
1,195
/** * ... * @author paul */ function initCBX(object, id, options) { var design = "assets"; if(object == null){ jQuery.noConflict(); var cboxClass; cboxClass = jQuery(id).attr("class"); if(jQuery.browser.msie && parseInt(jQuery.browser.version)<8 ){ jQuery(id).colorbox(); } else{ if(cboxClass.indexOf("cboxElement") == -1){ if(options.classes.image.id){ jQuery('.'+options.classes.image.id).colorbox({transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed}); } if(options.classes.video){ if(options.classes.video.id){ jQuery('.'+options.classes.video.id).colorbox({iframe:true, innerWidth:options.classes.video.innerWidth, innerHeight:options.classes.video.innerHeight, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed}); } } if(options.classes.swf){ if(options.classes.swf.id){ var cbxSWFSrc = jQuery('.'+options.classes.swf.id).attr("href"); var objEmbd = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" id="cbxSWF" ALIGN="">'+ '<PARAM NAME=movie VALUE="'+cbxSWFSrc+'">' + '<PARAM NAME=quality VALUE=high>' + '<PARAM NAME=wmode VALUE=transparent>'+ '<PARAM NAME=bgcolor VALUE=#333399>'+ '<EMBED src="'+cbxSWFSrc+'" quality=high wmode=transparent WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>'+ '</OBJECT>'; jQuery('.'+options.classes.swf.id).colorbox({html:objEmbd, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed}); } } } } jQuery(id).trigger('click'); return; } loadjQuery = function(filename) { loadjQuery.getScript(object.path+"/"+filename); loadjQuery.retry(0); } loadColorbox = function(filename) { loadColorbox.getScript(object.path+"/"+filename); loadColorbox.retry(0); } loadjQuery.getScript = function(filename) { if(typeof jQuery == "undefined"){ var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute("src", filename); document.getElementsByTagName("head")[0].appendChild(script); } } loadColorbox.getScript = function(filename) { if(typeof jQuery.colorbox == "undefined"){ var link = document.createElement('link'); link.setAttribute('media', 'screen'); link.setAttribute('href', object.path+'/'+design+'/colorbox.css'); link.setAttribute('rel', 'stylesheet'); document.getElementsByTagName("head")[0].appendChild(link); var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute("src", filename); document.getElementsByTagName("head")[0].appendChild(script); } } loadjQuery.retry = function(time_elapsed) { if (typeof jQuery == "undefined") { if (time_elapsed <= 5000) { setTimeout("loadjQuery.retry(" + (time_elapsed + 200) + ")", 200); } } else { if(typeof jQuery.colorbox == "undefined"){ loadColorbox("jquery.colorbox-min.js"); } } } loadColorbox.retry = function(time_elapsed) { if (typeof jQuery.colorbox == "undefined") { if (time_elapsed <= 5000) { setTimeout("loadColorbox.retry(" + (time_elapsed + 200) + ")", 200); } } } if(typeof jQuery == "undefined"){ loadjQuery("jquery-1.7.2.min.js"); } else if(typeof jQuery.colorbox == "undefined"){ loadColorbox("jquery.colorbox-min.js"); } }
PhoenixInteractiveNL/emuControlCenter
ecc-core/tools/3dGallery_scripts/circulargallery/colorbox/swf.js.communication.js
JavaScript
gpl-3.0
3,990
#include "gx2r_buffer.h" #include "gx2r_displaylist.h" #include "gx2_displaylist.h" #include <common/log.h> namespace gx2 { void GX2RBeginDisplayListEx(GX2RBuffer *displayList, uint32_t unused, GX2RResourceFlags flags) { if (!displayList || !displayList->buffer) { return; } auto size = displayList->elemCount * displayList->elemSize; GX2BeginDisplayListEx(displayList->buffer, size, TRUE); } uint32_t GX2REndDisplayList(GX2RBuffer *displayList) { auto size = GX2EndDisplayList(displayList->buffer); decaf_check(size < (displayList->elemCount * displayList->elemSize)); return size; } void GX2RCallDisplayList(GX2RBuffer *displayList, uint32_t size) { if (!displayList || !displayList->buffer) { return; } GX2CallDisplayList(displayList->buffer, size); } void GX2RDirectCallDisplayList(GX2RBuffer *displayList, uint32_t size) { if (!displayList || !displayList->buffer) { return; } GX2DirectCallDisplayList(displayList->buffer, size); } } // namespace gx2
petmac/decaf-emu
src/libdecaf/src/modules/gx2/gx2r_displaylist.cpp
C++
gpl-3.0
1,114
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>LamPI 433Mhz controller for RaspberryPI</title> </head> <body> <h1>Weather Dials/Meters </h1> <p>This part of the documentation describes the weather screen and what you can (and sometimes cannot) do with weather sensors. Since version 1.8 LamPI does support weather station sensors. At first only the UPM WT440H (outdoor) sensor is supported and it works fine. Other sensors can be added to the LamPI-receiver/sniffer program later, but it is good to know that the LamPI-daemon offers support for receiving Json messages from weather sensors.</p> <p>If you like to know more about te various sensors, check out their &quot;hardware&quot; pages. </p> <ul> <li><a href="../HardwareGuide/433-Sensors/wt440h/wt440h.html">WT-440H</a> for information about the WT-440H temperature and humidity sensor (433MHz unit)</li> </ul> <p>Of course temperature sensors can be meaningful in weather context, but also be used in energy applications. In the application I make that distinction (for the moment) as I expect most temperature, humidity and pressure sensors to be used most in context of weather. However, users are free to choose differently. As soon as I have my smart-meter up and running I will have a look at the energy sensors and their application as well.</p> <p>Below you see a screenshot of the weather screen...</p> <p><img src="screenshots/weather_screen_1.JPG" width="966" height="637" /></p> <p>&nbsp;</p> <h1>Weather Charts</h1> <p>When clicking in the weather screen on one of the dials, a separate screen will open that shows historical data for the weather sensors. This function is described separately in the section for rrd graphs.</p> <p><img src="screenshots/rrd_screen_01.JPG" width="963" height="636"></p> <h1>Json message format for sensors</h1> <p>The Json message that is sent to the LamPI-daemon is as follows:</p> <p><code>message = {<br> tcnt : integer,<br> type : 'json',<br> action : 'weather',<br> brand: wt440h # or other supported brand<br> address: integer, # (house code)<br> channel: integer,<br> temperature: integer.integer<br> humidity: integer,<br> windspeed: integer,<br> winddirection: integer, # in degrees<br> rainfall : char(8) # (mm per hour)</code></p> <p><code>}; </code><br> </p> <h1>Adding a new wireless Weather sensor</h1> <p>Weather sensors that are wireless 433MHz can be added to the LamPI-receiver by making a sensor function in C and including it in the receiver.c file and in the Makefile. The LamPI-receiver program in the ~/exe directory is the ONLY receiver for 433HMz messages and will handle all forwarding of successful receptions to the LamPI-daemon.</p> <p>Next to the program itself, the sensor needs to be declared in the database.cfg file so that the LamPI-deamon knows that the incoming message for this address/channel is a source that we trust and allow access to our application.</p> <p>&nbsp;</p> <h1>Adding new wired sensors</h1> <p>Adding wired sensors can be one of the following:</p> <ol> <li>A wired sensor without a bus</li> <li>The 1-wire Dallas bus</li> <li>A sensor with I2C support</li> </ol> <p>For more info on wired weather sensors, read the <a href="../HardwareGuide/Wired-Sensors/weather_sensors_msg_format.html">sensors.html</a> page </p> <h1>Logging our Sensor data</h1> <p>The LamPI-daemon will listen to all incoming json messages on its port 5000. Incoing messages from sensors will be matched against the configuration items in the database.cfg file for missing data such as names, location etc that are not sensor defined but defined by the user.</p> <p>But in order to watch trends in data and analyze the collected data we need to add logging capabilities to the LamPI environment. There are several options:</p> <ol> <li>Make LamPI-daemon store all collected data in a logfile and use Excel to analyze the data</li> <li>Make a logging process tat listens to port 5000 and be informed ot every json message that is processed by the daemon.</li> <li>Use an external PAAS service provider, forward all messages received to the service provider and use its analyzing functions to make sense of your data.</li> </ol> <p>The third option is attractive, as it will use external storage, services etc. to look at our data and the trend graphs are accessible from anywhere on the internet. The PAAS provider carriots.com provides this service for free for small users with up to 10 data streams.</p> <h3>re. Store in local logfile</h3> <p>The easiest method for analysing sensor data is to store all data collected to a local logfile on the PI, and import this file into excel on regular intervals. This is simple solution, and this also how I started.</p> <h3>re 2. Logging to rrdtool</h3> <p>There is a tools based on a round robin database tool that can be used to store sensors data and display graphs. </p> <h3>re 3. PAAS. Use a tool like Carriots</h3> <p>The PAAS (Platform As A Service) provider carriots.com provides a free membership for data analysis of a limited set of sensors.</p> <p>&nbsp;</p> </body> </html>
platenspeler/LamPI-3.0
gh-pages/UserGuide/weather.html
HTML
gpl-3.0
5,104
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'newpage', 'eo', { toolbar: 'Nova Paĝo' } );
vanpouckesven/cosnics
src/Chamilo/Libraries/Resources/Javascript/HtmlEditor/Ckeditor/src/plugins/newpage/lang/eo.js
JavaScript
gpl-3.0
226
// $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $ // Copyright (c) 2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.foundation.core; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.argouml.i18n.Translator; import org.argouml.kernel.ProjectManager; import org.argouml.model.Model; import org.argouml.uml.ui.AbstractActionAddModelElement2; /** * An Action to add client dependencies to some modelelement. * * @author Michiel */ public class ActionAddClientDependencyAction extends AbstractActionAddModelElement2 { /** * The constructor. */ public ActionAddClientDependencyAction() { super(); setMultiSelect(true); } /* * Constraint: This code only deals with 1 supplier per dependency! * TODO: How to support more? * * @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List) */ protected void doIt(Collection selected) { Set oldSet = new HashSet(getSelected()); for (Object client : selected) { if (oldSet.contains(client)) { oldSet.remove(client); //to be able to remove dependencies later } else { Model.getCoreFactory().buildDependency(getTarget(), client); } } Collection toBeDeleted = new ArrayList(); Collection dependencies = Model.getFacade().getClientDependencies( getTarget()); for (Object dependency : dependencies) { if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) { toBeDeleted.add(dependency); } } ProjectManager.getManager().getCurrentProject() .moveToTrash(toBeDeleted); } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices() */ protected List getChoices() { List ret = new ArrayList(); Object model = ProjectManager.getManager().getCurrentProject().getModel(); if (getTarget() != null) { ret.addAll(Model.getModelManagementHelper() .getAllModelElementsOfKind(model, "org.omg.uml.foundation.core.ModelElement")); ret.remove(getTarget()); } return ret; } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle() */ protected String getDialogTitle() { return Translator.localize("dialog.title.add-client-dependency"); } /* * @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected() */ protected List getSelected() { List v = new ArrayList(); Collection c = Model.getFacade().getClientDependencies(getTarget()); for (Object cd : c) { v.addAll(Model.getFacade().getSuppliers(cd)); } return v; } }
ckaestne/LEADT
workspace/argouml_critics/argouml-app/src/org/argouml/uml/ui/foundation/core/ActionAddClientDependencyAction.java
Java
gpl-3.0
4,569
require 'spec_helper' require 'rubybot/plugins/tweet' require 'support/twitter_mock' RSpec.describe Rubybot::Plugins::Tweet do include Cinch::Test describe '#commands' do subject { described_class.new(make_bot).commands } it('returns a single command') { is_expected.to have_exactly(1).items } end let(:bot) { make_bot described_class, get_plugin_configuration(described_class) } it 'doesn\'t match an unrelated url' do expect(get_replies make_message(bot, 'asdf')).to have_exactly(0).items end it 'gives tweet data for a twitter url' do replies = get_replies make_message(bot, 'https://twitter.com/AUser/status/43212344123', channel: 'a') expect(replies).to have_exactly(1).items expect(replies.first.event).to eq :message expect(replies.first.text).to eq '@AUser: asdf' end end
robotbrain/rubybot
spec/rubybot/plugins/tweet_spec.rb
Ruby
gpl-3.0
908
var searchData= [ ['transfer_20commands',['Transfer Commands',['../group___d_a_p__transfer__gr.html',1,'']]] ];
Stanford-BDML/super-scamp
vendor/CMSIS/CMSIS/Documentation/DAP/html/search/groups_74.js
JavaScript
gpl-3.0
114
Public Class RotationTile Inherits Entity Public Enum RotationTypes StartSpin StopSpin End Enum Dim RotationType As RotationTypes Dim RotateTo As Integer = 0 Public Overrides Sub Initialize() MyBase.Initialize() Select Case Me.ActionValue Case 0 Me.RotationType = RotationTypes.StartSpin Case 1 Me.RotationType = RotationTypes.StopSpin End Select Me.RotateTo = CInt(Me.AdditionalValue) Me.NeedsUpdate = True End Sub Public Overrides Sub Update() If Me.RotationType = RotationTypes.StartSpin Then If Core.CurrentScreen.Identification = Screen.Identifications.OverworldScreen Then If CType(Core.CurrentScreen, OverworldScreen).ActionScript.IsReady = True Then If Me.Position.X = Screen.Camera.Position.X And CInt(Me.Position.Y) = CInt(Screen.Camera.Position.Y) And Me.Position.Z = Screen.Camera.Position.Z Then Dim steps As Integer = GetSteps() Dim s As String = "version=2" & vbNewLine & "@player.move(0)" & vbNewLine & "@player.turnto(" & Me.RotateTo.ToString() & ")" & vbNewLine & "@player.move(" & steps & ")" & vbNewLine & ":end" CType(Core.CurrentScreen, OverworldScreen).ActionScript.StartScript(s, 2) End If End If End If End If End Sub Private Function GetSteps() As Integer Dim steps As Integer = 0 Dim direction As Vector2 = New Vector2(0) Select Case Me.RotateTo Case 0 direction.Y = -1 Case 1 direction.X = -1 Case 2 direction.Y = 1 Case 3 direction.X = 1 End Select Dim stepY As Integer = CInt(direction.Y) If stepY = 0 Then stepY = 1 End If For x = 0 To direction.X * 100 Step direction.X For y = 0 To direction.Y * 100 Step stepY Dim p As Vector3 = New Vector3(x, 0, y) + Me.Position For Each e As Entity In Screen.Level.Entities If e.Equals(Me) = False Then If e.EntityID.ToLower() = "rotationtile" Then If CInt(e.Position.X) = CInt(p.X) And CInt(e.Position.Y) = CInt(p.Y) And CInt(e.Position.Z) = CInt(p.Z) Then GoTo theend End If End If End If Next steps += 1 Next Next theend: Return steps End Function Public Overrides Sub Render() Me.Draw(Me.Model, Textures, False) End Sub Public Overrides Function LetPlayerMove() As Boolean Return Me.RotationType = RotationTypes.StopSpin End Function Public Overrides Function WalkIntoFunction() As Boolean If Me.RotationType = RotationTypes.StartSpin Then CType(Screen.Camera, OverworldCamera).YawLocked = True End If Return False End Function End Class
Zconj95/P3D-Legacy
2.5DHero/2.5DHero/Entites/Enviroment/RotationTile.vb
Visual Basic
gpl-3.0
3,308
#!/bin/bash # Butterfly root BUTTERFLY_ROOT=$(cd "$(dirname $0)/.." && pwd) sources="$BUTTERFLY_ROOT/api/client/client.cc \ $BUTTERFLY_ROOT/api/client/client.h \ $BUTTERFLY_ROOT/api/client/nic.cc \ $BUTTERFLY_ROOT/api/client/request.cc \ $BUTTERFLY_ROOT/api/client/sg.cc \ $BUTTERFLY_ROOT/api/client/shutdown.cc \ $BUTTERFLY_ROOT/api/client/status.cc \ $BUTTERFLY_ROOT/api/client/dump.cc \ $BUTTERFLY_ROOT/api/server/app.cc \ $BUTTERFLY_ROOT/api/server/app.h \ $BUTTERFLY_ROOT/api/server/server.cc \ $BUTTERFLY_ROOT/api/server/server.h \ $BUTTERFLY_ROOT/api/server/model.cc \ $BUTTERFLY_ROOT/api/server/model.h \ $BUTTERFLY_ROOT/api/server/api.cc \ $BUTTERFLY_ROOT/api/server/api.h \ $BUTTERFLY_ROOT/api/server/api_0.cc \ $BUTTERFLY_ROOT/api/server/graph.cc \ $BUTTERFLY_ROOT/api/server/graph.h \ $BUTTERFLY_ROOT/api/common/crypto.cc \ $BUTTERFLY_ROOT/api/common/crypto.h" $BUTTERFLY_ROOT/scripts/cpplint.py --filter=-build/c++11 --root=$BUTTERFLY_ROOT $sources if [ $? != 0 ]; then echo "${RED}API style test failed${NORMAL}" exit 1 fi cppcheck &> /dev/null if [ $? != 0 ]; then echo "cppcheck is not installed, some tests will be skipped" else cppcheck --check-config --error-exitcode=1 --enable=all -I $BUTTERFLY_ROOT $sources &> /tmp/cppcheck.log if [ $? != 0 ]; then cat /tmp/cppcheck.log echo "${RED}API style test failed${NORMAL}" rm /tmp/cppcheck.log exit 1 fi fi rm /tmp/cppcheck.log rm /tmp/has_tabs &> /dev/null || true for f in api benchmarks doc scripts tests; do find $BUTTERFLY_ROOT/$f -name *.sh | while read a; do if [ "-$(cat $a | grep -P '\t')" != "-" ]; then echo found tab in $a touch /tmp/has_tabs fi done done if test -f /tmp/has_tabs; then rm /tmp/has_tabs &> /dev/null || true echo "-- tabs found in scripts" exit 1 else echo "-- no tab found in scripts" fi exit 0
outscale-toa/butterfly
scripts/tests_api_style.sh
Shell
gpl-3.0
1,916
"""Data models for referral system.""" from __future__ import unicode_literals from builtins import map from django.db import models from django.core.urlresolvers import reverse from pttrack.models import (ReferralType, ReferralLocation, Note, ContactMethod, CompletableMixin,) from followup.models import ContactResult, NoAptReason, NoShowReason class Referral(Note): """A record of a particular patient's referral to a particular center.""" STATUS_SUCCESSFUL = 'S' STATUS_PENDING = 'P' STATUS_UNSUCCESSFUL = 'U' # Status if there are no referrals of a specific type # Used in aggregate_referral_status NO_REFERRALS_CURRENTLY = "No referrals currently" REFERRAL_STATUSES = ( (STATUS_SUCCESSFUL, 'Successful'), (STATUS_PENDING, 'Pending'), (STATUS_UNSUCCESSFUL, 'Unsuccessful'), ) location = models.ManyToManyField(ReferralLocation) comments = models.TextField(blank=True) status = models.CharField( max_length=50, choices=REFERRAL_STATUSES, default=STATUS_PENDING) kind = models.ForeignKey( ReferralType, help_text="The kind of care the patient should recieve at the " "referral location.") def __str__(self): """Provides string to display on front end for referral. For FQHC referrals, returns referral kind and date. For non-FQHC referrals, returns referral location and date. """ formatted_date = self.written_datetime.strftime("%D") if self.kind.is_fqhc: return "%s referral on %s" % (self.kind, formatted_date) else: location_names = [loc.name for loc in self.location.all()] locations = " ,".join(location_names) return "Referral to %s on %s" % (locations, formatted_date) @staticmethod def aggregate_referral_status(referrals): referral_status_output = "" if referrals: all_successful = all(referral.status == Referral.STATUS_SUCCESSFUL for referral in referrals) if all_successful: referral_status_output = (dict(Referral.REFERRAL_STATUSES) [Referral.STATUS_SUCCESSFUL]) else: # Determine referral status based on the last FQHC referral referral_status_output = (dict(Referral.REFERRAL_STATUSES) [referrals.last().status]) else: referral_status_output = Referral.NO_REFERRALS_CURRENTLY return referral_status_output class FollowupRequest(Note, CompletableMixin): referral = models.ForeignKey(Referral) contact_instructions = models.TextField() MARK_DONE_URL_NAME = 'new-patient-contact' ADMIN_URL_NAME = '' def class_name(self): return self.__class__.__name__ def short_name(self): return "Referral" def summary(self): return self.contact_instructions def mark_done_url(self): return reverse(self.MARK_DONE_URL_NAME, args=(self.referral.patient.id, self.referral.id, self.id)) def admin_url(self): return reverse( 'admin:referral_followuprequest_change', args=(self.id,) ) def __str__(self): formatted_date = self.due_date.strftime("%D") return 'Followup with %s on %s about %s' % (self.patient, formatted_date, self.referral) class PatientContact(Note): followup_request = models.ForeignKey(FollowupRequest) referral = models.ForeignKey(Referral) contact_method = models.ForeignKey( ContactMethod, null=False, blank=False, help_text="What was the method of contact?") contact_status = models.ForeignKey( ContactResult, blank=False, null=False, help_text="Did you make contact with the patient about this referral?") PTSHOW_YES = "Y" PTSHOW_NO = "N" PTSHOW_OPTS = [(PTSHOW_YES, "Yes"), (PTSHOW_NO, "No")] has_appointment = models.CharField( choices=PTSHOW_OPTS, blank=True, max_length=1, verbose_name="Appointment scheduled?", help_text="Did the patient make an appointment?") no_apt_reason = models.ForeignKey( NoAptReason, blank=True, null=True, verbose_name="No appointment reason", help_text="If the patient didn't make an appointment, why not?") appointment_location = models.ManyToManyField( ReferralLocation, blank=True, help_text="Where did the patient make an appointment?") pt_showed = models.CharField( max_length=1, choices=PTSHOW_OPTS, blank=True, null=True, verbose_name="Appointment attended?", help_text="Did the patient show up to the appointment?") no_show_reason = models.ForeignKey( NoShowReason, blank=True, null=True, help_text="If the patient didn't go to the appointment, why not?") def short_text(self): """Return a short text description of this followup and what happened. Used on the patient chart view as the text in the list of followups. """ text = "" locations = " ,".join(map(str, self.appointment_location.all())) if self.pt_showed == self.PTSHOW_YES: text = "Patient went to appointment at " + locations + "." else: if self.has_appointment == self.PTSHOW_YES: text = ("Patient made appointment at " + locations + "but has not yet gone.") else: if self.contact_status.patient_reached: text = ("Successfully contacted patient but the " "patient has not made an appointment yet.") else: text = "Did not successfully contact patient" return text
SaturdayNeighborhoodHealthClinic/osler
referral/models.py
Python
gpl-3.0
6,199
/* armor.c - Armor filters * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2007, 2008, 2010 * Free Software Foundation, Inc. * * Author: Timo Schulz * * This file is part of OpenCDK. * * The OpenCDK 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 3 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * ChangeLog for basic BASE64 code (base64_encode, base64_decode): * Original author: Eric S. Raymond (Fetchmail) * Heavily modified by Brendan Cully <brendan@kublai.com> (Mutt) * Modify the code for generic use by Timo Schulz <twoaday@freakmail.de> */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <string.h> #include <sys/stat.h> #include "opencdk.h" #include "main.h" #include "filters.h" #ifdef __MINGW32__ #define LF "\r\n" #define ALTLF "\n" #else #define LF "\n" #define ALTLF "\r\n" #endif #define CRCINIT 0xB704CE #define BAD -1 #define b64val(c) index64[(unsigned int)(c)] static u32 crc_table[] = { 0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17, 0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E, 0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E, 0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7, 0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE, 0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7, 0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077, 0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E, 0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5, 0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC, 0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C, 0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375, 0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C, 0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15, 0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5, 0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C, 0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3, 0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A, 0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A, 0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703, 0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A, 0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863, 0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3, 0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA, 0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61, 0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58, 0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8, 0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1, 0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88, 0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1, 0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401, 0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538 }; static const char *armor_begin[] = { "BEGIN PGP MESSAGE", "BEGIN PGP PUBLIC KEY BLOCK", "BEGIN PGP PRIVATE KEY BLOCK", "BEGIN PGP SIGNATURE", NULL }; static const char *armor_end[] = { "END PGP MESSAGE", "END PGP PUBLIC KEY BLOCK", "END PGP PRIVATE KEY BLOCK", "END PGP SIGNATURE", NULL }; static const char *valid_headers[] = { "Comment", "Version", "MessageID", "Hash", "Charset", NULL }; static char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static int index64[128] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; /* encode a raw binary buffer to a null-terminated base64 strings */ static int base64_encode (char *out, const byte * in, size_t len, size_t olen) { if (!out || !in) { gnutls_assert (); return CDK_Inv_Value; } while (len >= 3 && olen > 10) { *out++ = b64chars[in[0] >> 2]; *out++ = b64chars[((in[0] << 4) & 0x30) | (in[1] >> 4)]; *out++ = b64chars[((in[1] << 2) & 0x3c) | (in[2] >> 6)]; *out++ = b64chars[in[2] & 0x3f]; olen -= 4; len -= 3; in += 3; } /* clean up remainder */ if (len > 0 && olen > 4) { byte fragment = 0; *out++ = b64chars[in[0] >> 2]; fragment = (in[0] << 4) & 0x30; if (len > 1) fragment |= in[1] >> 4; *out++ = b64chars[fragment]; *out++ = (len < 2) ? '=' : b64chars[(in[1] << 2) & 0x3c]; *out++ = '='; } *out = '\0'; return 0; } /* Convert '\0'-terminated base64 string to raw byte buffer. Returns length of returned buffer, or -1 on error. */ static int base64_decode (byte * out, const char *in) { size_t len; byte digit1, digit2, digit3, digit4; if (!out || !in) { gnutls_assert (); return -1; } len = 0; do { digit1 = in[0]; if (digit1 > 127 || b64val (digit1) == BAD) { gnutls_assert (); return -1; } digit2 = in[1]; if (digit2 > 127 || b64val (digit2) == BAD) { gnutls_assert (); return -1; } digit3 = in[2]; if (digit3 > 127 || ((digit3 != '=') && (b64val (digit3) == BAD))) { gnutls_assert (); return -1; } digit4 = in[3]; if (digit4 > 127 || ((digit4 != '=') && (b64val (digit4) == BAD))) { gnutls_assert (); return -1; } in += 4; /* digits are already sanity-checked */ *out++ = (b64val (digit1) << 2) | (b64val (digit2) >> 4); len++; if (digit3 != '=') { *out++ = ((b64val (digit2) << 4) & 0xf0) | (b64val (digit3) >> 2); len++; if (digit4 != '=') { *out++ = ((b64val (digit3) << 6) & 0xc0) | b64val (digit4); len++; } } } while (*in && digit4 != '='); return len; } /* Return the compression algorithm in @r_zipalgo. If the parameter is not set after execution, the stream is not compressed. */ static int compress_get_algo (cdk_stream_t inp, int *r_zipalgo) { byte plain[512]; char buf[128]; int nread, pkttype; *r_zipalgo = 0; cdk_stream_seek (inp, 0); while (!cdk_stream_eof (inp)) { nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1); if (!nread || nread == -1) break; if (nread == 1 && !cdk_stream_eof (inp) && (nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1)) > 0) { base64_decode (plain, buf); if (!(*plain & 0x80)) break; pkttype = *plain & 0x40 ? (*plain & 0x3f) : ((*plain >> 2) & 0xf); if (pkttype == CDK_PKT_COMPRESSED && r_zipalgo) { _gnutls_buffers_log ("armor compressed (algo=%d)\n", *(plain + 1)); *r_zipalgo = *(plain + 1); } break; } } return 0; } static int check_armor (cdk_stream_t inp, int *r_zipalgo) { char buf[4096]; size_t nread; int check; check = 0; nread = cdk_stream_read (inp, buf, DIM (buf) - 1); if (nread > 0) { buf[nread] = '\0'; if (strstr (buf, "-----BEGIN PGP")) { compress_get_algo (inp, r_zipalgo); check = 1; } cdk_stream_seek (inp, 0); } return check; } static int is_armored (int ctb) { int pkttype = 0; if (!(ctb & 0x80)) { gnutls_assert (); return 1; /* invalid packet: assume it is armored */ } pkttype = ctb & 0x40 ? (ctb & 0x3f) : ((ctb >> 2) & 0xf); switch (pkttype) { case CDK_PKT_MARKER: case CDK_PKT_ONEPASS_SIG: case CDK_PKT_PUBLIC_KEY: case CDK_PKT_SECRET_KEY: case CDK_PKT_PUBKEY_ENC: case CDK_PKT_SIGNATURE: case CDK_PKT_LITERAL: case CDK_PKT_COMPRESSED: return 0; /* seems to be a regular packet: not armored */ } return 1; } static u32 update_crc (u32 crc, const byte * buf, size_t buflen) { unsigned int j; if (!crc) crc = CRCINIT; for (j = 0; j < buflen; j++) crc = (crc << 8) ^ crc_table[0xff & ((crc >> 16) ^ buf[j])]; crc &= 0xffffff; return crc; } static cdk_error_t armor_encode (void *data, FILE * in, FILE * out) { armor_filter_t *afx = data; struct stat statbuf; char crcbuf[5], buf[128], raw[49]; byte crcbuf2[3]; size_t nread = 0; const char *lf; if (!afx) { gnutls_assert (); return CDK_Inv_Value; } if (afx->idx < 0 || afx->idx > (int) DIM (armor_begin) || afx->idx2 < 0 || afx->idx2 > (int) DIM (armor_end)) { gnutls_assert (); return CDK_Inv_Value; } _gnutls_buffers_log ("armor filter: encode\n"); memset (crcbuf, 0, sizeof (crcbuf)); lf = afx->le ? afx->le : LF; fprintf (out, "-----%s-----%s", armor_begin[afx->idx], lf); fprintf (out, "Version: OpenPrivacy " PACKAGE_VERSION "%s", lf); if (afx->hdrlines) fwrite (afx->hdrlines, 1, strlen (afx->hdrlines), out); fprintf (out, "%s", lf); if (fstat (fileno (in), &statbuf)) { gnutls_assert (); return CDK_General_Error; } while (!feof (in)) { nread = fread (raw, 1, DIM (raw) - 1, in); if (!nread) break; if (ferror (in)) { gnutls_assert (); return CDK_File_Error; } afx->crc = update_crc (afx->crc, (byte *) raw, nread); base64_encode (buf, (byte *) raw, nread, DIM (buf) - 1); fprintf (out, "%s%s", buf, lf); } crcbuf2[0] = afx->crc >> 16; crcbuf2[1] = afx->crc >> 8; crcbuf2[2] = afx->crc; crcbuf[0] = b64chars[crcbuf2[0] >> 2]; crcbuf[1] = b64chars[((crcbuf2[0] << 4) & 0x30) | (crcbuf2[1] >> 4)]; crcbuf[2] = b64chars[((crcbuf2[1] << 2) & 0x3c) | (crcbuf2[2] >> 6)]; crcbuf[3] = b64chars[crcbuf2[2] & 0x3f]; fprintf (out, "=%s%s", crcbuf, lf); fprintf (out, "-----%s-----%s", armor_end[afx->idx2], lf); return 0; } /** * cdk_armor_filter_use: * @inp: the stream to check * * Check if the stream contains armored data. **/ int cdk_armor_filter_use (cdk_stream_t inp) { int c, check; int zipalgo; zipalgo = 0; c = cdk_stream_getc (inp); if (c == EOF) return 0; /* EOF, doesn't matter whether armored or not */ cdk_stream_seek (inp, 0); check = is_armored (c); if (check) { check = check_armor (inp, &zipalgo); if (zipalgo) _cdk_stream_set_compress_algo (inp, zipalgo); } return check; } static int search_header (const char *buf, const char **array) { const char *s; int i; if (strlen (buf) < 5 || strncmp (buf, "-----", 5)) { gnutls_assert (); return -1; } for (i = 0; (s = array[i]); i++) { if (!strncmp (s, buf + 5, strlen (s))) return i; } return -1; } const char * _cdk_armor_get_lineend (void) { return LF; } static cdk_error_t armor_decode (void *data, FILE * in, FILE * out) { armor_filter_t *afx = data; const char *s; char buf[127]; byte raw[128], crcbuf[4]; u32 crc2 = 0; ssize_t nread = 0; int i, pgp_data = 0; cdk_error_t rc = 0; int len; if (!afx) { gnutls_assert (); return CDK_Inv_Value; } _gnutls_buffers_log ("armor filter: decode\n"); fseek (in, 0, SEEK_SET); /* Search the begin of the message */ while (!feof (in) && !pgp_data) { s = fgets (buf, DIM (buf) - 1, in); if (!s) break; afx->idx = search_header (buf, armor_begin); if (afx->idx >= 0) pgp_data = 1; } if (feof (in) || !pgp_data) { gnutls_assert (); return CDK_Armor_Error; /* no data found */ } /* Parse header until the empty line is reached */ while (!feof (in)) { s = fgets (buf, DIM (buf) - 1, in); if (!s) return CDK_EOF; if (strcmp (s, LF) == 0 || strcmp (s, ALTLF) == 0) { rc = 0; break; /* empty line */ } /* From RFC2440: OpenPGP should consider improperly formatted Armor Headers to be corruption of the ASCII Armor. A colon and a single space separate the key and value. */ if (!strstr (buf, ": ")) { gnutls_assert (); return CDK_Armor_Error; } rc = CDK_General_Error; for (i = 0; (s = valid_headers[i]); i++) { if (!strncmp (s, buf, strlen (s))) rc = 0; } if (rc) { /* From RFC2440: Unknown keys should be reported to the user, but OpenPGP should continue to process the message. */ _cdk_log_info ("unknown header: `%s'\n", buf); rc = 0; } } /* Read the data body */ while (!feof (in)) { s = fgets (buf, DIM (buf) - 1, in); if (!s) break; len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0'; if (buf[len - 1] == '\r') buf[len - 1] = '\0'; if (buf[0] == '=' && strlen (s) == 5) { /* CRC */ memset (crcbuf, 0, sizeof (crcbuf)); base64_decode (crcbuf, buf + 1); crc2 = (crcbuf[0] << 16) | (crcbuf[1] << 8) | crcbuf[2]; break; /* stop here */ } else { nread = base64_decode (raw, buf); if (nread == -1 || nread == 0) break; afx->crc = update_crc (afx->crc, raw, nread); fwrite (raw, 1, nread, out); } } /* Search the tail of the message */ s = fgets (buf, DIM (buf) - 1, in); if (s) { int len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0'; if (buf[len - 1] == '\r') buf[len - 1] = '\0'; rc = CDK_General_Error; afx->idx2 = search_header (buf, armor_end); if (afx->idx2 >= 0) rc = 0; } /* This catches error when no tail was found or the header is different then the tail line. */ if (rc || afx->idx != afx->idx2) rc = CDK_Armor_Error; afx->crc_okay = (afx->crc == crc2) ? 1 : 0; if (!afx->crc_okay && !rc) { _gnutls_buffers_log ("file crc=%08X afx_crc=%08X\n", (unsigned int) crc2, (unsigned int) afx->crc); rc = CDK_Armor_CRC_Error; } return rc; } /** * cdk_file_armor: * @hd: Handle * @file: Name of the file to protect. * @output: Output filename. * * Protect a file with ASCII armor. **/ cdk_error_t cdk_file_armor (cdk_ctx_t hd, const char *file, const char *output) { cdk_stream_t inp, out; cdk_error_t rc; rc = _cdk_check_args (hd->opt.overwrite, file, output); if (rc) return rc; rc = cdk_stream_open (file, &inp); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_new (output, &out); if (rc) { cdk_stream_close (inp); gnutls_assert (); return rc; } cdk_stream_set_armor_flag (out, CDK_ARMOR_MESSAGE); if (hd->opt.compress) rc = cdk_stream_set_compress_flag (out, hd->compress.algo, hd->compress.level); if (!rc) rc = cdk_stream_set_literal_flag (out, 0, file); if (!rc) rc = cdk_stream_kick_off (inp, out); if (!rc) rc = _cdk_stream_get_errno (out); cdk_stream_close (out); cdk_stream_close (inp); return rc; } /** * cdk_file_dearmor: * @file: Name of the file to unprotect. * @output: Output filename. * * Remove ASCII armor from a file. **/ cdk_error_t cdk_file_dearmor (const char *file, const char *output) { cdk_stream_t inp, out; cdk_error_t rc; int zipalgo; rc = _cdk_check_args (1, file, output); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_open (file, &inp); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_create (output, &out); if (rc) { cdk_stream_close (inp); gnutls_assert (); return rc; } if (cdk_armor_filter_use (inp)) { rc = cdk_stream_set_literal_flag (inp, 0, NULL); zipalgo = cdk_stream_is_compressed (inp); if (zipalgo) rc = cdk_stream_set_compress_flag (inp, zipalgo, 0); if (!rc) rc = cdk_stream_set_armor_flag (inp, 0); if (!rc) rc = cdk_stream_kick_off (inp, out); if (!rc) rc = _cdk_stream_get_errno (inp); } cdk_stream_close (inp); cdk_stream_close (out); gnutls_assert (); return rc; } int _cdk_filter_armor (void *data, int ctl, FILE * in, FILE * out) { if (ctl == STREAMCTL_READ) return armor_decode (data, in, out); else if (ctl == STREAMCTL_WRITE) return armor_encode (data, in, out); else if (ctl == STREAMCTL_FREE) { armor_filter_t *afx = data; if (afx) { _gnutls_buffers_log ("free armor filter\n"); afx->idx = afx->idx2 = 0; afx->crc = afx->crc_okay = 0; return 0; } } gnutls_assert (); return CDK_Inv_Mode; } /** * cdk_armor_encode_buffer: * @inbuf: the raw input buffer * @inlen: raw buffer len * @outbuf: the destination buffer for the base64 output * @outlen: destination buffer len * @nwritten: actual length of the base64 data * @type: the base64 file type. * * Encode the given buffer into base64 format. The base64 * string will be null terminated but the null will * not be contained in the size. **/ cdk_error_t cdk_armor_encode_buffer (const byte * inbuf, size_t inlen, char *outbuf, size_t outlen, size_t * nwritten, int type) { const char *head, *tail, *le; byte tempbuf[48]; char tempout[128]; size_t pos, off, len, rest; if (!inbuf || !nwritten) { gnutls_assert (); return CDK_Inv_Value; } if (type > CDK_ARMOR_SIGNATURE) { gnutls_assert (); return CDK_Inv_Mode; } head = armor_begin[type]; tail = armor_end[type]; le = _cdk_armor_get_lineend (); pos = strlen (head) + 10 + 2 + 2 + strlen (tail) + 10 + 2 + 5 + 2 + 1; /* The output data is 4/3 times larger, plus a line end for each line. */ pos += (4 * inlen / 3) + 2 * (4 * inlen / 3 / 64) + 1; if (outbuf && outlen < pos) { gnutls_assert (); *nwritten = pos; return CDK_Too_Short; } /* Only return the size of the output. */ if (!outbuf) { *nwritten = pos; return 0; } pos = 0; memset (outbuf, 0, outlen); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, head, strlen (head)); pos += strlen (head); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); rest = inlen; for (off = 0; off < inlen;) { if (rest > 48) { memcpy (tempbuf, inbuf + off, 48); off += 48; len = 48; } else { memcpy (tempbuf, inbuf + off, rest); off += rest; len = rest; } rest -= len; base64_encode (tempout, tempbuf, len, DIM (tempout) - 1); memcpy (outbuf + pos, tempout, strlen (tempout)); pos += strlen (tempout); memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); } memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, tail, strlen (tail)); pos += strlen (tail); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); outbuf[pos] = 0; *nwritten = pos - 1; return 0; }
freedesktop-unofficial-mirror/gstreamer-sdk__gnutls
lib/opencdk/armor.c
C
gpl-3.0
21,279
//# MatrixInverse.cc: The inverse of an expression returning a Jones matrix. //# //# Copyright (C) 2005 //# ASTRON (Netherlands Institute for Radio Astronomy) //# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands //# //# This file is part of the LOFAR software suite. //# The LOFAR software suite 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. //# //# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>. //# //# $Id$ #include <lofar_config.h> #include <BBSKernel/Expr/MatrixInverse.h> // Inverse of a 2x2 matrix: // // (a b) ( d -b) // If A = ( ) then inverse(A) = ( ) / (ad - bc) // (c d) (-c a) namespace LOFAR { namespace BBS { MatrixInverse::MatrixInverse(const Expr<JonesMatrix>::ConstPtr &expr) : BasicUnaryExpr<JonesMatrix, JonesMatrix>(expr) { } const JonesMatrix::View MatrixInverse::evaluateImpl(const Grid&, const JonesMatrix::View &arg0) const { JonesMatrix::View result; Matrix invDet(1.0 / (arg0(0, 0) * arg0(1, 1) - arg0(0, 1) * arg0(1, 0))); result.assign(0, 0, arg0(1, 1) * invDet); result.assign(0, 1, arg0(0, 1) * -invDet); result.assign(1, 0, arg0(1, 0) * -invDet); result.assign(1, 1, arg0(0, 0) * invDet); return result; } } // namespace BBS } // namespace LOFAR
kernsuite-debian/lofar
CEP/Calibration/BBSKernel/src/Expr/MatrixInverse.cc
C++
gpl-3.0
1,851
########################################################################### # # This file is partially auto-generated by the DateTime::Locale generator # tools (v0.10). This code generator comes with the DateTime::Locale # distribution in the tools/ directory, and is called generate-modules. # # This file was generated from the CLDR JSON locale data. See the LICENSE.cldr # file included in this distribution for license details. # # Do not edit this file directly unless you are sure the part you are editing # is not created by the generator. # ########################################################################### =pod =encoding UTF-8 =head1 NAME DateTime::Locale::rwk - Locale data examples for the Rwa (rwk) locale =head1 DESCRIPTION This pod file contains examples of the locale data available for the Rwa locale. =head2 Days =head3 Wide (format) Jumatatuu Jumanne Jumatanu Alhamisi Ijumaa Jumamosi Jumapilyi =head3 Abbreviated (format) Jtt Jnn Jtn Alh Iju Jmo Jpi =head3 Narrow (format) J J J A I J J =head3 Wide (stand-alone) Jumatatuu Jumanne Jumatanu Alhamisi Ijumaa Jumamosi Jumapilyi =head3 Abbreviated (stand-alone) Jtt Jnn Jtn Alh Iju Jmo Jpi =head3 Narrow (stand-alone) J J J A I J J =head2 Months =head3 Wide (format) Januari Februari Machi Aprilyi Mei Junyi Julyai Agusti Septemba Oktoba Novemba Desemba =head3 Abbreviated (format) Jan Feb Mac Apr Mei Jun Jul Ago Sep Okt Nov Des =head3 Narrow (format) J F M A M J J A S O N D =head3 Wide (stand-alone) Januari Februari Machi Aprilyi Mei Junyi Julyai Agusti Septemba Oktoba Novemba Desemba =head3 Abbreviated (stand-alone) Jan Feb Mac Apr Mei Jun Jul Ago Sep Okt Nov Des =head3 Narrow (stand-alone) J F M A M J J A S O N D =head2 Quarters =head3 Wide (format) Robo 1 Robo 2 Robo 3 Robo 4 =head3 Abbreviated (format) R1 R2 R3 R4 =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) Robo 1 Robo 2 Robo 3 Robo 4 =head3 Abbreviated (stand-alone) R1 R2 R3 R4 =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide (format) Kabla ya Kristu Baada ya Kristu =head3 Abbreviated (format) KK BK =head3 Narrow (format) KK BK =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = Jumanne, 5 Februari 2008 1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995 -0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10 =head3 Long 2008-02-05T18:30:30 = 5 Februari 2008 1995-12-22T09:05:02 = 22 Desemba 1995 -0010-09-15T04:44:23 = 15 Septemba -10 =head3 Medium 2008-02-05T18:30:30 = 5 Feb 2008 1995-12-22T09:05:02 = 22 Des 1995 -0010-09-15T04:44:23 = 15 Sep -10 =head3 Short 2008-02-05T18:30:30 = 05/02/2008 1995-12-22T09:05:02 = 22/12/1995 -0010-09-15T04:44:23 = 15/09/-10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = Jumanne, 5 Februari 2008 18:30:30 UTC 1995-12-22T09:05:02 = Ijumaa, 22 Desemba 1995 09:05:02 UTC -0010-09-15T04:44:23 = Jumamosi, 15 Septemba -10 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5 Februari 2008 18:30:30 UTC 1995-12-22T09:05:02 = 22 Desemba 1995 09:05:02 UTC -0010-09-15T04:44:23 = 15 Septemba -10 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 5 Feb 2008 18:30:30 1995-12-22T09:05:02 = 22 Des 1995 09:05:02 -0010-09-15T04:44:23 = 15 Sep -10 04:44:23 =head3 Short 2008-02-05T18:30:30 = 05/02/2008 18:30 1995-12-22T09:05:02 = 22/12/1995 09:05 -0010-09-15T04:44:23 = 15/09/-10 04:44 =head2 Available Formats =head3 Bh (h B) 2008-02-05T18:30:30 = 6 B 1995-12-22T09:05:02 = 9 B -0010-09-15T04:44:23 = 4 B =head3 Bhm (h:mm B) 2008-02-05T18:30:30 = 6:30 B 1995-12-22T09:05:02 = 9:05 B -0010-09-15T04:44:23 = 4:44 B =head3 Bhms (h:mm:ss B) 2008-02-05T18:30:30 = 6:30:30 B 1995-12-22T09:05:02 = 9:05:02 B -0010-09-15T04:44:23 = 4:44:23 B =head3 E (ccc) 2008-02-05T18:30:30 = Jnn 1995-12-22T09:05:02 = Iju -0010-09-15T04:44:23 = Jmo =head3 EBhm (E h:mm B) 2008-02-05T18:30:30 = Jnn 6:30 B 1995-12-22T09:05:02 = Iju 9:05 B -0010-09-15T04:44:23 = Jmo 4:44 B =head3 EBhms (E h:mm:ss B) 2008-02-05T18:30:30 = Jnn 6:30:30 B 1995-12-22T09:05:02 = Iju 9:05:02 B -0010-09-15T04:44:23 = Jmo 4:44:23 B =head3 EHm (E HH:mm) 2008-02-05T18:30:30 = Jnn 18:30 1995-12-22T09:05:02 = Iju 09:05 -0010-09-15T04:44:23 = Jmo 04:44 =head3 EHms (E HH:mm:ss) 2008-02-05T18:30:30 = Jnn 18:30:30 1995-12-22T09:05:02 = Iju 09:05:02 -0010-09-15T04:44:23 = Jmo 04:44:23 =head3 Ed (d, E) 2008-02-05T18:30:30 = 5, Jnn 1995-12-22T09:05:02 = 22, Iju -0010-09-15T04:44:23 = 15, Jmo =head3 Ehm (E h:mm a) 2008-02-05T18:30:30 = Jnn 6:30 kyiukonyi 1995-12-22T09:05:02 = Iju 9:05 utuko -0010-09-15T04:44:23 = Jmo 4:44 utuko =head3 Ehms (E h:mm:ss a) 2008-02-05T18:30:30 = Jnn 6:30:30 kyiukonyi 1995-12-22T09:05:02 = Iju 9:05:02 utuko -0010-09-15T04:44:23 = Jmo 4:44:23 utuko =head3 Gy (G y) 2008-02-05T18:30:30 = BK 2008 1995-12-22T09:05:02 = BK 1995 -0010-09-15T04:44:23 = KK -10 =head3 GyMMM (G y MMM) 2008-02-05T18:30:30 = BK 2008 Feb 1995-12-22T09:05:02 = BK 1995 Des -0010-09-15T04:44:23 = KK -10 Sep =head3 GyMMMEd (G y MMM d, E) 2008-02-05T18:30:30 = BK 2008 Feb 5, Jnn 1995-12-22T09:05:02 = BK 1995 Des 22, Iju -0010-09-15T04:44:23 = KK -10 Sep 15, Jmo =head3 GyMMMd (G y MMM d) 2008-02-05T18:30:30 = BK 2008 Feb 5 1995-12-22T09:05:02 = BK 1995 Des 22 -0010-09-15T04:44:23 = KK -10 Sep 15 =head3 H (HH) 2008-02-05T18:30:30 = 18 1995-12-22T09:05:02 = 09 -0010-09-15T04:44:23 = 04 =head3 Hm (HH:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 Hms (HH:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Hmsv (HH:mm:ss v) 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Hmv (HH:mm v) 2008-02-05T18:30:30 = 18:30 UTC 1995-12-22T09:05:02 = 09:05 UTC -0010-09-15T04:44:23 = 04:44 UTC =head3 M (L) 2008-02-05T18:30:30 = 2 1995-12-22T09:05:02 = 12 -0010-09-15T04:44:23 = 9 =head3 MEd (E, M/d) 2008-02-05T18:30:30 = Jnn, 2/5 1995-12-22T09:05:02 = Iju, 12/22 -0010-09-15T04:44:23 = Jmo, 9/15 =head3 MMM (LLL) 2008-02-05T18:30:30 = Feb 1995-12-22T09:05:02 = Des -0010-09-15T04:44:23 = Sep =head3 MMMEd (E, MMM d) 2008-02-05T18:30:30 = Jnn, Feb 5 1995-12-22T09:05:02 = Iju, Des 22 -0010-09-15T04:44:23 = Jmo, Sep 15 =head3 MMMMEd (E, MMMM d) 2008-02-05T18:30:30 = Jnn, Februari 5 1995-12-22T09:05:02 = Iju, Desemba 22 -0010-09-15T04:44:23 = Jmo, Septemba 15 =head3 MMMMW-count-other ('week' W 'of' MMMM) 2008-02-05T18:30:30 = week 1 of Februari 1995-12-22T09:05:02 = week 3 of Desemba -0010-09-15T04:44:23 = week 2 of Septemba =head3 MMMMd (MMMM d) 2008-02-05T18:30:30 = Februari 5 1995-12-22T09:05:02 = Desemba 22 -0010-09-15T04:44:23 = Septemba 15 =head3 MMMd (MMM d) 2008-02-05T18:30:30 = Feb 5 1995-12-22T09:05:02 = Des 22 -0010-09-15T04:44:23 = Sep 15 =head3 Md (M/d) 2008-02-05T18:30:30 = 2/5 1995-12-22T09:05:02 = 12/22 -0010-09-15T04:44:23 = 9/15 =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 h (h a) 2008-02-05T18:30:30 = 6 kyiukonyi 1995-12-22T09:05:02 = 9 utuko -0010-09-15T04:44:23 = 4 utuko =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 kyiukonyi 1995-12-22T09:05:02 = 9:05 utuko -0010-09-15T04:44:23 = 4:44 utuko =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 kyiukonyi 1995-12-22T09:05:02 = 9:05:02 utuko -0010-09-15T04:44:23 = 4:44:23 utuko =head3 hmsv (h:mm:ss a v) 2008-02-05T18:30:30 = 6:30:30 kyiukonyi UTC 1995-12-22T09:05:02 = 9:05:02 utuko UTC -0010-09-15T04:44:23 = 4:44:23 utuko UTC =head3 hmv (h:mm a v) 2008-02-05T18:30:30 = 6:30 kyiukonyi UTC 1995-12-22T09:05:02 = 9:05 utuko UTC -0010-09-15T04:44:23 = 4:44 utuko UTC =head3 ms (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (M/y) 2008-02-05T18:30:30 = 2/2008 1995-12-22T09:05:02 = 12/1995 -0010-09-15T04:44:23 = 9/-10 =head3 yMEd (E, M/d/y) 2008-02-05T18:30:30 = Jnn, 2/5/2008 1995-12-22T09:05:02 = Iju, 12/22/1995 -0010-09-15T04:44:23 = Jmo, 9/15/-10 =head3 yMMM (MMM y) 2008-02-05T18:30:30 = Feb 2008 1995-12-22T09:05:02 = Des 1995 -0010-09-15T04:44:23 = Sep -10 =head3 yMMMEd (E, MMM d, y) 2008-02-05T18:30:30 = Jnn, Feb 5, 2008 1995-12-22T09:05:02 = Iju, Des 22, 1995 -0010-09-15T04:44:23 = Jmo, Sep 15, -10 =head3 yMMMM (MMMM y) 2008-02-05T18:30:30 = Februari 2008 1995-12-22T09:05:02 = Desemba 1995 -0010-09-15T04:44:23 = Septemba -10 =head3 yMMMd (y MMM d) 2008-02-05T18:30:30 = 2008 Feb 5 1995-12-22T09:05:02 = 1995 Des 22 -0010-09-15T04:44:23 = -10 Sep 15 =head3 yMd (y-MM-dd) 2008-02-05T18:30:30 = 2008-02-05 1995-12-22T09:05:02 = 1995-12-22 -0010-09-15T04:44:23 = -10-09-15 =head3 yQQQ (QQQ y) 2008-02-05T18:30:30 = R1 2008 1995-12-22T09:05:02 = R4 1995 -0010-09-15T04:44:23 = R3 -10 =head3 yQQQQ (QQQQ y) 2008-02-05T18:30:30 = Robo 1 2008 1995-12-22T09:05:02 = Robo 4 1995 -0010-09-15T04:44:23 = Robo 3 -10 =head3 yw-count-other ('week' w 'of' Y) 2008-02-05T18:30:30 = week 6 of 2008 1995-12-22T09:05:02 = week 51 of 1995 -0010-09-15T04:44:23 = week 37 of -10 =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week 1 (Jumatatuu) =head1 SUPPORT See L<DateTime::Locale>. =cut
kiamazi/mira
local/lib/perl5/DateTime/Locale/rwk.pod
Perl
gpl-3.0
10,533