text
stringlengths
2
6.14k
# # Copyright (C) 2018 by YOUR NAME HERE # # This file is part of RoboComp # # RoboComp 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. # # RoboComp 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 RoboComp. If not, see <http://www.gnu.org/licenses/>. # import sys, os, traceback, time from PySide import QtGui, QtCore from learnbot_components.baserobot.src.genericworker import * from pololu_drv8835_rpi import motors, MAX_SPEED configPath = os.path.join(os.path.dirname(os.path.dirname(__file__)),'etc','config') def map(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min class SpecificWorker(GenericWorker): def __init__(self, proxy_map): super(SpecificWorker, self).__init__(proxy_map) self.timer.timeout.connect(self.compute) self.Period = 2000 motors.setSpeeds(0, 0) # self.timer.start(self.Period) def setParams(self, params): return True @QtCore.Slot() def compute(self): print('SpecificWorker.compute...') self.setSpeedBase(0, 0) return True def computeRobotSpeed(self, vAdv, vRot): radius = 75 # milimetros K = 11 # constante if (vRot == 0): vRot = 0.000000001 Rrot = vAdv / (vRot * 0.7) Rl = Rrot - radius velLeft = vRot * Rl Rr = Rrot + radius velRight = vRot * Rr velRight = map(velRight, -MAX_SPEED, MAX_SPEED,-300, 300) velLeft = map(velLeft, -MAX_SPEED, MAX_SPEED,-300, 300) if velRight > MAX_SPEED: velRight = MAX_SPEED if velLeft > MAX_SPEED: velLeft = MAX_SPEED return int(velLeft), int(velRight) def correctOdometer(self, x, z, alpha): pass def getBasePose(self): x = int() z = int() alpha = float() return [x, z, alpha] def resetOdometer(self): pass def setOdometer(self, state): pass def getBaseState(self): state = RoboCompGenericBase.TBaseState() return state def setOdometerPose(self, x, z, alpha): pass def stopBase(self): pass def setSpeedBase(self, adv, rot): velRight, velLeft = self.computeRobotSpeed(adv, rot) print("Velocidad motores = ", velLeft, velRight) motors.setSpeeds(velLeft, velRight)
# -*- coding: utf-8 -*- import sys import regex from contractions import Contractions class EnglishContractions(Contractions): def __init__(self): # List of contractions adapted from Robert MacIntyre's tokenizer. # These were in turn collected from the TreebankWordTokenizer in NLTK. self.CONTRACTIONS = [regex.compile(r"([^' ])('[sS]|'[mM]|'[dD]|')\b"), regex.compile( \ r"([^' ])('ll|'LL|'re|'RE|'ve|'VE|n't|N'T)\b")] self.CONTRACTIONS2 = [regex.compile(r"(?i)\b(can)(not)\b"), regex.compile(r"(?i)\b(d)('ye)\b"), regex.compile(r"(?i)\b(gim)(me)\b"), regex.compile(r"(?i)\b(gon)(na)\b"), regex.compile(r"(?i)\b(got)(ta)\b"), regex.compile(r"(?i)\b(lem)(me)\b"), regex.compile(r"(?i)\b(mor)('n)\b"), regex.compile(r"(?i)\b(wan)(na) ")] self.CONTRACTIONS3 = [regex.compile(r"(?i) ('t)(is)\b"), regex.compile(r"(?i) ('t)(was)\b")] self.CONTRACTIONS4 = [regex.compile(r"(?i)\b(whad)(dd)(ya)\b"), regex.compile(r"(?i)\b(wha)(t)(cha)\b")] def split_if_contraction(self, word): for regexp in self.CONTRACTIONS: word = regexp.sub(r'\1 \2', word) for regexp in self.CONTRACTIONS2: word = regexp.sub(r'\1 \2', word) for regexp in self.CONTRACTIONS3: word = regexp.sub(r'\1 \2', word) # We are not using CONTRACTIONS4 since # they are also commented out in the SED scripts # for regexp in self.CONTRACTIONS4: # word = regexp.sub(r'\1 \2 \3', word) return word
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.python.util.fast_module_type.""" from tensorflow.python.platform import test from tensorflow.python.util import fast_module_type FastModuleType = fast_module_type.get_fast_module_type_class() class ChildFastModule(FastModuleType): def _getattribute1(self, name): # pylint: disable=unused-argument return 2 def _getattribute2(self, name): # pylint: disable=unused-argument raise AttributeError("Pass to getattr") def _getattr(self, name): # pylint: disable=unused-argument return 3 class FastModuleTypeTest(test.TestCase): def testBaseGetattribute(self): # Tests that the default attribute lookup works. module = ChildFastModule("test") module.foo = 1 self.assertEqual(1, module.foo) def testGetattributeCallback(self): # Tests that functionality of __getattribute__ can be set as a callback. module = ChildFastModule("test") FastModuleType.set_getattribute_callback(module, ChildFastModule._getattribute1) self.assertEqual(2, module.foo) def testGetattrCallback(self): # Tests that functionality of __getattr__ can be set as a callback. module = ChildFastModule("test") FastModuleType.set_getattribute_callback(module, ChildFastModule._getattribute2) FastModuleType.set_getattr_callback(module, ChildFastModule._getattr) self.assertEqual(3, module.foo) def testFastdictApis(self): module = ChildFastModule("test") # At first "bar" does not exist in the module's attributes self.assertFalse(module._fastdict_key_in("bar")) with self.assertRaisesRegex(KeyError, "module has no attribute 'bar'"): module._fastdict_get("bar") module._fastdict_insert("bar", 1) # After _fastdict_insert() the attribute is added. self.assertTrue(module._fastdict_key_in("bar")) self.assertEqual(1, module.bar) if __name__ == "__main__": test.main()
# # File : package.py # This file is part of RT-Thread RTOS # COPYRIGHT (C) 2006 - 2015, RT-Thread Development Team # # 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. # # Change Logs: # Date Author Notes # 2015-04-10 Bernard First version # # this script is used to build group with package.json instead of SConscript import os from building import * def ExtendPackageVar(package, var): v = [] if not package.has_key(var): return v for item in package[var]: v = v + [item] return v def BuildPackage(package): import json f = file(package) package_json = f.read() # get package.json path cwd = os.path.dirname(package) package = json.loads(package_json) # check package name if not package.has_key('name'): return [] # get depends depend = ExtendPackageVar(package, 'depends') src = [] if package.has_key('source_files'): for src_file in package['source_files']: src_file = os.path.join(cwd, src_file) src += Glob(src_file) CPPPATH = [] if package.has_key('CPPPATH'): for path in package['CPPPATH']: if path.startswith('/') and os.path.isdir(path): CPPPATH = CPPPATH + [path] else: CPPPATH = CPPPATH + [os.path.join(cwd, path)] CPPDEFINES = ExtendPackageVar(package, 'CPPDEFINES') objs = DefineGroup(package['name'], src, depend = depend, CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES) return objs
package practice.java.multithreading.forkAndJoin; import java.util.Arrays; import java.util.concurrent.RecursiveTask; /** * Created by patrick on 6/18/2015. */ public class CalculatorTest extends RecursiveTask<Long> { private static final int THRESHOLD = 5; private int[] nums; public CalculatorTest(int[] nums){ this.nums = nums; } @Override protected Long compute() { long sum = 0; int len = nums.length; boolean canCompute = (len <= THRESHOLD); if(canCompute){ for(int num : nums){ sum += num; } }else{ int mid = len/2; CalculatorTest leftTask = new CalculatorTest(Arrays.copyOfRange(nums,0,mid)); CalculatorTest rightTask = new CalculatorTest(Arrays.copyOfRange(nums,mid,len)); leftTask.fork(); rightTask.fork(); long leftResult = leftTask.join(); long rightResult = rightTask.join(); sum += leftResult + rightResult; } return sum; } }
""" Django settings for recall project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) path = lambda root, *a: os.path.join(root, *a) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = bool(os.environ.get('DEBUG')) TEMPLATE_DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'render' ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'recall.urls' WSGI_APPLICATION = 'recall.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': 'db.sqlite3', # } # } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' TEMPLATE_DIRS = ( path(BASE_DIR, 'templates'), ) # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default': dj_database_url.config()} # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) if DEBUG: INSTALLED_APPS += [ 'debug_toolbar', ] MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_PATCH_SETTINGS = False
/** * \file * Copyright (C) 2006-2009 Jedox AG * * This program 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 at http://www.gnu.org/copyleft/gpl.html. * * 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., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA * * You may obtain a copy of the License at * * <a href="http://www.jedox.com/license_palo_bi_suite.txt"> * http://www.jedox.com/license_palo_bi_suite.txt * </a> * * If you are developing and distributing open source applications under the * GPL License, then you are free to use Worksheetserver under the GPL License. * For OEMs, ISVs, and VARs who distribute Worksheetserver with their products, * and do not license and distribute their source code under the GPL, Jedox provides * a flexible OEM Commercial License. */ // This file has been auto-generated. Don't change it by hand! #include "dml-textBullet_writers.hpp" #include "dml-textBullet_literals.hpp" namespace drawingml { namespace xio { void CT_TextBulletColorFollowText_writer::write_target_to(xml_writer& w) { } void CT_TextBulletSizeFollowText_writer::write_target_to(xml_writer& w) { } void ST_TextBulletSizePercent_writer::write_target_to(xml_writer& w) { ST_Percentage_writer::write_target_to(w); } void CT_TextBulletSizePercent_writer::write_target_to(xml_writer& w) { if (t()->val.present()) w.attribute(0, dml_textBullet_val_literal, context()->serialize(t()->val.get())); } void CT_TextBulletSizePoint_writer::write_target_to(xml_writer& w) { if (t()->val.present()) w.attribute(0, dml_textBullet_val_literal, context()->serialize(t()->val.get())); } void CT_TextBulletTypefaceFollowText_writer::write_target_to(xml_writer& w) { } void CT_TextNoBullet_writer::write_target_to(xml_writer& w) { } void ST_TextBulletStartAtNum_writer::write_target_to(xml_writer& w) { w.write_element_value(context()->serialize(*t())); } void CT_TextAutonumberBullet_writer::write_target_to(xml_writer& w) { w.attribute(0, dml_textBullet_type_literal, context()->serialize(t()->type)); if (t()->startAt != 1) w.attribute(0, dml_textBullet_startAt_literal, context()->serialize(t()->startAt)); } void CT_TextCharBullet_writer::write_target_to(xml_writer& w) { w.attribute(0, dml_textBullet__char__literal, context()->serialize(t()->_char_)); } void CT_TextBlipBullet_writer::write_target_to(xml_writer& w) { w.start_element(0, dml_textBullet_blip_literal); _blip_writer.get_writer(context(), &t()->blip)->write_target_to(w); w.end_element(0, dml_textBullet_blip_literal); } } }
"""Vector Spherical Harmonics module. Based on my matlab functions.""" #TobiaC 2015-07-25 import sys import math import cmath import scipy.special import numpy def Psi(l,m,theta,phi): """Computes the components of the zenithal Vector Spherical Harmonic function with l and m quantal numbers in the theta,phi direction.""" if numpy.isscalar(theta): theta=numpy.array([[theta]]) phi=numpy.array([[phi]]) Psilm_th=numpy.zeros(theta.shape,dtype=complex) Psilm_ph=numpy.zeros(theta.shape,dtype=complex) x=numpy.cos(theta) thetaNonZerosIdx=numpy.where(theta!=0.0) if len(thetaNonZerosIdx[0]) != 0: Ylm=scipy.special.sph_harm(m,l,phi[thetaNonZerosIdx],theta[thetaNonZerosIdx]) #Compute derivative of sphrHarm function w.r.t. theta: if l>=numpy.abs(m): Plmpo=legendreLM(l,m+1,x[thetaNonZerosIdx]) YlmPmpo=math.sqrt((2*l+1)/(4*math.pi)*math.factorial(l-m)/float(math.factorial(l+m)))*Plmpo*numpy.exp(1j*m*phi[thetaNonZerosIdx]) #YlmPmpo=sqrt((l-m)*(l+m+1))*spharm(l,m+1,theta,phi)*exp(-i*phi) %Should be equivalent to above formula. dtYlm=+YlmPmpo+m*x[thetaNonZerosIdx]*Ylm/numpy.sin(theta[thetaNonZerosIdx]) # thetZerInd=[find(theta==0); find(theta==pi)] # dtYlm(thetZerInd)=0; %This is a fudge to remove NaNs else: dtYlm=numpy.zeros(theta[thetaNonZerosIdx].shape,dtype=complex) #dtYlm=spharmDtheta(l,m,theta,phi) Psilm_ph[thetaNonZerosIdx]=+1j*m/numpy.sin(theta[thetaNonZerosIdx])*Ylm Psilm_th[thetaNonZerosIdx]=+dtYlm #Ref: http://mathworld.wolfram.com/VectorSphericalHarmonic.html thetaZerosIdx=numpy.where(theta==0.0) if len(thetaZerosIdx[0]) != 0: if numpy.abs(m)==1: Yl1B=math.sqrt((2*l+1)/(4*math.pi)*math.factorial(l-m)/math.factorial(l+m))*PBl1(l,m)*numpy.exp(1j*m*phi[thetaZerosIdx]) Plmpo=legendreLM(l,m+1,x[thetaZerosIdx]) YlmPmpo=math.sqrt((2*l+1)/(4*math.pi)*math.factorial(l-m)/math.factorial(l+m))*Plmpo*numpy.exp(1j*m*phi[thetaZerosIdx]) dtYlm=+YlmPmpo+m*Yl1B Psilm_ph[thetaZerosIdx]=+1j*m*Yl1B Psilm_th[thetaZerosIdx]=+dtYlm else: Plmpo=legendreLM(l,m+1,x[thetaZerosIdx]) YlmPmpo=math.sqrt((2*l+1)/(4*math.pi)*math.factorial(l-m)/math.factorial(l+m))*Plmpo*numpy.exp(1j*m*phi[thetaZerosIdx]) dtYlm=+YlmPmpo+0 Psilm_ph[thetaZerosIdx]=0 Psilm_th[thetaZerosIdx]=+dtYlm return Psilm_th,Psilm_ph def Phi(l,m,theta,phi): """Computes the components of the azimuthal Vector Spherical Harmonic function with l and m quantal numbers in the theta,phi direction.""" Psilm_th, Psilm_ph=Psi(l,m,theta,phi); Philm_th=-Psilm_ph; Philm_ph=+Psilm_th; return Philm_th, Philm_ph def K(s,n,m,theta,phi): #Hansen1988 far-field functions. Needs to be corrected. if s==1: K_th,K_ph= Psi(n,m,theta,phi) elif s==2: K_th,K_ph=Phi(n,m,theta,phi) return K_th, K_ph def legendreLM(l,m,x): lout=scipy.special.lpmv(abs(m),l,x) if m<0: m=abs(m) lout=(-1)**m*math.factorial(l-m)/math.factorial(l+m)*lout return(lout) def PBl1(l_target, m): """Compute the value of the apparent singularity for a function within the VSH at the north pole. The function is P_l^m(x)/\sqrt{1-x^2} where P_l^m(x) is the associate Legendre polynomial. It is evaluated for x=+1 and |m|=1. (For |m|>1 this function is 0 at x=+1.) (This function is called by vshPhi and vshPsi)""" #TobiaC 2011-10-13 (2011-10-13) PBtab=numpy.array([0.0, -1.0, -3.0]) l=2 while l_target>l: PBlp1=((2*l+1)*PBtab[l +0]-(l+1)*PBtab[l-1 +0])/float(l) PBtab=numpy.hstack((PBtab, numpy.array([PBlp1]))) l=l+1 if m==1: PBout=PBtab[l_target +0] else: if m==-1: PBout=-math.factorial(l_target-1)/float(math.factorial(l_target+1))*PBtab[l_target +0] else: PBout=0.0 return PBout def vsfun(Q_slm, theta, phi,f=[]): """Direct computation of a vector function with spherical components theta,phi based on the vector spherical harmonics expansion with coefficients Q_slm.""" vsf_th=numpy.zeros(theta.shape, dtype='complex') vsf_ph=numpy.zeros(theta.shape, dtype='complex') for (s,l,m) in Q_slm: vsh_th,vsh_ph=K(s, l, m, theta, phi) c_slm=Q_slm.getBysnm(s, l, m) if not(f) else Q_slm.getBysnm(s, l, m)(f) vsf_th=vsf_th+c_slm*vsh_th vsf_ph=vsf_ph+c_slm*vsh_ph return vsf_th, vsf_ph
/* * File : trap.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2013, RT-Thread Develop Team * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rt-thread.org/license/LICENSE * * Change Logs: * Date Author Notes * 2013-07-20 Bernard first version */ #include <rthw.h> #include <board.h> #include <rtthread.h> #include "armv7.h" extern struct rt_thread *rt_current_thread; #ifdef RT_USING_FINSH extern long list_thread(void); #endif /** * this function will show registers of CPU * * @param regs the registers point */ void rt_hw_show_register(struct rt_hw_exp_stack *regs) { rt_kprintf("Execption:\n"); rt_kprintf("r00:0x%08x r01:0x%08x r02:0x%08x r03:0x%08x\n", regs->r0, regs->r1, regs->r2, regs->r3); rt_kprintf("r04:0x%08x r05:0x%08x r06:0x%08x r07:0x%08x\n", regs->r4, regs->r5, regs->r6, regs->r7); rt_kprintf("r08:0x%08x r09:0x%08x r10:0x%08x\n", regs->r8, regs->r9, regs->r10); rt_kprintf("fp :0x%08x ip :0x%08x\n", regs->fp, regs->ip); rt_kprintf("sp :0x%08x lr :0x%08x pc :0x%08x\n", regs->sp, regs->lr, regs->pc); rt_kprintf("cpsr:0x%08x\n", regs->cpsr); } /** * When comes across an instruction which it cannot handle, * it takes the undefined instruction trap. * * @param regs system registers * * @note never invoke this function in application */ void rt_hw_trap_undef(struct rt_hw_exp_stack *regs) { rt_kprintf("undefined instruction:\n"); rt_hw_show_register(regs); #ifdef RT_USING_FINSH list_thread(); #endif rt_hw_cpu_shutdown(); } /** * The software interrupt instruction (SWI) is used for entering * Supervisor mode, usually to request a particular supervisor * function. * * @param regs system registers * * @note never invoke this function in application */ void rt_hw_trap_swi(struct rt_hw_exp_stack *regs) { rt_kprintf("software interrupt:\n"); rt_hw_show_register(regs); #ifdef RT_USING_FINSH list_thread(); #endif rt_hw_cpu_shutdown(); } /** * An abort indicates that the current memory access cannot be completed, * which occurs during an instruction prefetch. * * @param regs system registers * * @note never invoke this function in application */ void rt_hw_trap_pabt(struct rt_hw_exp_stack *regs) { rt_kprintf("prefetch abort:\n"); rt_hw_show_register(regs); #ifdef RT_USING_FINSH list_thread(); #endif rt_hw_cpu_shutdown(); } /** * An abort indicates that the current memory access cannot be completed, * which occurs during a data access. * * @param regs system registers * * @note never invoke this function in application */ void rt_hw_trap_dabt(struct rt_hw_exp_stack *regs) { rt_kprintf("data abort:"); rt_hw_show_register(regs); #ifdef RT_USING_FINSH list_thread(); #endif rt_hw_cpu_shutdown(); } /** * Normally, system will never reach here * * @param regs system registers * * @note never invoke this function in application */ void rt_hw_trap_resv(struct rt_hw_exp_stack *regs) { rt_kprintf("reserved trap:\n"); rt_hw_show_register(regs); #ifdef RT_USING_FINSH list_thread(); #endif rt_hw_cpu_shutdown(); } void rt_hw_trap_irq(void) { void *param; rt_isr_handler_t isr_func; extern struct rt_irq_desc isr_table[]; uint32_t value = 0; // rt_kprintf("pend basic: 0x%08x\n", IRQ_PEND_BASIC); // rt_kprintf(" pend1: 0x%08x\n", IRQ_PEND1); // rt_kprintf(" pend2: 0x%08x\n", IRQ_PEND2); value = IRQ_PEND_BASIC & 0x3ff; if (value) { uint32_t irq; if (value & (1 << 8)) { value = IRQ_PEND1; irq = __rt_ffs(value) - 1; } else if (value & (1 << 9)) { value = IRQ_PEND2; irq = __rt_ffs(value) + 31; } else { value &= 0x0f; irq = __rt_ffs(value) - 1; } /* get interrupt service routine */ isr_func = isr_table[irq].handler; #ifdef RT_USING_INTERRUPT_INFO isr_table[irq].counter++; #endif if (isr_func) { /* Interrupt for myself. */ param = isr_table[irq].param; /* turn to interrupt service routine */ isr_func(irq, param); } } } void rt_hw_trap_fiq(void) { /* TODO */ }
define( //begin v1.x content { "days-standAlone-short": [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], "field-weekday": "Dia da semana", "field-wed-relative+0": "esta quarta-feira", "field-wed-relative+1": "próxima quarta-feira", "dateFormatItem-GyMMMEd": "E, d 'de' MMM 'de' y G", "dateFormatItem-MMMEd": "E, d 'de' MMM", "field-tue-relative+-1": "terça-feira passada", "days-format-short": [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], "dateFormat-long": "d 'de' MMMM 'de' y G", "field-fri-relative+-1": "sexta-feira passada", "field-wed-relative+-1": "quarta-feira passada", "dateFormatItem-yyyyQQQ": "QQQQ 'de' y G", "dateTimeFormat-medium": "{1}, {0}", "dayPeriods-format-wide-pm": "da tarde", "dateFormat-full": "EEEE, d 'de' MMMM 'de' y G", "dateFormatItem-yyyyMEd": "E, dd/MM/y GGGGG", "field-thu-relative+-1": "quinta-feira passada", "dateFormatItem-Md": "d/M", "dayPeriods-format-abbr-am": "a.m.", "dayPeriods-format-wide-noon": "meio-dia", "field-era": "Era", "quarters-format-wide": [ "1.º trimestre", "2.º trimestre", "3.º trimestre", "4.º trimestre" ], "field-year": "Ano", "field-hour": "Hora", "field-sat-relative+0": "este sábado", "field-sat-relative+1": "próximo sábado", "field-day-relative+0": "hoje", "field-thu-relative+0": "esta quinta-feira", "field-day-relative+1": "amanhã", "field-thu-relative+1": "próxima quinta-feira", "dateFormatItem-GyMMMd": "d 'de' MMM 'de' y G", "field-day-relative+2": "depois de amanhã", "quarters-format-abbr": [ "T1", "T2", "T3", "T4" ], "quarters-standAlone-wide": [ "1.º trimestre", "2.º trimestre", "3.º trimestre", "4.º trimestre" ], "dateFormatItem-Gy": "y G", "dateFormatItem-yyyyMMMEd": "E, d/MM/y G", "days-standAlone-wide": [ "domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado" ], "dateFormatItem-yyyyMMM": "MM/y G", "dateFormatItem-yyyyMMMd": "d/MM/y G", "field-sun-relative+0": "este domingo", "field-sun-relative+1": "próximo domingo", "quarters-standAlone-abbr": [ "T1", "T2", "T3", "T4" ], "field-minute": "Minuto", "field-dayperiod": "Da manhã/da tarde", "days-standAlone-abbr": [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], "field-day-relative+-1": "ontem", "dateTimeFormat-long": "{1} 'às' {0}", "dayPeriods-format-narrow-am": "a.m.", "field-day-relative+-2": "anteontem", "dateFormatItem-MMMd": "d 'de' MMM", "dateFormatItem-MEd": "E, dd/MM", "dateTimeFormat-full": "{1} 'às' {0}", "field-fri-relative+0": "esta sexta-feira", "field-fri-relative+1": "próxima sexta-feira", "field-day": "Dia", "days-format-wide": [ "domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado" ], "field-zone": "Fuso horário", "dateFormatItem-y": "y G", "field-year-relative+-1": "ano passado", "field-month-relative+-1": "mês passado", "dayPeriods-format-abbr-pm": "p.m.", "days-format-abbr": [ "dom", "seg", "ter", "qua", "qui", "sex", "sáb" ], "days-format-narrow": [ "D", "S", "T", "Q", "Q", "S", "S" ], "dateFormatItem-yyyyMd": "dd/MM/y GGGGG", "field-month": "Mês", "days-standAlone-narrow": [ "D", "S", "T", "Q", "Q", "S", "S" ], "field-tue-relative+0": "esta terça-feira", "field-tue-relative+1": "próxima terça-feira", "dayPeriods-format-wide-am": "da manhã", "field-mon-relative+0": "esta segunda-feira", "field-mon-relative+1": "próxima segunda-feira", "dateFormat-short": "d/M/y G", "field-second": "Segundo", "field-sat-relative+-1": "sábado passado", "field-sun-relative+-1": "domingo passado", "field-month-relative+0": "este mês", "field-month-relative+1": "próximo mês", "dateFormatItem-Ed": "E, d", "field-week": "Semana", "dateFormat-medium": "d 'de' MMM, y G", "field-year-relative+0": "este ano", "field-week-relative+-1": "semana passada", "dateFormatItem-yyyyM": "MM/y GGGGG", "field-year-relative+1": "próximo ano", "dayPeriods-format-narrow-pm": "p.m.", "dateFormatItem-yyyyQQQQ": "QQQQ 'de' y G", "dateTimeFormat-short": "{1}, {0}", "dateFormatItem-GyMMM": "MMM 'de' y G", "field-mon-relative+-1": "segunda-feira passada", "dateFormatItem-yyyy": "y G", "field-week-relative+0": "esta semana", "field-week-relative+1": "próxima semana" } //end v1.x content );
# Copyright 2015 eNovance # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import mock from oslo_db.sqlalchemy import test_migrations import six from gnocchi.indexer import sqlalchemy_base from gnocchi.tests import base class ABCSkip(base.SkipNotImplementedMeta, abc.ABCMeta): pass class ModelsMigrationsSync( six.with_metaclass(ABCSkip, base.TestCase, test_migrations.ModelsMigrationsSync)): def setUp(self): super(ModelsMigrationsSync, self).setUp() # NOTE(jd) This only works with PostgreSQL for now because of # https://bitbucket.org/zzzeek/alembic/issue/296/unable-to-compare-custom-with-different if not self.conf.indexer.url.startswith("postgresql"): self.skipTest("This test only works with PostgreSQL") self.db = mock.Mock() @staticmethod def get_metadata(): return sqlalchemy_base.Base.metadata def get_engine(self): return self.index.engine_facade.get_engine() @staticmethod def db_sync(engine): # NOTE(jd) Nothing to do here as setUp() in the base class is already # creating table using upgrade pass
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Public License version 2.1 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.LGPL" in the source distribution for more information. # # Headers in this file shall remain intact. from zope.interface import implements from flumotion.transcoder.admin.datastore import config from flumotion.transcoder.admin.api import interfaces, api class BaseConfigMedium(api.Medium): implements(interfaces.IConfigMedium) api.readonly_property("type") def __init__(self, confStore): super(BaseConfigMedium, self).__init__(confStore) class IdentityConfigMedium(BaseConfigMedium): implements(interfaces.IIdentityConfigMedium) api.register_medium(interfaces.IIdentityConfigMedium, config.IIdentityConfigStore) def __init__(self, confStore): super(IdentityConfigMedium, self).__init__(confStore) class AudioConfigMedium(BaseConfigMedium): implements(interfaces.IAudioConfigMedium) api.register_medium(interfaces.IAudioConfigMedium, config.IAudioConfigStore) api.readonly_property("muxer") api.readonly_property("audioEncoder") api.readonly_property("audioRate") api.readonly_property("audioChannels") def __init__(self, confStore): super(AudioConfigMedium, self).__init__(confStore) class VideoConfigMedium(BaseConfigMedium): implements(interfaces.IVideoConfigMedium) api.register_medium(interfaces.IVideoConfigMedium, config.IVideoConfigStore) api.readonly_property("muxer") api.readonly_property("videoEncoder") api.readonly_property("videoWidth") api.readonly_property("videoHeight") api.readonly_property("videoMaxWidth") api.readonly_property("videoMaxHeight") api.readonly_property("videoWidthMultiple") api.readonly_property("videoHeightMultiple") api.readonly_property("videoPAR") api.readonly_property("videoFramerate") api.readonly_property("videoScaleMethod") def __init__(self, confStore): super(VideoConfigMedium, self).__init__(confStore) class AudioVideoConfigMedium(AudioConfigMedium, VideoConfigMedium): implements(interfaces.IAudioVideoConfigMedium) api.register_medium(interfaces.IAudioVideoConfigMedium, config.IAudioVideoConfigStore) api.readonly_property("tolerance") def __init__(self, confStore): super(AudioVideoConfigMedium, self).__init__(confStore) class ThumbnailsConfigMedium(BaseConfigMedium): implements(interfaces.IThumbnailsConfigMedium) api.register_medium(interfaces.IThumbnailsConfigMedium, config.IThumbnailsConfigStore) api.readonly_property("thumbsWidth") api.readonly_property("thumbsHeight") api.readonly_property("periodValue") api.readonly_property("periodUnit") api.readonly_property("maxCount") api.readonly_property("ensureOne") api.readonly_property("format") def __init__(self, confStore): super(ThumbnailsConfigMedium, self).__init__(confStore)
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>red</title> <link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg"> <script>var pathToRoot = "../../../../";</script> <script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script> <link href="../../../../styles/style.css" rel="Stylesheet"> <link href="../../../../styles/logo-styles.css" rel="Stylesheet"> <link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../../styles/main.css" rel="Stylesheet"> <script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script> <script type="text/javascript" src="../../../../scripts/main.js" async="async"></script> </head> <body> <div id="container"> <div id="leftColumn"> <div id="logo"></div> <div id="paneSearch"></div> <div id="sideMenu"></div> </div> <div id="main"> <div id="leftToggler"><span class="icon-toggler"></span></div> <script type="text/javascript" src="../../../../scripts/pages.js"></script> <script type="text/javascript" src="../../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="org.hexworks.zircon.api.color/ANSITileColor.BLACK/red/#/PointingToDeclaration//-755115832"> <div class="navigation-wrapper" id="navigation-wrapper"> <div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.api.color</a>/<a href="../index.html">ANSITileColor</a>/<a href="index.html">BLACK</a>/<a href="red.html">red</a></div> <div class="pull-right d-flex"> <div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div> <div id="searchBar"></div> </div> </div> <div class="cover "> <h1 class="cover"><span>red</span></h1> </div> <div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div> <div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">override val <a href="red.html">red</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html">Int</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div> </div> </div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
<!DOCTYPE html> <!-- Copyright (c) 2013 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. Authors: Xu Yuhan <yuhanx.xu@intel.com> --> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, width=device-width"> <link rel="stylesheet" type="text/css" href="../../css/jquery.mobile.css" /> <link rel="stylesheet" type="text/css" href="../../css/main.css" /> <script src="../../js/thirdparty/jquery.js"></script> <script src="../../js/thirdparty/jquery.mobile.js"></script> <script src="../../js/tests.js"></script> </head> <body> <div data-role="page" id="main"> <div data-role="header"> <h1 id="main_page_title"></h1> </div> <div data-role="content"> <a data-role="button" href="res/index.html" class="wgtButton" data-ajax="false">Launch Test Page</a> </div> <div data-role="footer" data-position="fixed"> </div> <div data-role="popup" id="popup_info"> <font class="fontSize"> <p>Purpose:</p> <p>Verifies that enable web app gesture</p> <p>Test steps:</p> <ol> <li>Click the button "Launch Test Page"</li> <li>Scroll up screen</li> <li>Scroll down screen</li> </ol> <p>Expected Result:</p> <ol> <li>Test page displayed successfully</li> <li>Interface with gestures to scroll up successfully</li> <li>Interface with gestures to scroll down successfully</li> </ol> </font> </div> </div> </body> </html>
# Copyright 2015-present Scikit Flow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import tensorflow as tf from skflow import ops class DropoutTest(tf.test.TestCase): def test_dropout_float(self): with self.test_session() as session: x = tf.placeholder(tf.float32, [5, 5]) y = ops.dropout(x, 0.5) probs = tf.get_collection(ops.DROPOUTS) session.run(tf.initialize_all_variables()) self.assertEqual(len(probs), 1) self.assertEqual(session.run(probs[0]), 0.5) def test_dropout_tensor(self): with self.test_session(): x = tf.placeholder(tf.float32, [5, 5]) y = tf.get_variable("prob", [], initializer=tf.constant_initializer(0.5)) z = ops.dropout(x, y) probs = tf.get_collection(ops.DROPOUTS) self.assertEqual(probs, [y]) if __name__ == '__main__': tf.test.main()
# Based on iwidgets2.2.0/promptdialog.itk code. import Pmw # A Dialog with an entryfield class PromptDialog(Pmw.Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. INITOPT = Pmw.INITOPT optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Pmw.Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('entry', 'entryfield_entry'), ('label', 'entryfield_label'), ) self._promptDialogEntry = self.createcomponent('entryfield', aliases, None, Pmw.EntryField, (interior,)) self._promptDialogEntry.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # EntryField's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._promptDialogEntry.insert(index, text) def deleteentry(self, first, last=None): self._promptDialogEntry.delete(first, last) def indexentry(self, index): return self._promptDialogEntry.index(index) Pmw.forwardmethods(PromptDialog, Pmw.EntryField, '_promptDialogEntry')
using UnityEngine; using System.Collections; public class ButtonScript : MonoBehaviour { public GameObject explosion; public AudioClip explosion_asteroid; public AudioSource audioSource; void OnTriggerEnter (Collider other) { if (other.gameObject.tag == "Shot") { Debug.Log(explosion); if (explosion != null) { audioSource.clip = explosion_asteroid; audioSource.Play(); Debug.Log("Sounds should have been played."); //explosion.GetComponent<Animation>().Play(); Instantiate(explosion, transform.position, transform.rotation); } if (transform.parent != null) { MainMenuScript script = transform.parent.gameObject.GetComponent<MainMenuScript>(); switch (this.name) { case "btn_Start": //Debug.Log("Start pressed"); script.btnStartPressed(); break; case "btn_Settings": //Debug.Log("Settings pressed"); script.btnSettingsPressed(); break; case "btn_Exit": //Debug.Log("Exit pressed"); script.btnExitPressed(); break; case "btnStartExplode": //Debug.Log("Start pressed"); script.btnStartPressed(); break; case "btnOptionsExplode": //Debug.Log("Settings pressed"); script.btnSettingsPressed(); break; case "btnExitExplode": //Debug.Log("Exit pressed"); script.btnExitPressed(); break; case "btn_Highscore": script.btnHighscorePressed(); break; case "btnHighscore": script.btnHighscorePressed(); break; default: Debug.Log("Nothing"); break; } } Destroy(other.gameObject); Destroy(gameObject); } } }
#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_seal version_added: "1.2.0" short_description: Hashicorp Vault seal module description: - Module to seal Hashicorp Vault. extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_seal: register: 'vault_seal' - debug: msg="Seal return is {{vault_seal.rc}}" ''' def main(): argspec = hashivault_argspec() module = hashivault_init(argspec) result = hashivault_seal(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_seal(params): client = hashivault_auth_client(params) if not client.sys.is_sealed(): status = client.sys.seal().ok return {'status': status, 'changed': True} else: return {'changed': False} if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 09:34:59 2015 @author: mehdi.rahim@cea.fr """ from base_connectivity import Connectivity import numpy as np from fetch_data import fetch_adni_baseline_rs_fmri, fetch_adni_masks, \ set_cache_base_dir, set_group_indices, fetch_adni_longitudinal_rs_fmri_DARTEL from nilearn.plotting import plot_connectome from scipy import stats CACHE_DIR = set_cache_base_dir() dataset = fetch_adni_baseline_rs_fmri() #dataset = fetch_adni_longitudinal_rs_fmri_DARTEL() mask = fetch_adni_masks()['mask_fmri'] atlas_name = 'mayo' metric = 'correlation' conn = Connectivity(atlas_name=atlas_name, rois=True, metric=metric, mask=mask, detrend=True, low_pass=.1, high_pass=.01, t_r=3., resampling_target='data', smoothing_fwhm=6., memory=CACHE_DIR, memory_level=2, n_jobs=20) fc = conn.fit(dataset.func) np.savez_compressed('longitudinal_dartel_fc', data=fc) idx = set_group_indices(dataset.dx_group) groups = [['AD', 'MCI'], ['AD', 'Normal'], ['MCI', 'Normal']] for g in groups: t, p = stats.ttest_ind(fc[idx[g[0]]], fc[idx[g[1]]]) tv = t tv[np.where(p>.01)] = 0 n_rois = conn.rois['n_rois'] centroids = conn.rois['rois_centroids'] ind = np.tril_indices(n_rois, k=-1) m = np.zeros((n_rois, n_rois)) m[ind] = tv m = .5 * (m + m.T) plot_connectome(m, centroids, title='_'.join(g))
#!/home/oleg/Web/Hack70/env/bin/python3 # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-30 fl Optimize output (PNG, JPEG) # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) # 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter) # from __future__ import print_function import getopt import string import sys from PIL import Image def usage(): print("PIL Convert 0.5/1998-12-30 -- convert image files") print("Usage: pilconvert [option] infile outfile") print() print("Options:") print() print(" -c <format> convert to format (default is given by extension)") print() print(" -g convert to greyscale") print(" -p convert to palette image (using standard palette)") print(" -r convert to rgb") print() print(" -o optimize output (trade speed for size)") print(" -q <value> set compression quality (0-100, JPEG only)") print() print(" -f list supported file formats") sys.exit(1) if len(sys.argv) == 1: usage() try: opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r") except getopt.error as v: print(v) sys.exit(1) output_format = None convert = None options = {} for o, a in opt: if o == "-f": Image.init() id = sorted(Image.ID) print("Supported formats (* indicates output format):") for i in id: if i in Image.SAVE: print(i+"*", end=' ') else: print(i, end=' ') sys.exit(1) elif o == "-c": output_format = a if o == "-g": convert = "L" elif o == "-p": convert = "P" elif o == "-r": convert = "RGB" elif o == "-o": options["optimize"] = 1 elif o == "-q": options["quality"] = string.atoi(a) if len(argv) != 2: usage() try: im = Image.open(argv[0]) if convert and im.mode != convert: im.draft(convert, im.size) im = im.convert(convert) if output_format: im.save(argv[1], output_format, **options) else: im.save(argv[1], **options) except: print("cannot convert image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
/** * Created by david on 1/31/2017. */ let express = require('express'); import path = require('path'); import process = require('process'); let app = new express(); app.use('/', express.static(process.cwd())); app.listen(3000); console.log('listening to port 3000');
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60-ea) on Tue Aug 16 17:15:32 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.keycloak (Public javadocs 2016.8.1 API)</title> <meta name="date" content="2016-08-16"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../org/wildfly/swarm/keycloak/package-summary.html" target="classFrame">org.wildfly.swarm.keycloak</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="Secured.html" title="interface in org.wildfly.swarm.keycloak" target="classFrame"><span class="interfaceName">Secured</span></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="KeycloakFraction.html" title="class in org.wildfly.swarm.keycloak" target="classFrame">KeycloakFraction</a></li> </ul> </div> </body> </html>
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.util; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** * Adapter class that wraps an <code>Enumeration</code> around a Java2 * collection classes object <code>Iterator</code> so that existing APIs * returning Enumerations can easily run on top of the new collections. * Constructors are provided to easily create such wrappers. * * @author Craig R. McClanahan * @deprecated Replaced by java.util.Collections#enumeration(..) */ @Deprecated public final class Enumerator<T> implements Enumeration<T> { // ----------------------------------------------------------- Constructors /** * Return an Enumeration over the values of the specified Collection. * * @param collection Collection whose values should be enumerated */ public Enumerator(Collection<T> collection) { this(collection.iterator()); } /** * Return an Enumeration over the values of the specified Collection. * * @param collection Collection whose values should be enumerated * @param clone true to clone iterator */ public Enumerator(Collection<T> collection, boolean clone) { this(collection.iterator(), clone); } /** * Return an Enumeration over the values returned by the * specified Iterator. * * @param iterator Iterator to be wrapped */ public Enumerator(Iterator<T> iterator) { super(); this.iterator = iterator; } /** * Return an Enumeration over the values returned by the * specified Iterator. * * @param iterator Iterator to be wrapped * @param clone true to clone iterator */ public Enumerator(Iterator<T> iterator, boolean clone) { super(); if (!clone) { this.iterator = iterator; } else { List<T> list = new ArrayList<T>(); while (iterator.hasNext()) { list.add(iterator.next()); } this.iterator = list.iterator(); } } /** * Return an Enumeration over the values of the specified Map. * * @param map Map whose values should be enumerated */ public Enumerator(Map<?,T> map) { this(map.values().iterator()); } /** * Return an Enumeration over the values of the specified Map. * * @param map Map whose values should be enumerated * @param clone true to clone iterator */ public Enumerator(Map<?,T> map, boolean clone) { this(map.values().iterator(), clone); } // ----------------------------------------------------- Instance Variables /** * The <code>Iterator</code> over which the <code>Enumeration</code> * represented by this class actually operates. */ private Iterator<T> iterator = null; // --------------------------------------------------------- Public Methods /** * Tests if this enumeration contains more elements. * * @return <code>true</code> if and only if this enumeration object * contains at least one more element to provide, <code>false</code> * otherwise */ @Override public boolean hasMoreElements() { return (iterator.hasNext()); } /** * Returns the next element of this enumeration if this enumeration * has at least one more element to provide. * * @return the next element of this enumeration * * @exception NoSuchElementException if no more elements exist */ @Override public T nextElement() throws NoSuchElementException { return (iterator.next()); } }
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging import re from webkitpy.common.webkit_finder import WebKitFinder from webkitpy.layout_tests.breakpad.dump_reader_multipart import DumpReaderLinux from webkitpy.layout_tests.models import test_run_results from webkitpy.layout_tests.port import base from webkitpy.layout_tests.port import win from webkitpy.layout_tests.port import config _log = logging.getLogger(__name__) class LinuxPort(base.Port): port_name = 'linux' SUPPORTED_VERSIONS = ('precise', 'trusty') FALLBACK_PATHS = {} FALLBACK_PATHS['trusty'] = ['linux'] + win.WinPort.latest_platform_fallback_path() FALLBACK_PATHS['precise'] = ['linux-precise'] + FALLBACK_PATHS['trusty'] DEFAULT_BUILD_DIRECTORIES = ('out',) BUILD_REQUIREMENTS_URL = 'https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md' @classmethod def determine_full_port_name(cls, host, options, port_name): if port_name.endswith('linux'): assert host.platform.is_linux() version = host.platform.os_version return port_name + '-' + version return port_name def __init__(self, host, port_name, **kwargs): super(LinuxPort, self).__init__(host, port_name, **kwargs) self._version = port_name[port_name.index('linux-') + len('linux-'):] self._architecture = "x86_64" assert self._version in self.SUPPORTED_VERSIONS if not self.get_option('disable_breakpad'): self._dump_reader = DumpReaderLinux(host, self._build_path()) def additional_driver_flag(self): flags = super(LinuxPort, self).additional_driver_flag() if not self.get_option('disable_breakpad'): flags += ['--enable-crash-reporter', '--crash-dumps-dir=%s' % self._dump_reader.crash_dumps_directory()] return flags def check_build(self, needs_http, printer): result = super(LinuxPort, self).check_build(needs_http, printer) if result: _log.error('For complete Linux build requirements, please see:') _log.error('') _log.error(' https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md') return result def look_for_new_crash_logs(self, crashed_processes, start_time): if self.get_option('disable_breakpad'): return None return self._dump_reader.look_for_new_crash_logs(crashed_processes, start_time) def clobber_old_port_specific_results(self): if not self.get_option('disable_breakpad'): self._dump_reader.clobber_old_results() def operating_system(self): return 'linux' def path_to_apache(self): # The Apache binary path can vary depending on OS and distribution # See http://wiki.apache.org/httpd/DistrosDefaultLayout for path in ["/usr/sbin/httpd", "/usr/sbin/apache2"]: if self._filesystem.exists(path): return path _log.error("Could not find apache. Not installed or unknown path.") return None # # PROTECTED METHODS # def _check_apache_install(self): result = self._check_file_exists(self.path_to_apache(), "apache2") result = self._check_file_exists(self.path_to_apache_config_file(), "apache2 config file") and result if not result: _log.error(' Please install using: "sudo apt-get install apache2 libapache2-mod-php5"') _log.error('') return result def _wdiff_missing_message(self): return 'wdiff is not installed; please install using "sudo apt-get install wdiff"' def _path_to_driver(self, configuration=None): binary_name = self.driver_name() return self._build_path_with_configuration(configuration, binary_name) def _path_to_helper(self): return None
<?php /* Smarty version 2.6.18, created on 2013-11-05 14:00:11 compiled from 4/uduhzr1383613588/header.html */ ?> <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="telephone=no" name="format-detection" /> <link rel="Shortcut Icon" href="favicon.ico" /> <link rel="Bookmark Icon" href="favicon.ico" /> <link href="logo.png" sizes="114x114" rel="apple-touch-icon"> <meta name="Author" content="024" /> <title><?php echo $this->_tpl_vars['metaTitle']; ?> </title> <meta name="keywords" content="<?php echo $this->_tpl_vars['metaKeywords']; ?> " /> <meta name="description" content="<?php echo $this->_tpl_vars['metaDescription']; ?> "/> <LINK href="templates/gangse/jquery.mobile.structure-1.2.0.min.css?<?php echo $this->_tpl_vars['rand']; ?> " tppabs="/3g/css/jquery.mobile.structure-1.2.0.min.css?<?php echo $this->_tpl_vars['rand']; ?> " rel=stylesheet> <LINK href="<?php echo $this->_tpl_vars['cssdir']; ?> /style.css?<?php echo $this->_tpl_vars['rand']; ?> " rel=stylesheet> <script language="JavaScript" type="text/javascript" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /jquery-1.6.4.min.js" tppabs="/3g/common/js/jquery-1.6.4.min.js"></script> <script language="JavaScript" type="text/javascript" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /nav.js" tppabs="/3g/common/js/nav.js"></script> <script language="JavaScript" type="text/javascript" src="smarty/templates/tpls/<?php echo $this->_tpl_vars['site']['template']; ?> /search.js" tppabs="/3g/common/js/search.js"></script> <script language="JavaScript" type="text/javascript" src="smarty/templates/tpls/tianlan/banner.js" tppabs="common/js/banner.js"></script> </head> <body> <div class="top"> <a href="<?php echo $this->_tpl_vars['homeurl']; ?> " title="主页" class="homebtn"></a> <center><a href="<?php echo $this->_tpl_vars['homeurl']; ?> "><img src="<?php echo $this->_tpl_vars['site']['logourl']; ?> " alt="" style="max-height:40px;" class="logo"></a></center> <a href="javascript:void(0);" title="导航" class="navbtn"></a> <div class="search"> <form method="post" action="?m=site&c=home&a=search&token=<?php echo $this->_tpl_vars['token']; ?> "> <input type="text" class="text" name="SeaStr" id="SeaStr" placeholder="请输入搜索关键词"/> <input type="submit" class="button" value=""> </form> </div> </div> <ul class="nav"> <?php if ($this->_tpl_vars['navChannels']): ?> <?php $_from = $this->_tpl_vars['navChannels']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }if (count($_from)): foreach ($_from as $this->_tpl_vars['n']): ?> <li><a href="<?php echo $this->_tpl_vars['n']['link']; ?> " title="<?php echo $this->_tpl_vars['n']['name']; ?> "><?php echo $this->_tpl_vars['n']['name']; ?> </a></li> <?php endforeach; endif; unset($_from); ?> <?php endif; ?> </ul>
{% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ title }}</title> {% include '_head_css_js.html' %} <link href="{% static "css/jumpserver.css" %}" rel="stylesheet"> <script src="{% static "js/jumpserver.js" %}"></script> </head> <body class="gray-bg"> <div class="passwordBox2 animated fadeInDown"> <div class="row"> <div class="col-md-12"> <div class="ibox-content"> <div> <img src="{% static 'img/logo.png' %}" style="margin: auto" width="82" height="82"> <h2 style="display: inline">Jumpserver</h2> </div> {% if errors %} <p> <div class="alert alert-danger"> {{ errors }} </div> </p> {% endif %} {% if messages %} <p> <div class="alert alert-success" id="messages"> {{ messages|safe }} </div> </p> {% endif %} <div class="row"> <div class="col-lg-3"> <a href="{{ redirect_url }}" class="btn btn-primary block full-width m-b">返回</a> </div> </div> </div> </div> </div> <hr/> <div class="row"> <div class="col-md-6"> Copyright Jumpserver.org </div> <div class="col-md-6 text-right"> <small>2014-2017</small> </div> </div> </div> </body> <script> var time = '{{ interval }}'; if (!time){ time = 5; } else { time = parseInt(time); } function redirect_page() { if (time >= 0) { var messages = '{{ messages|safe }}, <b>' + time +'</b> ...'; $('#messages').html(messages); time--; setTimeout(redirect_page, 1000); } else { window.location.href = "{{ redirect_url }}"; } } {% if auto_redirect %} window.onload = redirect_page; {% endif %} </script> </html>
/* Angular Auto Save Form (c) 2017 Tiberiu Zuld License: MIT */ (function () { 'use strict'; autoSaveForm.$inject = ["$parse", "autoSaveForm", "$log"]; angular.module('angular-auto-save-form', []) .provider('autoSaveForm', autoSaveFormProvider) .directive('autoSaveForm', autoSaveForm) .directive('autoSaveFormProperty', autoSaveFormProperty); /** @ngInject */ function autoSaveFormProvider() { var debounce = 500; var autoSaveMode = true; var spinner = true; var spinnerPosition = 'top right'; return { setDebounce: function (value) { if (angular.isNumber(value)) { debounce = value; } }, setAutoSaveMode: function (value) { if (angular.isDefined(value)) { autoSaveMode = value; } }, setSpinner: function (value) { if (angular.isDefined(value)) { spinner = value; } }, setSpinnerPosition: function (value) { if (angular.isDefined(value)) { spinnerPosition = value; } }, $get: function () { return { debounce: debounce, autoSaveMode: autoSaveMode, spinner: spinner, spinnerPosition: spinnerPosition }; } } } /** @ngInject */ function autoSaveForm($parse, autoSaveForm, $log) { var spinnerTemplate = '<div class="spinner"></div>'; function saveFormLink(scope, element, attributes) { var formModel = scope.$eval(attributes.name); var saveFormAuto = scope.$eval(attributes.autoSaveFormMode); var saveFormDebounce = scope.$eval(attributes.autoSaveFormDebounce); var saveFormSpinner = scope.$eval(attributes.autoSaveFormSpinner); var saveFormSpinnerPosition = scope.$eval(attributes.autoSaveFormSpinnerPosition); var saveFormSpinnerElement; scope.autoSaveFormSubmit = getChangedControls; if (angular.isUndefined(saveFormAuto)) { saveFormAuto = autoSaveForm.autoSaveMode; } if (angular.isUndefined(saveFormSpinner)) { saveFormSpinner = autoSaveForm.spinner; } if (saveFormSpinner) { if (angular.isUndefined(saveFormSpinnerPosition)) { saveFormSpinnerPosition = autoSaveForm.spinnerPosition; } element.append(spinnerTemplate); saveFormSpinnerElement = angular.element(element[0].lastChild); saveFormSpinnerElement.addClass(saveFormSpinnerPosition); } if (saveFormAuto) { if (angular.isUndefined(saveFormDebounce)) { saveFormDebounce = autoSaveForm.debounce; } var debounce = _.debounce(getChangedControls, saveFormDebounce); scope.$watch(function () { return formModel.$dirty && formModel.$valid; }, function (newValue) { if (newValue) { debounce(); formModel.$valid = false; } }); } else { element.on('submit', function (event) { event.preventDefault(); getChangedControls(event); }); } function getChangedControls(event) { if (formModel.$invalid || formModel.$pristine) { return; } var controls = {}; cycleForm(formModel); var invoker = $parse(attributes.autoSaveForm); var promise = invoker(scope, { controls: controls, $event: event }); if (promise && !saveFormAuto) { if (saveFormSpinner) { saveFormSpinnerElement.addClass('spin'); } promise .then(function () { formModel.$setPristine(); }, $log.error) .finally(function () { if (saveFormSpinner) { saveFormSpinnerElement.removeClass('spin'); } }); } else { formModel.$setPristine(); } function cycleForm(formModel) { angular.forEach(formModel.$$controls, checkForm); } function checkForm(value) { if (value.$dirty) { if (value.hasOwnProperty('$submitted')) { //check nestedForm cycleForm(value); } else { var keys = value.$name.split(/\./); if (scope.autoSaveFormProperties && scope.autoSaveFormProperties[keys[0]]) { keys = scope.autoSaveFormProperties[keys[0]].split(/\./); } constructControlsObject(keys, value.$modelValue, controls); } } } function constructControlsObject(keys, value, controls) { var key = keys.shift(); if (keys.length) { if (!controls.hasOwnProperty(key)) { controls[key] = {}; } constructControlsObject(keys, value, controls[key]); } else { controls[key] = value; } } } } return { restrict: 'A', link: saveFormLink }; } /** @ngInject */ function autoSaveFormProperty() { function saveFormLink(scope, element, attributes) { if (attributes.autoSaveFormProperty) { if (angular.isUndefined(scope.autoSaveFormProperties)) { scope.autoSaveFormProperties = {}; } var keys = attributes.autoSaveFormProperty.split(/\./); scope.autoSaveFormProperties[keys.splice(0, 1)] = keys.join('.'); } } return { restrict: 'A', link: saveFormLink }; } })();
#!/usr/bin/env python # # This file is part of moses. Its use is licensed under the GNU Lesser General # Public License version 2.1 or, at your option, any later version. import sys FEAT_FIELD = 2 SCORE_FIELD = 3 def main(): if len(sys.argv[1:]) != 1: sys.stderr.write('Usage: {} moses.ini <nbest.with-new-features >nbest.rescored\n'.format(sys.argv[0])) sys.stderr.write('Entries are _not_ re-sorted based on new score. Use topbest.py\n') sys.exit(2) weights = {} # moses.ini ini = open(sys.argv[1]) while True: line = ini.readline() if not line: sys.stderr.write('Error: no [weight] section\n') sys.exit(1) if line.strip() == '[weight]': break while True: line = ini.readline() if not line or line.strip().startswith('['): break if line.strip() == '': continue fields = line.split() weights[fields[0]] = [float(f) for f in fields[1:]] # N-best for line in sys.stdin: fields = [f.strip() for f in line.split('|||')] feats = fields[FEAT_FIELD].split() key = '' i = 0 score = 0 for f in feats: if f.endswith('='): key = f i = 0 else: score += (float(f) * weights[key][i]) i += 1 fields[SCORE_FIELD] = str(score) sys.stdout.write('{}\n'.format(' ||| '.join(fields))) if __name__ == '__main__': main()
/* * Copyright (C) 2008 Martin Willi * Copyright (C) 2007 Andreas Steffen * Hochschule fuer Technik Rapperswil * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include <curl/curl.h> #include <library.h> #include <debug.h> #include "curl_fetcher.h" #define DEFAULT_TIMEOUT 10 typedef struct private_curl_fetcher_t private_curl_fetcher_t; /** * private data of a curl_fetcher_t object. */ struct private_curl_fetcher_t { /** * Public data */ curl_fetcher_t public; /** * CURL handle */ CURL* curl; /** * Optional HTTP headers */ struct curl_slist *headers; }; /** * writes data into a dynamically resizeable chunk_t */ static size_t append(void *ptr, size_t size, size_t nmemb, chunk_t *data) { size_t realsize = size * nmemb; data->ptr = (u_char*)realloc(data->ptr, data->len + realsize); if (data->ptr) { memcpy(&data->ptr[data->len], ptr, realsize); data->len += realsize; } return realsize; } METHOD(fetcher_t, fetch, status_t, private_curl_fetcher_t *this, char *uri, chunk_t *result) { char error[CURL_ERROR_SIZE]; status_t status; *result = chunk_empty; if (curl_easy_setopt(this->curl, CURLOPT_URL, uri) != CURLE_OK) { /* URL type not supported by curl */ return NOT_SUPPORTED; } curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, error); curl_easy_setopt(this->curl, CURLOPT_FAILONERROR, TRUE); curl_easy_setopt(this->curl, CURLOPT_NOSIGNAL, TRUE); curl_easy_setopt(this->curl, CURLOPT_CONNECTTIMEOUT, DEFAULT_TIMEOUT); curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, (void*)append); curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, (void*)result); if (this->headers) { curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); } DBG2(DBG_LIB, " sending http request to '%s'...", uri); switch (curl_easy_perform(this->curl)) { case CURLE_UNSUPPORTED_PROTOCOL: status = NOT_SUPPORTED; break; case CURLE_OK: status = SUCCESS; break; default: DBG1(DBG_LIB, "libcurl http request failed: %s", error); status = FAILED; break; } return status; } METHOD(fetcher_t, set_option, bool, private_curl_fetcher_t *this, fetcher_option_t option, ...) { va_list args; va_start(args, option); switch (option) { case FETCH_REQUEST_DATA: { chunk_t data = va_arg(args, chunk_t); curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, (char*)data.ptr); curl_easy_setopt(this->curl, CURLOPT_POSTFIELDSIZE, data.len); return TRUE; } case FETCH_REQUEST_TYPE: { char header[BUF_LEN]; char *request_type = va_arg(args, char*); snprintf(header, BUF_LEN, "Content-Type: %s", request_type); this->headers = curl_slist_append(this->headers, header); return TRUE; } case FETCH_REQUEST_HEADER: { char *header = va_arg(args, char*); this->headers = curl_slist_append(this->headers, header); return TRUE; } case FETCH_HTTP_VERSION_1_0: { curl_easy_setopt(this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); return TRUE; } case FETCH_TIMEOUT: { curl_easy_setopt(this->curl, CURLOPT_CONNECTTIMEOUT, va_arg(args, u_int)); return TRUE; } default: return FALSE; } } METHOD(fetcher_t, destroy, void, private_curl_fetcher_t *this) { curl_slist_free_all(this->headers); curl_easy_cleanup(this->curl); free(this); } /* * Described in header. */ curl_fetcher_t *curl_fetcher_create() { private_curl_fetcher_t *this; INIT(this, .public.interface = { .fetch = _fetch, .set_option = _set_option, .destroy = _destroy, }, .curl = curl_easy_init(), ); if (!this->curl) { free(this); return NULL; } return &this->public; }
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name='twitchy-term', version='1.0.1', description='A terminal tool for browsing/streaming on Twitch.tv.', long_description=open('README.rst').read(), url='https://github.com/Andy-Au/twitchy-term', author='Andy Au', author_email='au.andy.ch@gmail.com', license='MIT', keywords='twitch livestreamer command line interface terminal stream', classifiers=[ 'Intended Audience :: End Users/Desktop', 'Environment :: Console :: Curses', 'Operating System :: POSIX', 'Natural Language :: English', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.4', 'Topic :: Multimedia :: Video', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Games/Entertainment', ], packages=find_packages(), install_requires=['livestreamer'], entry_points={ 'console_scripts': [ 'twitchy-term=twitchyterm.__main__:main', ], }, )
#!/usr/bin/python # # Copyright (c) 2016, The OpenThread Authors. # 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. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>" <?php print $rdf_namespaces; ?>> <head profile="<?php print $grddl_profile; ?>"> <?php print $head; ?> <title><?php print $head_title; ?></title> <?php print $styles; ?> <!--- added by zhanglin //--> <? global $base_url; $current_path = drupal_get_path_alias(); // print $current_path ; // 显示当前页面的内部路径 switch($current_path){ case "home": $custom_style_file ='/css/index.css'; break; case "news": $custom_style_file ='/css/information.css'; break; case "jiazuoxuandu": $custom_style_file ='/css/information.css'; break; case "newsdetails": $custom_style_file ='/css/information.css'; break; case "searcher": $custom_style_file ='/css/searcher.css'; break; case "user": $custom_style_file ='/css/myuser.css'; break; } if(stristr($current_path,'newsdetails/')) $custom_style_file ='/css/information.css'; if(stristr($current_path,'page/')||stristr($current_path,'example/')) $custom_style_file ='/css/page.css'; if(stristr($current_path,'jiazuoxuandu/')) $custom_style_file ='/css/information.css'; if(stristr($current_path,'users/')||stristr($current_path,'user/')) $custom_style_file ='/css/myuser.css'; if(stristr($current_path,'paper/')) $custom_style_file ='/css/paper.css'; if(stristr($current_path,'qu')||stristr($current_path,'xuexiao/')) $custom_style_file ='/css/information.css'; if(!empty($custom_style_file)){ $custom_style_uri = ' <style type="text/css" media="all">@import url("'.$base_url.'/'.drupal_get_path('theme','zuowen').$custom_style_file.'");</style>'; // print $base_url.'/'.drupal_get_path('theme','zuowen').$custom_style_file; print $custom_style_uri ; } ?> <!--- added by zhanglin// --> <?php print $scripts; ?> </head> <body class="<?php print $classes; ?>" <?php print $attributes;?>> <div id="skip"> <a href="#main-menu"><?php print t('Jump to Navigation'); ?></a> </div> <?php print $page_top; ?> <?php print $page; ?> <?php print $page_bottom; ?> </body> </html>
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebKitDLL.h" #include "WebGeolocationPosition.h" #include <WebCore/COMPtr.h> #include <WebCore/GeolocationPosition.h> using namespace WebCore; COMPtr<WebGeolocationPosition> WebGeolocationPosition::createInstance() { return new WebGeolocationPosition; } WebGeolocationPosition::WebGeolocationPosition() : m_refCount(0) { gClassCount++; gClassNameCount.add("WebGeolocationPosition"); } WebGeolocationPosition::~WebGeolocationPosition() { gClassCount--; gClassNameCount.remove("WebGeolocationPosition"); } HRESULT WebGeolocationPosition::QueryInterface(REFIID riid, void** ppvObject) { *ppvObject = 0; if (IsEqualIID(riid, __uuidof(WebGeolocationPosition))) *ppvObject = this; else if (IsEqualIID(riid, __uuidof(IUnknown))) *ppvObject = static_cast<IWebGeolocationPosition*>(this); else if (IsEqualIID(riid, __uuidof(IWebGeolocationPosition))) *ppvObject = static_cast<IWebGeolocationPosition*>(this); else return E_NOINTERFACE; AddRef(); return S_OK; } ULONG WebGeolocationPosition::AddRef() { return ++m_refCount; } ULONG WebGeolocationPosition::Release() { ULONG newRef = --m_refCount; if (!newRef) delete this; return newRef; } HRESULT WebGeolocationPosition::initWithTimestamp(double timestamp, double latitude, double longitude, double accuracy) { m_position = GeolocationPosition::create(timestamp, latitude, longitude, accuracy); return S_OK; } GeolocationPosition* core(IWebGeolocationPosition* position) { if (!position) return 0; COMPtr<WebGeolocationPosition> webGeolocationPosition(Query, position); if (!webGeolocationPosition) return 0; return webGeolocationPosition->impl(); }
from datetime import date from unittest import TestCase import numpy as np import pandas as pd from Curves.Corporates.CorporateDaily import CorporateRates from parameters import WORKING_DIR periods = '1Y' freq = '1M' t_step = 1.0 / 365.0 simNumber = 10 start = date(2005, 3, 30) trim_start = date(2000, 1, 1) trim_end = date(2010, 12, 31) referenceDate = date(2005, 3, 30) xR = [2.0, 0.05, 0.01, 0.07] # CashFlow Dates myCorp = CorporateRates() myCorp.getCorporates(trim_start, trim_end) myCorp.pickleMe() scheduleComplete = pd.date_range(start=trim_start,end=trim_end) class TestCorporateRates(TestCase): def test_getOIS(self): OIS = myCorp.getOISData(datelist=scheduleComplete) print('AAA', np.shape(OIS)) def test_getCorporateData1(self): AAA = myCorp.getCorporateData(rating='AAA') print(np.shape(AAA)) def test_getCorporateData2(self): OIS = myCorp.getCorporateData(rating='OIS', datelist=scheduleComplete) print('OIS', np.shape(OIS)) def test_pickleMe(self): return fileName = WORKING_DIR + '/myCorp' myCorp.pickleMe(fileName) def test_unPickleMe(self): fileName = WORKING_DIR + '/myCorp.dat' myCorp.unPickleMe(fileName) def test_saveMeExcel(self): fileName = WORKING_DIR + '/myCorp.xlsx' myCorp.saveMeExcel(whichdata=myCorp.corporates, fileName=fileName)
'use strict'; /** * @ngdoc overview * @name memoryApp * @description * # memoryApp * * Main module of the application. */ angular .module('zombieKong', ["sharedModule"]);
<?php /** * Main loop for displaying ads * * @package ClassiPress * @author AppThemes * */ ?> <?php appthemes_before_loop(); ?> <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <?php appthemes_before_post(); ?> <div class="post-block-out <?php if ( is_sticky() ) echo 'featured'; ?>"> <div class="post-block"> <div class="post-left"> <?php if ( get_option('cp_ad_images') == 'yes' ) cp_ad_loop_thumbnail(); ?> </div> <div class="<?php if ( get_option('cp_ad_images') == 'yes' ) echo 'post-right'; else echo 'post-right-no-img'; ?> <?php echo get_option('cp_ad_right_class'); ?>"> <?php appthemes_before_post_title(); ?> <h3><a href="<?php the_permalink(); ?>"><?php if ( mb_strlen( get_the_title() ) >= 75 ) echo mb_substr( get_the_title(), 0, 75 ).'...'; else the_title(); ?></a></h3> <div class="clr"></div> <?php appthemes_after_post_title(); ?> <div class="clr"></div> <?php appthemes_before_post_content(); ?> <p class="post-desc"><?php echo cp_get_content_preview( 160 ); ?></p> <?php appthemes_after_post_content(); ?> <div class="clr"></div> </div> <div class="clr"></div> </div><!-- /post-block --> </div><!-- /post-block-out --> <?php appthemes_after_post(); ?> <?php endwhile; ?> <?php appthemes_after_endwhile(); ?> <?php else: ?> <?php appthemes_loop_else(); ?> <?php endif; ?> <?php appthemes_after_loop(); ?> <?php wp_reset_query(); ?>
package p; public class Thing { private Thing[] subthings; public Thing() { subthings = new Thing[] {}; } private /*[*//*]*/Thing(Thing... subthings) { this.subthings = subthings; } public static void main(String args[]) { System.out.println(createThing(createThing(new Thing()), createThing(new Thing())).subthings.length); } public static Thing createThing(Thing... subthings) { return new Thing(subthings); } }
# usage: python stats_copy.py <source_server> <target_server> <target_database> <delay> # example store localhosts _stats on localhost:5984/stats every 60 seconds: # $ python stats_copy.py localhost localhost stats 60 import httplib import time from datetime import datetime import threading import sys import simplejson as json class Couch: """Basic wrapper class for operations on a couchDB""" def __init__(self, host, port=5984, options=None): self.host = host self.port = port def connect(self): return httplib.HTTPConnection(self.host, self.port) # No close() def put(self, uri, body): c = self.connect() headers = {"Content-type": "application/json"} c.request("PUT", uri, body, headers) return c.getresponse() def stats(self, range): c = self.connect() c.request("GET","/_stats?range=%s" % range, "",{}) return c.getresponse() source_srv = Couch(sys.argv[1]) target_srv = Couch(sys.argv[2]) target_db = sys.argv[3] # beware couchdb only supports fixed delays of 60, 300 and 900 # anything else will not work delay = int(sys.argv[4]) def stats(delay): stats = json.loads(source_srv.stats(delay).read()) now = datetime.now() # this format can be parsed by javascript's `new Date(str)` jsonDate = now.strftime("%Y/%m/%d %H:%M:%S +0000") stats['timestamp'] = jsonDate path = '/%s/stats-%s' % (target_db, now.strftime("%Y-%m-%d-%H%M%S")) print target_srv.put(path, json.dumps(stats)).read() while True: threading.Thread(target=stats, args=[delay]).start() time.sleep(delay)
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import Event, EventError @register(Event) class EventSerializer(Serializer): def _get_entries(self, event, user, is_public=False): # XXX(dcramer): These are called entries for future-proofing interface_list = [] for key, interface in event.interfaces.iteritems(): # we treat user as a special contextual item if key == 'sentry.interfaces.User': continue entry = { 'data': interface.get_api_context(is_public=is_public), 'type': interface.get_alias(), } interface_list.append((interface, entry)) interface_list.sort(key=lambda x: x[0].get_display_score(), reverse=True) return [i[1] for i in interface_list] def get_attrs(self, item_list, user, is_public=False): Event.objects.bind_nodes(item_list, 'data') results = {} for item in item_list: user_interface = item.interfaces.get('sentry.interfaces.User') if user_interface: user_data = user_interface.to_json() else: user_data = None results[item] = { 'entries': self._get_entries(item, user, is_public=is_public), 'user': user_data, } return results def serialize(self, obj, attrs, user): errors = [] error_set = set() for error in obj.data.get('errors', []): message = EventError.get_message(error) if message in error_set: continue error_set.add(message) error_result = { 'type': error['type'], 'message': message, 'data': { k: v for k, v in error.items() if k != 'type' }, } errors.append(error_result) # TODO(dcramer): move release serialization here d = { 'id': str(obj.id), 'groupID': obj.group.id, 'eventID': str(obj.event_id), 'size': obj.size, 'entries': attrs['entries'], 'message': obj.message, 'user': attrs['user'], 'context': obj.data.get('extra', {}), 'packages': obj.data.get('modules', {}), 'tags': dict(obj.get_tags(with_internal=False)), 'platform': obj.platform, 'dateCreated': obj.datetime, 'timeSpent': obj.time_spent, 'errors': errors, } return d class SharedEventSerializer(EventSerializer): def get_attrs(self, item_list, user): return super(SharedEventSerializer, self).get_attrs( item_list, user, is_public=True ) def serialize(self, obj, attrs, user): result = super(SharedEventSerializer, self).serialize(obj, attrs, user) del result['context'] del result['user'] del result['tags'] return result
from cvlib import * num = 24 #360/15 = 24 -> Higher number == more images, better acc #SYS = "XF:10IDD-BI" #DEV = "OnAxis-Cam:1" #MOTOR = "XF:10IDD-OP{Spec:1-Ax:Th}Mtr" #MaxAngle = 10 #MinAngle = -10 angle = 0 angleAdj = 15 #caget(MOTOR+".RBV") #XF:10IDD-OP{Spec:1-Ax:Th}Mtr.RBV angles = [] toppt = [] # Start roatation here for i in range(num) #and angle < MaxAngle: #change to number of images img = load("sample_00%d.tiff" % angle) #change name to fit img img = np.array(img, np.uint8) #angle = caget(MOTOR+".RBV") #XF:10IDD-OP{Spec:1-Ax:Th}Mtr.RVB angles.append(angle) angle += angleAdj flood = floodFill(img, (600,600), lo=0, hi=0) cnt = findContours(flood) top = extremePoints(cnt[0])["T"] print "PIN TOP %d: " % angle, top toppt.append(top[0]) #plotPoint(img, top, radius = 10) #drawContour(img, cnt[0], thickness=10) #save(img, "result%d.png" % i) #display(img) saveGraph(angles, toppt, "Pin Tip Position", "Angle", "X Coord Top") # Do We need this? d = approxSinCurve(toppt) print d["amplitude"], d["phase shift"], d["vertical shift"] # Extract? saveGraph(angles, d["data"], "X Coord Per Angle", "Angles in Degrees", "X Coord Top", filename="fit.png") makeGraph(angles, d["data"], "X Coord Per Angle", "Angles in Degrees", "X Coord Top", style="r") # Get rid of this # use amplitude and phase to motors
import asyncio from .tsdb_serialization import serialize, LENGTH_FIELD_LENGTH, Deserializer from .tsdb_ops import * from .tsdb_error import * import json class TSDBClient(object): def __init__(self, port=9999): self.port = port def insert_ts(self, primary_key, ts): op = TSDBOp_InsertTS(primary_key, ts) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def delete_ts(self, primary_key): op = TSDBOp_DeleteTS(primary_key) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def upsert_meta(self, primary_key, metadata_dict): op = TSDBOp_UpsertMeta(primary_key, metadata_dict) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def commit(self): op = TSDBOp_Commit() serialized_json = serialize(op.to_json()) return self._send(serialized_json) def rollback(self): op = TSDBOp_Rollback() serialized_json = serialize(op.to_json()) return self._send(serialized_json) def select(self, metadata_dict={}, fields=None, additional=None): op = TSDBOp_Select(metadata_dict, fields, additional) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def augmented_select(self, proc, target, arg=None, metadata_dict={}, additional=None): op = TSDBOp_AugmentedSelect(proc, target, arg, metadata_dict, additional) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def add_trigger(self, proc, onwhat, target, arg=None): op = TSDBOp_AddTrigger(proc, onwhat, target, arg) serialized_json = serialize(op.to_json()) return self._send(serialized_json) def remove_trigger(self, proc, onwhat): op = TSDBOp_RemoveTrigger(proc, onwhat) serialized_json = serialize(op.to_json()) return self._send(serialized_json) # Returns status and payload async def _send_coro(self, msg, loop): reader, writer = await asyncio.open_connection('127.0.0.1', self.port, loop=loop) writer.write(msg) data = await reader.read() d = Deserializer() d.append(data) decoded = d.deserialize() return decoded['status'], decoded['payload'] # call `_send` with a well formed message to send. # once again replace this function if appropriate def _send(self, msg): loop = asyncio.get_event_loop() coro = asyncio.ensure_future(self._send_coro(msg, loop)) loop.run_until_complete(coro) return coro.result()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function import numpy as np ''' This module provide utility function to represent the trajectories with matplotlib ''' def plot_3coords(trajs, coords=('x', 'y', 'z'), text=True, fig=None, **kwargs): ''' Soon to be deprecated, use `plot_stacked_coords` instead ''' return plot_stacked_coords(trajs, coords=coords, text=text, fig=fig, **kwargs) def plot_stacked_coords(trajs, coords=('x', 'y', 'z'), text=False, fig=None, **kwargs): # pragma: no cover ''' Plots stacked graphs with each of the coordinates given in the `coords` argument plotted against time. Parameters ---------- trajs: a :class:`Trajectories` instance coords: a tuple, default ('x', 'y', 'z') the coordinates (`trajs` column names) to be ploted text: bool, default False if True, will append each trajectory segment's label at the extremities on the upper most plot fig: a matplotlib `Figure`, default `None` the figure on which to plot Returns ------- axes: a list of :class:`matplotlib.axes.Axes` ''' import matplotlib.pyplot as plt if fig is None: # Create a figure with 3 graphs verticaly stacked fig, axes = plt.subplots(len(coords), 1, sharex=True, figsize=(6, 9)) else: axes = fig.get_axes() for coord, ax in zip(coords, axes): trajs.show('t', coord, ax=ax, **kwargs) ax.set_ylabel('{} coordinate'.format(coord)) ax.set_title('') ax.set_xlabel('') if text: for label, segment in trajs.iter_segments: axes[0].text(segment.t.iloc[0], segment[coords[0]].iloc[0], str(label)) axes[0].text(segment.t.iloc[-1], segment[coords[0]].iloc[-1], str(label)) axes[-1].set_xlabel('Time') fig.tight_layout() plt.draw() return axes def show_4panels(trajs, label, coords=('x', 'y', 'z'), axes=None, ax_3d=None, scatter_kw={}, line_kw={}, interpolate=False, interp_kw={}): # pragma: no cover '''Plots the segment of trajectories `trajs` with label `label` on four panels organized in two cols by two rows like so:: y| y| |___ |___ x z z| z| y |___ |/__ x x Parameters ---------- trajs: a :class:`Trajectories` instance label: int the label of the trajectories's segment to plot coords: a tuple of column names default to ('x', 'y', 'z'), the coordinates to plot axes: the axes to plot on ax_3d: the 3D ax on the lower right corner scatter_kw: dict keyword arguments passed to the `plt.scatter` function line_kw: dict keyword arguments passed to the `plt.plot` function interpolate: bool if True, will plot the line as an interpolation of the trajectories (not implemented right now) interp_kw: dict keyword arguments for the interpolation Returns ------- axes, ax3d: the 2D and 3D axes ''' import matplotlib.pyplot as plt u, v, w = coords segment = trajs.get_segments()[label] if interpolate: segment_i = trajs.time_interpolate(**interp_kw).get_segments()[label] else: segment_i = segment colors = trajs.get_colors() if 'c' not in scatter_kw and 'color' not in scatter_kw: scatter_kw['c'] = colors[label] if 'c' not in line_kw and 'color' not in line_kw: line_kw['c'] = colors[label] if axes is None: fig = plt.figure(figsize=(6, 6)) ax2 = fig.add_subplot(222, aspect='equal') ax3 = fig.add_subplot(223, aspect='equal') ax1 = fig.add_subplot(221, sharey=ax2, sharex=ax3) ax_3d = fig.add_subplot(224, projection='3d') axes = np.array([[ax1, ax2], [ax3, ax_3d]]) ax_3d.set_aspect('equal') for ax in axes.ravel(): ax.set_aspect('equal') ax.grid() axes[0, 0].scatter(segment[u].values, segment[v].values, **scatter_kw) axes[0, 1].scatter(segment[w].values, segment[v].values, **scatter_kw) axes[1, 0].scatter(segment[u].values, segment[w].values, **scatter_kw) if ax_3d is not None: ax_3d.scatter(segment[u].values, segment[v].values, segment[w].values, **scatter_kw) axes[0, 0].plot(segment_i[u].values, segment_i[v].values, **line_kw) axes[0, 1].plot(segment_i[w].values, segment_i[v].values, **line_kw) axes[1, 0].plot(segment_i[u].values, segment_i[w].values, **line_kw) if ax_3d is not None: ax_3d.plot(segment_i[u].values, segment_i[v].values, zs=segment_i[w].values, **line_kw) axes[0, 0].set_ylabel(u'y position (µm)') axes[1, 0].set_xlabel(u'x position (µm)') axes[1, 0].set_ylabel(u'z position (µm)') axes[0, 0].set_ylabel(u'y position (µm)') axes[0, 1].set_xlabel(u'z position (µm)') if ax_3d is not None: ax_3d.set_xlabel(u'x position (µm)') ax_3d.set_ylabel(u'y position (µm)') ax_3d.set_zlabel(u'z position (µm)') return axes, ax_3d
/* * Copyright (c) 2014 ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Universitaetsstrasse 6, CH-8092 Zurich. Attn: Systems Group. */ #include <barrelfish/barrelfish.h> #include <virtio/virtio_guest.h> #include "guest/channel.h" struct virtio_guest_chan_fn *vguest_chan_fn = NULL; /** * */ errval_t virtio_guest_init(enum virtio_guest_channel backend, char *iface) { errval_t err; switch (backend) { case VIRTIO_GUEST_CHAN_FLOUNDER: err = virtio_guest_flounder_init(iface); break; case VIRTIO_GUEST_CHAN_XEON_PHI: err = virtio_guest_xeon_phi_init(); break; default: err = -1; break; } if (err_is_fail(err)) { return err; } assert(vguest_chan_fn); return SYS_ERR_OK; }
## # Copyright 2012-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ Support for dummy compiler. @author: Stijn De Weirdt (Ghent University) @author: Kenneth Hoste (Ghent University) """ import easybuild.tools.systemtools as systemtools from easybuild.tools.toolchain.compiler import Compiler TC_CONSTANT_DUMMY = "DUMMY" class DummyCompiler(Compiler): """Dummy compiler : try not to even use system gcc""" COMPILER_MODULE_NAME = [] COMPILER_FAMILY = TC_CONSTANT_DUMMY COMPILER_CC = '%sCC' % TC_CONSTANT_DUMMY COMPILER_CXX = '%sCXX' % TC_CONSTANT_DUMMY COMPILER_F77 = '%sF77' % TC_CONSTANT_DUMMY COMPILER_F90 = '%sF90' % TC_CONSTANT_DUMMY COMPILER_FC = '%sFC' % TC_CONSTANT_DUMMY
from __future__ import print_function, absolute_import, division, unicode_literals # This file is part of the ISIS IBEX application. # Copyright (C) 2012-2016 Science & Technology Facilities Council. # All rights reserved. # # This program is distributed in the hope that it will be useful. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License v1.0 which accompanies this distribution. # EXCEPT AS EXPRESSLY SET FORTH IN THE ECLIPSE PUBLIC LICENSE V1.0, THE PROGRAM # AND ACCOMPANYING MATERIALS ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND. See the Eclipse Public License v1.0 for more details. # # You should have received a copy of the Eclipse Public License v1.0 # along with this program; if not, you can obtain a copy from # https://www.eclipse.org/org/documents/epl-v10.php or # http://opensource.org/licenses/eclipse-1.0.php import six class IocOptions(object): """Contains the possible macros and pvsets of an IOC.""" def __init__(self, name: str): """Constructor Args: name: The name of the IOC the options are associated with """ self.name = name # The possible macros, pvsets and pvs for an IOC, along with associated parameters such as description self.macros = dict() self.pvsets = dict() self.pvs = dict() def _dict_to_list(self, in_dict: dict) -> list: # Convert into format for better GUI parsing (I know it's messy but it's what the GUI wants) out_list = [] for k, v in in_dict.items(): v['name'] = k out_list.append(v) return out_list def to_dict(self) -> dict: """Get a dictionary of the possible macros and pvsets for an IOC Returns: dict : Possible macros and pvsets """ return {'macros': self._dict_to_list(self.macros), 'pvsets': self._dict_to_list(self.pvsets), 'pvs': self._dict_to_list(self.pvs)}
from glue.core import Subset from glue.external.echo import (CallbackProperty, SelectionCallbackProperty, delay_callback) from glue.core.state_objects import StateAttributeLimitsHelper from glue.core.data_combo_helper import ComponentIDComboHelper from ..common.layer_state import VispyLayerState __all__ = ['VolumeLayerState'] class VolumeLayerState(VispyLayerState): """ A state object for volume layers """ attribute = SelectionCallbackProperty() vmin = CallbackProperty() vmax = CallbackProperty() subset_mode = CallbackProperty('data') limits_cache = CallbackProperty({}) def __init__(self, layer=None, **kwargs): super(VolumeLayerState, self).__init__(layer=layer) if self.layer is not None: self.color = self.layer.style.color self.alpha = self.layer.style.alpha self.att_helper = ComponentIDComboHelper(self, 'attribute') self.lim_helper = StateAttributeLimitsHelper(self, attribute='attribute', lower='vmin', upper='vmax', cache=self.limits_cache) self.add_callback('layer', self._on_layer_change) if layer is not None: self._on_layer_change() if isinstance(self.layer, Subset): self.vmin = 0 self.vmax = 1 self.update_from_dict(kwargs) def _on_layer_change(self, layer=None): with delay_callback(self, 'vmin', 'vmin'): if self.layer is None: self.att_helper.set_multiple_data([]) else: self.att_helper.set_multiple_data([self.layer]) def update_priority(self, name): return 0 if name.endswith(('vmin', 'vmax')) else 1
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .proxy_resource import ProxyResource class DatabaseOperation(ProxyResource): """A database operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar database_name: The name of the database the operation is being performed on. :vartype database_name: str :ivar operation: The name of operation. :vartype operation: str :ivar operation_friendly_name: The friendly name of operation. :vartype operation_friendly_name: str :ivar percent_complete: The percentage of the operation completed. :vartype percent_complete: int :ivar server_name: The name of the server. :vartype server_name: str :ivar start_time: The operation start time. :vartype start_time: datetime :ivar state: The operation state. Possible values include: 'Pending', 'InProgress', 'Succeeded', 'Failed', 'CancelInProgress', 'Cancelled' :vartype state: str or ~azure.mgmt.sql.models.ManagementOperationState :ivar error_code: The operation error code. :vartype error_code: int :ivar error_description: The operation error description. :vartype error_description: str :ivar error_severity: The operation error severity. :vartype error_severity: int :ivar is_user_error: Whether or not the error is a user error. :vartype is_user_error: bool """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'database_name': {'readonly': True}, 'operation': {'readonly': True}, 'operation_friendly_name': {'readonly': True}, 'percent_complete': {'readonly': True}, 'server_name': {'readonly': True}, 'start_time': {'readonly': True}, 'state': {'readonly': True}, 'error_code': {'readonly': True}, 'error_description': {'readonly': True}, 'error_severity': {'readonly': True}, 'is_user_error': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'database_name': {'key': 'properties.databaseName', 'type': 'str'}, 'operation': {'key': 'properties.operation', 'type': 'str'}, 'operation_friendly_name': {'key': 'properties.operationFriendlyName', 'type': 'str'}, 'percent_complete': {'key': 'properties.percentComplete', 'type': 'int'}, 'server_name': {'key': 'properties.serverName', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'state': {'key': 'properties.state', 'type': 'str'}, 'error_code': {'key': 'properties.errorCode', 'type': 'int'}, 'error_description': {'key': 'properties.errorDescription', 'type': 'str'}, 'error_severity': {'key': 'properties.errorSeverity', 'type': 'int'}, 'is_user_error': {'key': 'properties.isUserError', 'type': 'bool'}, } def __init__(self): super(DatabaseOperation, self).__init__() self.database_name = None self.operation = None self.operation_friendly_name = None self.percent_complete = None self.server_name = None self.start_time = None self.state = None self.error_code = None self.error_description = None self.error_severity = None self.is_user_error = None
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-keypairs' POLICY_ROOT = 'os_compute_api:os-keypairs:%s' keypairs_policies = [ policy.DocumentedRuleDefault( POLICY_ROOT % 'index', 'rule:admin_api or user_id:%(user_id)s', "List all keypairs", [ { 'path': '/os-keypairs', 'method': 'GET' } ]), policy.DocumentedRuleDefault( POLICY_ROOT % 'create', 'rule:admin_api or user_id:%(user_id)s', "Create a keypair", [ { 'path': '/os-keypairs', 'method': 'POST' } ]), policy.DocumentedRuleDefault( POLICY_ROOT % 'delete', 'rule:admin_api or user_id:%(user_id)s', "Delete a keypair", [ { 'path': '/os-keypairs/{keypair_name}', 'method': 'DELETE' } ]), policy.DocumentedRuleDefault( POLICY_ROOT % 'show', 'rule:admin_api or user_id:%(user_id)s', "Show details of a keypair", [ { 'path': '/os-keypairs/{keypair_name}', 'method': 'GET' } ]), policy.DocumentedRuleDefault( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, "Return 'key_name' in the response of server.", [ { 'path': '/servers/{id}', 'method': 'GET', }, { 'path': '/servers/detail', 'method': 'GET' } ]), ] def list_rules(): return keypairs_policies
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.profiler.context.storage; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.profiler.context.SpanChunkFactoryV1; import com.navercorp.pinpoint.profiler.context.Span; import com.navercorp.pinpoint.profiler.context.SpanChunkFactory; import com.navercorp.pinpoint.profiler.context.SpanEvent; import com.navercorp.pinpoint.profiler.context.SpanPostProcessor; import com.navercorp.pinpoint.profiler.context.SpanPostProcessorV1; import com.navercorp.pinpoint.profiler.sender.CountingDataSender; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class BufferedStorageTest { private final SpanPostProcessor spanPostProcessor = new SpanPostProcessorV1(); private final SpanChunkFactory spanChunkFactory = new SpanChunkFactoryV1("applicationName", "agentId", 0, ServiceType.STAND_ALONE); private final CountingDataSender countingDataSender = new CountingDataSender(); @Before public void before() { countingDataSender.stop(); } @Test public void testStore_Noflush() throws Exception { BufferedStorage bufferedStorage = new BufferedStorage(countingDataSender, spanPostProcessor, spanChunkFactory, 10); Span span = new Span(); SpanEvent spanEvent = new SpanEvent(span); bufferedStorage.store(spanEvent); bufferedStorage.store(spanEvent); Assert.assertEquals(0, countingDataSender.getTotalCount()); } @Test public void testStore_flush() throws Exception { BufferedStorage bufferedStorage = new BufferedStorage(countingDataSender, spanPostProcessor, spanChunkFactory, 1); Span span = new Span(); SpanEvent spanEvent = new SpanEvent(span); bufferedStorage.store(spanEvent); bufferedStorage.store(spanEvent); Assert.assertEquals(2, countingDataSender.getSenderCounter()); Assert.assertEquals(2, countingDataSender.getTotalCount()); Assert.assertEquals(2, countingDataSender.getSpanChunkCounter()); Assert.assertEquals(0, countingDataSender.getSpanCounter()); } @Test public void testStore_spanFlush() throws Exception { BufferedStorage bufferedStorage = new BufferedStorage(countingDataSender, spanPostProcessor, spanChunkFactory, 10); Span span = new Span(); bufferedStorage.store(span); bufferedStorage.store(span); bufferedStorage.store(span); Assert.assertEquals(3, countingDataSender.getSenderCounter()); Assert.assertEquals(3, countingDataSender.getTotalCount()); Assert.assertEquals(3, countingDataSender.getSpanCounter()); Assert.assertEquals(0, countingDataSender.getSpanChunkCounter()); } @Test public void testStore_spanLastFlush() throws Exception { BufferedStorage bufferedStorage = new BufferedStorage(countingDataSender, spanPostProcessor, spanChunkFactory, 10); Span span = new Span(); SpanEvent spanEvent = new SpanEvent(span); bufferedStorage.store(spanEvent); bufferedStorage.store(spanEvent); bufferedStorage.store(span); Assert.assertEquals(1, countingDataSender.getSenderCounter()); Assert.assertEquals(1, countingDataSender.getTotalCount()); Assert.assertEquals(1, countingDataSender.getSpanCounter()); Assert.assertEquals(0, countingDataSender.getSpanChunkCounter()); } @Test public void testStore_manual_flush() throws Exception { BufferedStorage bufferedStorage = new BufferedStorage(countingDataSender, spanPostProcessor, spanChunkFactory, 10); Span span = new Span(); SpanEvent spanEvent = new SpanEvent(span); bufferedStorage.store(spanEvent); bufferedStorage.store(spanEvent); bufferedStorage.flush(); Assert.assertEquals(1, countingDataSender.getSenderCounter()); Assert.assertEquals(1, countingDataSender.getTotalCount()); Assert.assertEquals(0, countingDataSender.getSpanCounter()); Assert.assertEquals(1, countingDataSender.getSpanChunkCounter()); } }
# Copyright (C) 2008 Dirk Vanden Boer <dirk.vdb@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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import os import gobject import transferinfo import phonebrowser from filecollection import File from filecollection import Directory class TransferManager(gobject.GObject): __gsignals__ = { "transferscompleted": ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []), "progress": ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_INT]), "filetransferstarted": ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]) } def __init__(self, phoneBrowser): gobject.GObject.__init__(self) self.__phoneBrowser = phoneBrowser self.__phoneBrowser.connect('progress', self.__transferProgressCb) self.__phoneBrowser.connect('completed', self.__transferCompletedCb) self.__copyFromPhoneToLocal = True self.__localDirectory = None self.__transferQueue = [] self.__currentTransferDir = None self.__currentPath = None def __del__(self): self.__phoneBrowser.disconnect('progress') self.__phoneBrowser.disconnect('completed') def buildDirectoryStructure(self, directoryName = '.', parent = None): directory = Directory() directory.parent = parent directory.name = directoryName if directoryName != '.': self.__phoneBrowser.changeDirectory(directoryName) dirs, files = self.__phoneBrowser.getDirectoryListing() for file in files: directory.addFile(file) for dir in dirs: directory.addDirectory(self.buildFileCollectionFromDir(dir, directory)) if directoryName != '.': self.__phoneBrowser.directoryUp() return directory def copyToLocal(self, remoteDirectory, localDirectory): self.__copyFromPhoneToLocal = True self.__localDirectory = localDirectory self.__transferQueue = remoteDirectory self.__currentTransferDir = remoteDirectory self.__currentTransferPath = localDirectory self.__transferNextFileInQueue() def copyToRemote(self, localDirectory): self.__copyFromPhoneToLocal = False self.__transferQueue = localDirectory self.__currentTransferDir = localDirectory self.__transferNextFileInQueue() def __transferNextFileInQueue(self): if (len(self.__currentTransferDir.directories) > 0): self.__currentTransferDir = self.__currentTransferDir.directories[0] self.__phoneBrowser.changeDirectory(self.__currentTransferDir.name) self.__currentTransferPath = os.path.join(self.__currentTransferPath, self.__currentTransferDir.name) if not os.path.exists(self.__currentTransferPath): os.mkdir(self.__currentTransferPath) self.__transferNextFileInQueue() else: if (len(self.__currentTransferDir.files) > 0): fileInfo = self.__currentTransferDir.files.pop(0) self.emit("filetransferstarted", fileInfo) if self.__copyFromPhoneToLocal == True: self.__phoneBrowser.copyToLocal(fileInfo.name, self.__currentTransferPath) else: self.__phoneBrowser.copyToRemote(fileInfo.name) else: self.__currentTransferDir = self.__currentTransferDir.parent if self.__currentTransferDir != None: self.__currentTransferDir.directories.pop(0) self.__phoneBrowser.directoryUp() self.__currentTransferPath = os.path.normpath(os.path.join(self.__currentTransferPath, '..')) self.__transferNextFileInQueue() else: self.emit('transferscompleted') def __transferProgressCb(self, sender, bytesTransferred): self.emit('progress', bytesTransferred) def __transferCompletedCb(self, sender = None): self.__transferNextFileInQueue()
#include "StdAfx.h" #include "AppConfigMgr.h" #include "Global.h" /////////////////////////////////////////////////////////////////////////////// #define SECTION_GENERAL TEXT("Config") /////////////////////////////////////////////////////////////////////////////// CAppConfigMgr::CAppConfigMgr() { } CAppConfigMgr::~CAppConfigMgr() { } CString CAppConfigMgr::GetIniFileName() { return GetAppPath() + CONFIG_FILE_NAME; } void CAppConfigMgr::LoadRecentSrcPaths() { CString str = GetString(SECTION_GENERAL, TEXT("RecentSrcPaths")); m_RecentSrcPaths.SetCommaText(str); } void CAppConfigMgr::SaveRecentSrcPaths() { CString str = m_RecentSrcPaths.GetCommaText(); SetString(SECTION_GENERAL, TEXT("RecentSrcPaths"), str); } void CAppConfigMgr::Load() { LoadFromIniFile(GetIniFileName()); LoadRecentSrcPaths(); } void CAppConfigMgr::Save() { SaveRecentSrcPaths(); SaveToIniFile(GetIniFileName()); } void CAppConfigMgr::GetRecentSrcPaths(CStrList& List) { List = m_RecentSrcPaths; } void CAppConfigMgr::SetRecentSrcPaths(const CStrList& List) { CStrList TempList; // È¥³ýÖØ¸´ for (int i = 0; i < List.GetCount() && i < MAX_RECENT_SRC_DIRS; i++) { CString str = List[i]; if (!TempList.Exists(str)) TempList.Add(str); } m_RecentSrcPaths = TempList; } /////////////////////////////////////////////////////////////////////////////// CAppConfigMgr ConfigMgr; ///////////////////////////////////////////////////////////////////////////////
import { Composable, propsCallback } from "./blueprint"; import pick from "./utils/pick"; export function getContext<T>( contextTypes: T, ): Composable { return { staticCallback: (componentClass) => { componentClass.contextTypes = { ...componentClass.contextTypes, ...(contextTypes as any), }; }, instanceCallbacks: [ propsCallback((props, _, context) => ({ ...props, ...pick(context, ...Object.keys(contextTypes)), })), ], }; } export default getContext;
#ifndef QEMU_HID_H #define QEMU_HID_H #include "migration/vmstate.h" #include "ui/input.h" #define HID_MOUSE 1 #define HID_TABLET 2 #define HID_KEYBOARD 3 typedef struct HIDPointerEvent { int32_t xdx, ydy; /* relative iff it's a mouse, otherwise absolute */ int32_t dz, buttons_state; } HIDPointerEvent; #define QUEUE_LENGTH 16 /* should be enough for a triple-click */ #define QUEUE_MASK (QUEUE_LENGTH-1u) #define QUEUE_INCR(v) ((v)++, (v) &= QUEUE_MASK) typedef struct HIDState HIDState; typedef void (*HIDEventFunc)(HIDState *s); typedef struct HIDMouseState { HIDPointerEvent queue[QUEUE_LENGTH]; int mouse_grabbed; } HIDMouseState; typedef struct HIDKeyboardState { uint32_t keycodes[QUEUE_LENGTH]; uint16_t modifiers; uint8_t leds; uint8_t key[16]; int32_t keys; } HIDKeyboardState; struct HIDState { union { HIDMouseState ptr; HIDKeyboardState kbd; }; uint32_t head; /* index into circular queue */ uint32_t n; int kind; int32_t protocol; uint8_t idle; bool idle_pending; QEMUTimer *idle_timer; HIDEventFunc event; QemuInputHandlerState *s; }; void hid_init(HIDState *hs, int kind, HIDEventFunc event); void hid_reset(HIDState *hs); void hid_free(HIDState *hs); bool hid_has_events(HIDState *hs); void hid_set_next_idle(HIDState *hs); void hid_pointer_activate(HIDState *hs); int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len); int hid_keyboard_poll(HIDState *hs, uint8_t *buf, int len); int hid_keyboard_write(HIDState *hs, uint8_t *buf, int len); extern const VMStateDescription vmstate_hid_keyboard_device; #define VMSTATE_HID_KEYBOARD_DEVICE(_field, _state) { \ .name = (stringify(_field)), \ .size = sizeof(HIDState), \ .vmsd = &vmstate_hid_keyboard_device, \ .flags = VMS_STRUCT, \ .offset = vmstate_offset_value(_state, _field, HIDState), \ } extern const VMStateDescription vmstate_hid_ptr_device; #define VMSTATE_HID_POINTER_DEVICE(_field, _state) { \ .name = (stringify(_field)), \ .size = sizeof(HIDState), \ .vmsd = &vmstate_hid_ptr_device, \ .flags = VMS_STRUCT, \ .offset = vmstate_offset_value(_state, _field, HIDState), \ } #endif /* QEMU_HID_H */
extern "C" void abort (void); void single (int a, int b) { #pragma omp single copyprivate(a) copyprivate(b) { a = b = 5; } if (a != b) abort (); } int main() { #pragma omp parallel single (1, 2); return 0; }
/* * ORXONOX - the hottest 3D action shooter ever to exist * > www.orxonox.net < * * * License notice: * * 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. * * Author: * Fabian 'x3n' Landau * Co-authors: * ... * */ #include "WaypointPatrolController.h" #include "util/Math.h" #include "core/CoreIncludes.h" #include "core/XMLPort.h" #include "worldentities/pawns/Pawn.h" namespace orxonox { RegisterClass(WaypointPatrolController); WaypointPatrolController::WaypointPatrolController(Context* context) : WaypointController(context) { RegisterObject(WaypointPatrolController); this->alertnessradius_ = 500.0f; this->attackradius_ = 1000.0f; this->patrolTimer_.setTimer(rnd(), true, createExecutor(createFunctor(&WaypointPatrolController::searchEnemy, this))); } void WaypointPatrolController::XMLPort(Element& xmlelement, XMLPort::Mode mode) { SUPER(WaypointPatrolController, XMLPort, xmlelement, mode); XMLPortParam(WaypointPatrolController, "alertnessradius", setAlertnessRadius, getAlertnessRadius, xmlelement, mode).defaultValues(500.0f); XMLPortParam(WaypointPatrolController, "attackradius", setAttackRadius, getAttackRadius, xmlelement, mode).defaultValues(1000.0f); } void WaypointPatrolController::tick(float dt) { if (!this->isActive()) return; if (this->target_) //if there is a target, follow it and shoot it, if it is close enough { this->aimAtTarget(); if (this->bHasTargetPosition_) this->moveToTargetPosition(); if (this->getControllableEntity() && this->isCloseAtTarget(this->attackradius_) && this->isLookingAtTarget(math::pi / 20.0f)) this->getControllableEntity()->fire(0); } else { SUPER(WaypointPatrolController, tick, dt); } } void WaypointPatrolController::searchEnemy() { this->patrolTimer_.setInterval(rnd()); if (!this->getControllableEntity()) return; Vector3 myposition = this->getControllableEntity()->getPosition(); float shortestsqdistance = (float)static_cast<unsigned int>(-1); for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); ++it) { if (ArtificialController::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it), this->getGametype())) continue; float sqdistance = it->getPosition().squaredDistance(myposition); if (sqdistance < shortestsqdistance) { shortestsqdistance = sqdistance; this->target_ = (*it); } } if (shortestsqdistance > (this->alertnessradius_ * this->alertnessradius_)) this->target_ = 0; } }
import unittest import arff try: from StringIO import StringIO except ImportError: from io import StringIO OBJ = { 'description': 'teste', 'relation': 'teste', 'attributes': [ ('a', 'STRING'), ('b', ('a', 'b', 'c', 'd')), ('c', 'STRING'), ('d', ('"a"', '"b"', '"c"', '"d"')), ], 'data': [ ['lorem', 'b', 'thisisavalidstatement', '"b"'], ['lorem', 'b', 'this is a valid statement with an % symbol', '"b"'], ['lorem2', 'd', 'this is a valid statement', '"d"'], ['lorem3', 'c', 'this is a valid statement with double quotes included """""""! ', '"c"'], ['lorem4', 'a', 'this is a valid \\ statement with singlequotes included \' lol \'! ', '"a"'] ] } ARFF = '''% teste @RELATION teste @ATTRIBUTE a STRING @ATTRIBUTE b {a, b, c, d} @ATTRIBUTE c STRING @ATTRIBUTE d {\'\\"a\\"\', \'\\"b\\"\', \'\\"c\\"\', \'\\"d\\"\'} @DATA lorem,b,thisisavalidstatement,\'\\"b\\"\' lorem,b,'this is a valid statement with an \\% symbol',\'\\"b\\"\' lorem2,d,'this is a valid statement',\'\\"d\\"\' lorem3,c,'this is a valid statement with double quotes included \\"\\"\\"\\"\\"\\"\\"! ',\'\\"c\\"\' lorem4,a,'this is a valid \\\\ statement with singlequotes included \\\' lol \\\'! ',\'\\"a\\"\' ''' class TestDumps(unittest.TestCase): def get_dumps(self): dumps = arff.dumps return dumps def test_simple(self): dumps = self.get_dumps() s = dumps(OBJ) self.assertEqual(s, ARFF) count = 0 while count < 10: count += 1 obj = arff.loads(s) src = arff.dumps(obj) self.assertEqual(src, ARFF)
namespace _64BitArray { using System; using System.Text; public class SixtyFourBitArrayMain { public static void Main() { BitArray64 bits = new BitArray64(123456789999); Console.WriteLine(string.Join("", bits)); Console.WriteLine("Hash code: {0}", bits.GetHashCode()); BitArray64 anotherBits = new BitArray64(123456789999); Console.WriteLine(string.Join("", anotherBits)); Console.WriteLine("Hash code: {0}", anotherBits.GetHashCode()); Console.WriteLine("Equals: {0}", bits.Equals(anotherBits)); Console.WriteLine(" == {0}", bits == anotherBits); Console.WriteLine(" != {0}", bits != anotherBits); Console.WriteLine("Foreach:"); foreach (var bit in bits) { Console.Write(bit); } Console.WriteLine(); Console.WriteLine("For:"); for (int i = 0; i < bits.Bits.Length; i++) { Console.Write(bits.Bits[i]); } Console.WriteLine(); } } }
/* * bim.{cc,hh} -- element reads and writes packets to/from * ABACOM BIM-4xx-RS232 radios * Robert Morris * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include "bim.hh" #include <click/error.hh> #include <click/packet.hh> #include <click/confparse.hh> #include <click/glue.hh> #include "bim-proto.hh" #include <click/standard/scheduleinfo.hh> #include <unistd.h> #include <termios.h> #include <fcntl.h> #include <sys/ioctl.h> CLICK_DECLS BIM::BIM() : _task(this) { _speed = 9600; _fd = -1; _len = _started = _escaped = 0; } BIM::~BIM() { if(_fd >= 0) close(_fd); } int BIM::configure(Vector<String> &conf, ErrorHandler *errh) { if (cp_va_kparse(conf, this, errh, "DEVNAME", cpkP+cpkM, cpString, &_dev, "BAUD", cpkP, cpInteger, &_speed, cpEnd) < 0) return -1; if(_speed == 4800) _speed = B4800; else if(_speed == 9600) _speed = B9600; else if(_speed == 19200) _speed = B19200; else if(_speed == 38400) _speed = B38400; else { return errh->error("bad speed %d", _speed); } return 0; } int BIM::initialize(ErrorHandler *errh) { if (_fd >= 0) return 0; else if (!_dev) return errh->error("device name not set"); char *dname = _dev.mutable_c_str(); _fd = open(dname, O_RDWR|O_NONBLOCK, 0); if(_fd < 0) return errh->error("%s: %s", dname, strerror(errno)); ioctl(_fd, TIOCEXCL, 0); struct termios t; if(tcgetattr(_fd, &t) < 0) return errh->error("bad tcgetattr"); t.c_iflag = IGNBRK; t.c_oflag = 0; t.c_cflag = CS8|CREAD|HUPCL|CLOCAL; t.c_lflag = 0; cfsetispeed(&t, _speed); cfsetospeed(&t, _speed); if(tcsetattr(_fd, TCSANOW, &t) < 0) return errh->error("can't set terminal characteristics"); #ifdef FIONBIO int yes = 1; if(ioctl(_fd, FIONBIO, &yes) < 0) return errh->error("can't set non-blocking IO"); #else return errh->error("not configured for non-blocking IO"); #endif #ifdef TCIOFLUSH tcflush(_fd, TCIOFLUSH); #elif defined(TIOCFLUSH) tcflush(_fd, TIOCFLUSH); #else return errh->error("this architecture has no TIOCFLUSH"); #endif ScheduleInfo::join_scheduler(this, &_task, errh); add_select(_fd, SELECT_READ | SELECT_WRITE); return 0; } void BIM::selected(int fd) { int cc, i; char b[128]; if (fd != _fd) return; cc = read(_fd, b, sizeof(b)); for(i = 0; i < cc; i++) got_char(b[i] & 0xff); } void BIM::got_char(int c) { if(_started == 0 && _escaped == 0 && c == BIM_ESC){ _escaped = 1; } else if(_escaped && c == BIM_ESC_START){ _escaped = 0; _started = 1; _len = 0; } else if(_started && !_escaped && c == BIM_ESC){ _escaped = 1; } else if(_started && _escaped && c == BIM_ESC_END){ Packet *p = Packet::make(_buf, _len); output(0).push(p); _escaped = _started = _len = 0; } else if(_started && _escaped && c == BIM_ESC_ESC){ _buf[_len++] = BIM_ESC; _escaped = 0; } else if(_started && !_escaped && c != BIM_ESC){ _buf[_len++] = c; } else if(_started || _escaped){ fprintf(stderr, "bim: framing error, st %d es %d _len %d c %02x\n", _started, _escaped, _len, c); _started = _escaped = _len = 0; } if(_len > 1024){ fprintf(stderr, "bim: incoming packet too large\n"); _len = _started = 0; } } bool BIM::run_task(Task *) { Packet *p = input(0).pull(); if (p) push(0, p); _task.fast_reschedule(); return p != 0; } void BIM::push(int, Packet *p) { send_packet(p->data(), p->length()); p->kill(); } void BIM::send_packet(const unsigned char buf[], unsigned int len) { unsigned int i, j; char big[2048]; if(len > 1024){ fprintf(stderr, "bim: packet too large\n"); return; } j = 0; for(i = 0; i < 13; i++){ big[j++] = 'U'; /* preamble 01010101 */ } big[j++] = 0xff; /* sync */ big[j++] = BIM_ESC; big[j++] = BIM_ESC_START; for(i = 0; i < len; i++){ int c = buf[i] & 0xff; if(c == BIM_ESC){ big[j++] = BIM_ESC; big[j++] = BIM_ESC_ESC; } else { big[j++] = c; } } big[j++] = BIM_ESC; big[j++] = BIM_ESC_END; if(write(_fd, big, j) != (int) j){ perror("bim: write rs232"); } #if 0 { FILE *fp = fopen("foo", "a"); if(fp){ double a = 0.5; int by, bi; for(by = 0; by < j; by++){ for(bi = 0; bi < 8; bi++){ int bit = (big[by] >> bi) & 1; a = (a * 0.9) + (bit * 0.1); fprintf(fp, "%.5f\n", a); } } fprintf(fp, "\n"); fclose(fp); } } #endif } CLICK_ENDDECLS EXPORT_ELEMENT(BIM) ELEMENT_REQUIRES(userlevel)
import os import robot from keywordgroup import KeywordGroup class _ScreenshotKeywords(KeywordGroup): def __init__(self): self._screenshot_index = 0 # Public def capture_page_screenshot(self, filename=None): """Takes a screenshot of the current page and embeds it into the log. `filename` argument specifies the name of the file to write the screenshot into. If no `filename` is given, the screenshot is saved into file `selenium-screenshot-<counter>.png` under the directory where the Robot Framework log file is written into. The `filename` is also considered relative to the same directory, if it is not given in absolute format. `css` can be used to modify how the screenshot is taken. By default the bakground color is changed to avoid possible problems with background leaking when the page layout is somehow broken. """ path, link = self._get_screenshot_paths(filename) self._current_browser().save_screenshot(path) # Image is shown on its own row and thus prev row is closed on purpose self._html('</td></tr><tr><td colspan="3"><a href="%s">' '<img src="%s" width="800px"></a>' % (link, link)) # Private def _get_screenshot_paths(self, filename): if not filename: self._screenshot_index += 1 filename = 'selenium-screenshot-%d.png' % self._screenshot_index else: filename = filename.replace('/', os.sep) logdir = self._get_log_dir() path = os.path.join(logdir, filename) link = robot.utils.get_link_path(path, logdir) return path, link
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from ujson import loads from tornado import gen from tornado.httpclient import HTTPError from holmes.models import User from holmes.handlers import BaseHandler class AuthenticateHandler(BaseHandler): def get(self): ''' Only returns true or false if is a valid authenticated request ''' self.set_status(200) user = self.get_authenticated_user() if user: self.write_json({ 'authenticated': True, 'isSuperUser': user.is_superuser }) else: self.write_json({ 'authenticated': False, 'isSuperUser': False }) @gen.coroutine def post(self): ''' Try to authenticate user with the provider and access_token POST data. If the `self.authenticate` method returns the user, create a JSON Web Token (JWT) and set a `HOLMES_AUTH_TOKEN` cookie with the encoded value. Otherwise returns a unauthorized request. ''' post_data = loads(self.request.body) provider = post_data.get('provider') access_token = post_data.get('access_token') user = yield self.authenticate(provider, access_token) if user: payload = dict( sub=user.email, iss=user.provider, token=access_token, iat=datetime.utcnow(), exp=datetime.utcnow() + timedelta( seconds=self.config.SESSION_EXPIRATION ) ) auth_token = self.jwt.encode(payload) self.set_cookie('HOLMES_AUTH_TOKEN', auth_token) self.write_json(dict(authenticated=True, first_login=user.first_login)) else: self.set_unauthorized() def delete(self): self.clear_cookie('HOLMES_AUTH_TOKEN') self.write_json({'loggedOut': True}) @gen.coroutine def authenticate(self, provider, access_token): ''' Authenticate user with the given access_token on the specific provider method. If it returns the user data, try to fetch the user on the database or create user if it doesn`t exist and then return the user object. Otherwise, returns None, meaning invalid authentication parameters. ''' if provider == u'GooglePlus': oauth_user = yield self.authenticate_on_google(access_token) else: oauth_user = None if oauth_user: db = self.application.db user = User.by_email(oauth_user['email'], db) if user: user.last_login = datetime.utcnow() db.flush() db.commit() # FIXME, test if commit() is necessary user.first_login = False else: user = User.add_user( db, oauth_user['fullname'], oauth_user['email'], provider, datetime.utcnow() ) user.first_login = True else: user = None raise gen.Return(user) @gen.coroutine def authenticate_on_google(self, access_token): ''' Try to get Google user info and returns it if the given access_token get`s a valid user info in a string json format. If the response was not an status code 200 or get an error on Json, None was returned. Example of return on success: { id: "1234567890abcdef", email: "...@gmail.com", fullname: "Ricardo L. Dani", } ''' response = yield self._fetch_google_userinfo(access_token) if response.code == 200: body = loads(response.body) if not body.get('error'): raise gen.Return({ 'email': body.get("email"), 'fullname': body.get("name"), 'id': body.get("id") }) raise gen.Return(None) @gen.coroutine def _fetch_google_userinfo(self, access_token): google_api_url = 'https://www.googleapis.com/oauth2/v1/userinfo' url = '%s?access_token=%s' % (google_api_url, access_token) try: response = yield self.application.http_client.fetch( url, proxy_host=self.application.config.HTTP_PROXY_HOST, proxy_port=self.application.config.HTTP_PROXY_PORT ) except HTTPError, e: response = e.response raise gen.Return(response)
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * from distutils.dir_util import copy_tree, mkpath from distutils.file_util import copy_file class Fastqc(Package): """A quality control tool for high throughput sequence data.""" homepage = "http://www.bioinformatics.babraham.ac.uk/projects/fastqc/" url = "http://www.bioinformatics.babraham.ac.uk/projects/fastqc/fastqc_v0.11.5.zip" version('0.11.7', '8fead05fa62c5e723f0d2157a9b5fcd4') version('0.11.5', '3524f101c0ab0bae77c7595983170a76') version('0.11.4', '104ff2e0e9aebf5bee1f6b068a059b0d') depends_on('java', type='run') depends_on('perl') # for fastqc "script", any perl will do patch('fastqc.patch', level=0) def install(self, spec, prefix): mkpath(self.prefix.bin) mkpath(self.prefix.lib) copy_file('fastqc', self.prefix.bin) for j in ['cisd-jhdf5.jar', 'jbzip2-0.9.jar', 'sam-1.103.jar']: copy_file(j, self.prefix.lib) for d in ['Configuration', 'net', 'org', 'Templates', 'uk']: copy_tree(d, join_path(self.prefix.lib, d)) chmod = which('chmod') chmod('+x', join_path(self.prefix.bin, 'fastqc')) # In theory the 'run' dependency on 'jdk' above should take # care of this for me. In practice, it does not. def setup_environment(self, spack_env, run_env): """Add <prefix> to the path; the package has a script at the top level. """ run_env.prepend_path('PATH', join_path(self.spec['java'].prefix, 'bin'))
<?php namespace XoopsModules\Xsitemap\Common; /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. 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. */ /** * Breadcrumb Class * * @copyright XOOPS Project (https://xoops.org) * @license http://www.fsf.org/copyleft/gpl.html GNU public license * @author lucio <lucio.rota@gmail.com> * @package pedigree * @since 3.23 * @version $Id: breadcrumb.php 12865 2014-11-22 07:03:35Z beckmi $ * * Example: * $breadcrumb = new PedigreeBreadcrumb(); * $breadcrumb->addLink( 'bread 1', 'index1.php' ); * $breadcrumb->addLink( 'bread 2', '' ); * $breadcrumb->addLink( 'bread 3', 'index3.php' ); * echo $breadcrumb->render(); */ defined('XOOPS_ROOT_PATH') || die('XOOPS Root Path not defined'); /** * Class Breadcrumb */ class Breadcrumb { public $dirname; private $bread = []; /** * */ public function __construct() { $this->dirname = basename(dirname(__DIR__)); } /** * Add link to breadcrumb * * @param string $title * @param string $link */ public function addLink($title = '', $link = '') { $this->bread[] = [ 'link' => $link, 'title' => $title ]; } /** * Render Pedigree BreadCrumb * */ public function render() { if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) { require_once $GLOBALS['xoops']->path('class/theme.php'); $GLOBALS['xoTheme'] = new \xos_opal_Theme(); } require_once $GLOBALS['xoops']->path('class/template.php'); $breadcrumbTpl = new \XoopsTpl(); $breadcrumbTpl->assign('breadcrumb', $this->bread); $html = $breadcrumbTpl->fetch('db:' . $this->dirname . '_common_breadcrumb.tpl'); unset($breadcrumbTpl); return $html; } }
/* * C293PCIE Board Setup * * Copyright 2013 Freescale Semiconductor 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 2 of the License, or (at your * option) any later version. */ #include <linux/stddef.h> #include <linux/kernel.h> #include <linux/of_fdt.h> #include <linux/of_platform.h> #include <asm/machdep.h> #include <asm/udbg.h> #include <asm/mpic.h> #include <sysdev/fsl_soc.h> #include <sysdev/fsl_pci.h> #include "mpc85xx.h" void __init c293_pcie_pic_init(void) { struct mpic *mpic = mpic_alloc(NULL, 0, MPIC_BIG_ENDIAN | MPIC_SINGLE_DEST_CPU, 0, 256, " OpenPIC "); BUG_ON(mpic == NULL); mpic_init(mpic); } /* * Setup the architecture */ static void __init c293_pcie_setup_arch(void) { if (ppc_md.progress) { ppc_md.progress("c293_pcie_setup_arch()", 0); } fsl_pci_assign_primary(); printk(KERN_INFO "C293 PCIE board from Freescale Semiconductor\n"); } machine_arch_initcall(c293_pcie, mpc85xx_common_publish_devices); /* * Called very early, device-tree isn't unflattened */ static int __init c293_pcie_probe(void) { if (of_machine_is_compatible("fsl,C293PCIE")) { return 1; } return 0; } define_machine(c293_pcie) { .name = "C293 PCIE", .probe = c293_pcie_probe, .setup_arch = c293_pcie_setup_arch, .init_IRQ = c293_pcie_pic_init, .get_irq = mpic_get_irq, .calibrate_decr = generic_calibrate_decr, .progress = udbg_progress, };
# -*- coding: utf-8 -*- # Copyright 2015 Objectif Libre # # 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. # from wsme import types as wtypes from cloudkitty.api.v1 import types as ck_types class Group(wtypes.Base): """Type describing a group. A group is used to divide calculations. It can be used to create a group for the instance rating (flavor) and one if we have premium images (image_id). So you can take into account multiple parameters during the rating. """ group_id = wtypes.wsattr(ck_types.UuidType(), mandatory=False) """UUID of the group.""" name = wtypes.wsattr(wtypes.text, mandatory=True) """Name of the group.""" @classmethod def sample(cls): sample = cls(group_id='afe898cb-86d8-4557-ad67-f4f01891bbee', name='instance_rating') return sample class GroupCollection(wtypes.Base): """Type describing a list of groups. """ groups = [Group] """List of groups.""" @classmethod def sample(cls): sample = Group.sample() return cls(groups=[sample])
import { expect } from 'chai'; /** * Compares instance with expected values */ export function assertInstance(instance: any | any[], expectedValues: any | any[]): void { if (Array.isArray(expectedValues)) { expect(instance).to.have.property('length', expectedValues.length); return instance.forEach((_instance, i) => assertInstance(_instance, expectedValues[i])); } expect(instance).to.have.property('id').that.is.not.null; Object.keys(expectedValues).forEach((key) => { const value = instance[key]; const expectedValue = expectedValues[key]; expect(instance).to.have.property(key).that.is.not.null.and.not.undefined; if (typeof expectedValue === 'object') { assertInstance(value, expectedValue); } else { expect(instance).to.have.property(key, expectedValue); } }); }
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the POSDictionaryWriter.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2004 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of 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, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections.Generic; using System.IO; namespace OpenNLP.Tools.PosTagger { /// <summary> /// Class that helps generate part-of-speech lookup list files. /// </summary> public class PosLookupListWriter { private string mDictionaryFile; private Dictionary<string, Util.Set<string>> mDictionary; private Dictionary<string, int> mWordCounts; /// <summary> /// Creates a new part-of-speech lookup list, specifying the location to write it to. /// </summary> /// <param name="file"> /// File to write the new list to. /// </param> public PosLookupListWriter(string file) { mDictionaryFile = file; mDictionary = new Dictionary<string, Util.Set<string>>(); mWordCounts = new Dictionary<string, int>(); } /// <summary> /// Adds an entry to the lookup list in memory, ready for writing to file. /// </summary> /// <param name="word"> /// The word for which an entry should be added. /// </param> /// <param name="tag"> /// The tag that should be marked as valid for this word. /// </param> public virtual void AddEntry(string word, string tag) { Util.Set<string> tags; if (mDictionary.ContainsKey(word)) { tags = mDictionary[word]; } else { tags = new Util.Set<string>(); mDictionary.Add(word, tags); } tags.Add(tag); if (!(mWordCounts.ContainsKey(word))) { mWordCounts.Add(word, 1); } else { mWordCounts[word]++; } } /// <summary> /// Write the lookup list entries to file with a default cutoff of 5. /// </summary> public virtual void Write() { Write(5); } /// <summary> /// Write the lookup list entries to file. /// </summary> /// <param name="cutoff"> /// The number of times a word must have been added to the lookup list for it to be considered important /// enough to write to file. /// </param> public virtual void Write(int cutoff) { using (StreamWriter writer = new StreamWriter(mDictionaryFile)) { foreach (string word in mDictionary.Keys) { if (mWordCounts[word] > cutoff) { writer.Write(word); Util.Set<string> tags = mDictionary[word]; foreach (string tag in tags) { writer.Write(" "); writer.Write(tag); } writer.Write(System.Environment.NewLine); } } writer.Close(); } } } }
using FluentAssertions; using iSynaptic.Commons; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace iSynaptic { [TestFixture] public class LogicalTypeRegistryTests { [Test] public void SimpleMapping_BehavesCorrectly() { var logicalType = LogicalType.Parse("sys:String"); var actualType = typeof(string); var registry = new LogicalTypeRegistry(); registry.AddMapping(logicalType, actualType); registry.LookupActualType(logicalType).Should().Be(actualType); registry.LookupLogicalType(actualType).Should().Be(logicalType); } [Test] public void ClosedTypes_MapCorrectly() { var logicalType = LogicalType.Parse("syn:Maybe<sys:Int32>"); var actualType = typeof(Maybe<int>); var registry = new LogicalTypeRegistry(); registry.AddMapping(logicalType, actualType); registry.LookupActualType(logicalType).Should().Be(actualType); registry.LookupLogicalType(actualType).Should().Be(logicalType); } [Test] public void OpenTypes_MapCorrectly() { var logicalType = LogicalType.Parse("syn:Maybe`1"); var actualType = typeof(Maybe<>); var registry = new LogicalTypeRegistry(); registry.AddMapping(logicalType, actualType); registry.LookupActualType(logicalType).Should().Be(actualType); registry.LookupLogicalType(actualType).Should().Be(logicalType); } [Test] public void CannotMapOpenLogicalTypeToClosedActualType() { var logicalType = LogicalType.Parse("syn:Maybe`1"); var actualType = typeof(Maybe<int>); var registry = new LogicalTypeRegistry(); registry.Invoking(x => x.AddMapping(logicalType, actualType)) .ShouldThrow<ArgumentException>(); } [Test] public void CannotMapClosedLogicalTypeToOpenActualType() { var logicalType = LogicalType.Parse("syn:Maybe<sys:Int32>"); var actualType = typeof(Maybe<>); var registry = new LogicalTypeRegistry(); registry.Invoking(x => x.AddMapping(logicalType, actualType)) .ShouldThrow<ArgumentException>(); } [Test] public void CannotMapOpenTypesWithMismatchedArity() { var registry = new LogicalTypeRegistry(); registry.Invoking(x => x.AddMapping(LogicalType.Parse("syn:Maybe"), typeof(Maybe<>))) .ShouldThrow<ArgumentException>(); registry.Invoking(x => x.AddMapping(LogicalType.Parse("syn:Maybe`2"), typeof(Maybe<>))) .ShouldThrow<ArgumentException>(); } [Test] public void CannotAddDuplicateMappings() { var registry = new LogicalTypeRegistry(); registry.AddMapping(LogicalType.Parse("sys:String"), typeof(string)); registry.Invoking(x => x.AddMapping(LogicalType.Parse("sys:String"), typeof(int))) .ShouldThrow<ArgumentException>(); registry.Invoking(x => x.AddMapping(LogicalType.Parse("tst:Description"), typeof(string))) .ShouldThrow<ArgumentException>(); } [Test] public void LookupActualTypeUsingClosedLogicalType_ViaOpenMapping() { var registry = new LogicalTypeRegistry(); registry.AddMapping(LogicalType.Parse("syn:Result`2"), typeof(Result<,>)); registry.AddMapping(LogicalType.Parse("sys:Int32"), typeof(int)); registry.AddMapping(LogicalType.Parse("sys:String"), typeof(string)); registry.LookupActualType(LogicalType.Parse("syn:Result<sys:Int32, sys:String>")) .Should().Be(typeof(Result<int, string>)); } [Test] public void LookupLogicalTypeUsingClosedActualType_ViaOpenMapping() { var registry = new LogicalTypeRegistry(); registry.AddMapping(LogicalType.Parse("syn:Result`2"), typeof(Result<,>)); registry.AddMapping(LogicalType.Parse("sys:Int32"), typeof(int)); registry.AddMapping(LogicalType.Parse("sys:String"), typeof(string)); registry.LookupLogicalType(typeof(Result<int, string>)) .Should().Be(LogicalType.Parse("syn:Result<sys:Int32, sys:String>")); } } }
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-392.js * @description ES5 Attributes - [[Value]] attribute of data property is a Date object */ function testcase() { var obj = {}; var dateObj = new Date(); Object.defineProperty(obj, "prop", { value: dateObj }); var desc = Object.getOwnPropertyDescriptor(obj, "prop"); return obj.prop === dateObj && desc.value === dateObj; } runTestCase(testcase);
<?php namespace common\models; use Yii; /** * This is the model class for table "goods_delivery". * * @property integer $id * @property string $ucat_id * @property string $cat_id * @property string $title * @property string $finish_date * @property string $delivery_text * @property integer $active */ class GoodsSending extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'goods_sending'; } /** * @inheritdoc */ public function rules() { return [ [['ucat_id', 'cat_id', 'title', 'finish_date', 'delivery_text', 'active'], 'required'], [['finish_date'], 'safe'], [['active'], 'integer'], [['ucat_id', 'cat_id'], 'string', 'max' => 6], [['title', 'delivery_text'], 'string', 'max' => 255], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'ucat_id' => 'Подкаталог', 'cat_id' => 'Каталог', 'title' => 'Заглавие', 'finish_date' => 'Дата окончания приема заказов', 'delivery_text' => 'Текст о доставке', 'active' => 'Active', ]; } }
/* * Copyright (c) 2017, Wasiq Bhamla. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.wasiqb.coteafs.appium.constants; /** * @author wasiq.bhamla * @since Jul 22, 2017 10:02:54 PM */ public interface ErrorMessage { /** * Server stopped error message. */ String SERVER_STOPPED = "Server Session has been stopped."; }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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. // File System.Net.OpenWriteCompletedEventArgs.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Net { public partial class OpenWriteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { #region Methods and constructors internal OpenWriteCompletedEventArgs() : base (default(Exception), default(bool), default(Object)) { } #endregion #region Properties and indexers public Stream Result { get { Contract.Ensures(!this.Cancelled); Contract.Ensures(this.Error == null); return default(Stream); } } #endregion } }
// // DCAccountPsdView.h // STOExpressDelivery // // Created by 陈甸甸 on 2018/2/6. //Copyright © 2018年 STO. All rights reserved. // #import <UIKit/UIKit.h> @interface DCAccountPsdView : UIView @end
# Copyright (c) 2012 Rackspace Hosting Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from sqlalchemy.dialects import sqlite from sqlalchemy import types class INET(types.TypeDecorator): impl = types.CHAR def load_dialect_impl(self, dialect): # IPv6 is 128 bits => 2^128 == 3.4e38 => 39 digits return dialect.type_descriptor(types.CHAR(39)) def process_bind_param(self, value, dialect): if value is None: return value return str(value) def process_result_value(self, value, dialect): if value is None: return value return long(value) def coerce_compared_value(self, op, value): # NOTE(mdietz): If left unimplemented, the column is coerced into a # string every time, causing the next_auto_assign_increment to be a # string concatenation rather than an addition. 'value' in the # signature is the "other" value being compared for the purposes of # casting. if isinstance(value, int): return types.Integer() return self class MACAddress(types.TypeDecorator): impl = types.BigInteger def load_dialect_impl(self, dialect): if dialect.name == 'sqlite': return dialect.type_descriptor(sqlite.CHAR) return dialect.type_descriptor(self.impl)
"""Utility functions for handling and fetching repo archives in zip format.""" import os import tempfile from zipfile import BadZipFile, ZipFile import requests from cookiecutter.exceptions import InvalidZipRepository from cookiecutter.prompt import read_repo_password from cookiecutter.utils import make_sure_path_exists, prompt_and_delete def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None): """Download and unpack a zipfile at a given URI. This will download the zipfile to the cookiecutter repository, and unpack into a temporary directory. :param zip_uri: The URI for the zipfile. :param is_url: Is the zip URI a URL or a file? :param clone_to_dir: The cookiecutter repository directory to put the archive into. :param no_input: Suppress any prompts :param password: The password to use when unpacking the repository. """ # Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) if is_url: # Build the name of the cached zipfile, # and prompt to delete if it already exists. identifier = zip_uri.rsplit('/', 1)[1] zip_path = os.path.join(clone_to_dir, identifier) if os.path.exists(zip_path): download = prompt_and_delete(zip_path, no_input=no_input) else: download = True if download: # (Re) download the zipfile r = requests.get(zip_uri, stream=True) with open(zip_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) else: # Just use the local zipfile as-is. zip_path = os.path.abspath(zip_uri) # Now unpack the repository. The zipfile will be unpacked # into a temporary directory try: zip_file = ZipFile(zip_path) if len(zip_file.namelist()) == 0: raise InvalidZipRepository('Zip repository {} is empty'.format(zip_uri)) # The first record in the zipfile should be the directory entry for # the archive. If it isn't a directory, there's a problem. first_filename = zip_file.namelist()[0] if not first_filename.endswith('/'): raise InvalidZipRepository( 'Zip repository {} does not include ' 'a top-level directory'.format(zip_uri) ) # Construct the final target directory project_name = first_filename[:-1] unzip_base = tempfile.mkdtemp() unzip_path = os.path.join(unzip_base, project_name) # Extract the zip file into the temporary directory try: zip_file.extractall(path=unzip_base) except RuntimeError: # File is password protected; try to get a password from the # environment; if that doesn't work, ask the user. if password is not None: try: zip_file.extractall(path=unzip_base, pwd=password.encode('utf-8')) except RuntimeError: raise InvalidZipRepository( 'Invalid password provided for protected repository' ) elif no_input: raise InvalidZipRepository( 'Unable to unlock password protected repository' ) else: retry = 0 while retry is not None: try: password = read_repo_password('Repo password') zip_file.extractall( path=unzip_base, pwd=password.encode('utf-8') ) retry = None except RuntimeError: retry += 1 if retry == 3: raise InvalidZipRepository( 'Invalid password provided for protected repository' ) except BadZipFile: raise InvalidZipRepository( 'Zip repository {} is not a valid zip archive:'.format(zip_uri) ) return unzip_path
/* * Copyright (c) 2015, AZQ. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ #ifndef _CHK_ERR_H_ #define _CHK_ERR_H_ // if x is ZERO, return -1. #define CHK_ZI(x)\ do {\ if (!(x)) return -1;\ } while (0) // if x is NEGATIVE, return -1. #define CHK_NI(x)\ do {\ if ((x)<0) return -1;\ } while (0) // if x is NON-ZERO, return -1. #define CHK_NZI(x)\ do {\ if ((x)) return -1;\ } while (0) // if x is ZERO, print msg to stderr and return -1. #define CHK_ZPI(x,msg)\ do {\ if (!(x)) {\ fprintf(stderr, "error: %s\n", (msg));\ return -1;\ }\ } while (0) // if x is NEGATIVE, print msg to stderr and return -1. #define CHK_NPI(x,msg)\ do {\ if ((x)<0) {\ fprintf(stderr, "error: %s\n", (msg));\ return -1;\ }\ } while (0) // if x is NON-ZERO, print msg to stderr and return -1. #define CHK_NZPI(x,msg)\ do {\ if ((x)) {\ fprintf(stderr, "error: %s\n", (msg));\ return -1;\ }\ } while (0) // if x is ZERO, print errno and msg to stderr and return -1. #define CHK_ZEI(x,msg)\ do {\ if (!(x)) {\ fprintf(stderr, "error: %s - %s\n", strerror(errno), (msg));\ return -1;\ }\ } while (0) // if x is NEGATIVE, print errno and msg to stderr and return -1. #define CHK_NEI(x,msg)\ do {\ if ((x)<0) {\ fprintf(stderr, "error: %s - %s\n", strerror(errno), (msg));\ return -1;\ }\ } while (0) // if x is NON-ZERO, print errno and msg to stderr and return -1. #define CHK_NZEI(x,msg)\ do {\ if ((x)) {\ fprintf(stderr, "error: %s - %s\n", strerror(errno), (msg));\ return -1;\ }\ } while (0) #endif /* _CHK_ERR_H_ */
#!/usr/bin/env node 'use strict'; const argv = require('yargs') .usage('Usage: $0 -i [file] -o [dir]') .demand(['inputFile', 'outputDirectory']) .alias('inputFile', 'i') .alias('outputDirectory', 'o') .alias('smushLayers', 's') .alias('stitchTiles', 'l') .alias('stitchWidth', 'w') .default('stitchWidth', 10) .boolean('smushLayers') .boolean('stitchTiles') .describe('inputFile', 'The .pyxel file you wish to export.') .describe('outputDirectory', 'The directory where I put the exported tiles.') .describe('smushLayers', 'Smush all the layers and export the result.') .describe('stitchTiles', 'Grab all the tiles from the Pyxel file and stitch them into one image.') .describe('stitchWidth', 'How wide the final stitched sheet is.') .example('$0 -i stoneTiles.pyxel -o assets/build', 'export all the tiles in stoneTiles.pyxel to assets/build') .example('$0 -i player.pyxel -o assets/build -s', 'export all the tiles in player.pyxel after first smushing the layers together') .example('$0 -i stoneTiles.pyxel -o assets/build -l -w 10', 'export one sheet of tiles with the given width') .argv; const path = require('path'); const AdmZip = require('adm-zip'); const Jimp = require('jimp'); const Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); const inputFile = new AdmZip(argv.inputFile); const entries = inputFile.getEntries(); // Gotta find docData.json. That's the metadata about the images within. const docDataFile = inputFile.getEntry('docData.json'); if (!docDataFile) { throw Error(`Missing docData.json in ${argv.inputFile}`); } const docData = JSON.parse(inputFile.readFile(docDataFile).toString()); // Cache the decoding of files for quicker access later. const imageHash = new Map(); function getImage(name) { if (imageHash.has(name)) { return Promise.resolve(imageHash.get(name)); } const entry = inputFile.getEntry(name); const buffer = inputFile.readFile(entry); return Jimp.read(buffer) .then(image => { imageHash.set(name, image); return image; }) .catch(e => { console.error(e); }) } function generateOutfilename(index = '') { return path.join(argv.outputDirectory, `${path.basename(argv.inputFile, '.pyxel')}${index}.png`); } function smushLayers() { // All the tiles in this thing. Each is an array of an image that we'll squash later. const outputTiles = new Map(); // Do in reverse order cuz we're applying composite, one on top of another. const layerKeys = Object.keys(docData.canvas.layers).reverse(); return Promise.resolve(layerKeys) .map(layerKey => docData.canvas.layers[layerKey]) .filter(layer => !layer.hidden) .map(layer => { return Promise.resolve(Object.keys(layer.tileRefs)) .map(tileRefKey => { const tileRef = layer.tileRefs[tileRefKey]; let outputTile = outputTiles.get(tileRefKey); if (!outputTile) { // TODO: Support tileset fixedWidth === false outputTile = new Jimp(docData.tileset.tileWidth, docData.tileset.tileHeight); outputTiles.set(tileRefKey, outputTile); } return getImage(`tile${tileRef.index}.png`) .then(tile => { // TODO: Support layer alpha, blendmode // TODO: Support tile rotation and flip outputTile.composite(tile, 0, 0); }) .catch(e => { console.error(e); }); }) }) .then(() => { outputTiles.forEach((value, key) => { value.write(generateOutfilename(key), function (error, img) { if (error) { throw error; } }); }); }); } function getAllTheTilenames() { return Promise.resolve(new Array(docData.tileset.numTiles)) // Generate the filenames in the input file. .map((_, i) => `tile${i}.png`) } function stitchTiles() { const { tileWidth, tileHeight, numTiles } = docData.tileset; if (!numTiles) { // Do nothing if we've got no tiles. return; } const width = Math.min(argv.stitchWidth * tileWidth, numTiles * tileWidth); const height = Math.max(Math.round(numTiles / argv.stitchWidth) * tileHeight, tileHeight); return new Promise((resolve, reject) => { const image = new Jimp(width, height, (err, image) => { if (err) { reject(err); } else { resolve(image); } }); }) .then(image => { return getAllTheTilenames() .map(getImage) .map((tileImage, i) => { const x = i % argv.stitchWidth; const y = Math.floor(i / argv.stitchWidth); const tileX = x * tileWidth; const tileY = y * tileHeight; return image.blit(tileImage, tileX, tileY); }) .then(() => image) }) .then(image => image.write(generateOutfilename())) .catch(e => { console.error(e); }) } function exportTheTiles() { // Easy peasey. Write out all the tile files in a format matching the inputFile tilename. return getAllTheTilenames() .map(filename => inputFile.getEntry(filename)) .map((zipEntry, i) => fs.writeFileAsync(generateOutfilename(i), zipEntry.getData())) .catch(e => { console.error(e); }); } if (argv.smushLayers) { smushLayers(); } if (argv.stitchTiles) { stitchTiles(); } else { exportTheTiles(); }
#!python # capture web2py environment before doing anything else web2py_environment = dict(globals()) __doc__ = """This script is run from the nose command in the application being tested: e.g. python2.6 ./applications/eden/tests/nose.py <nose arguments> web2py runs a file which: 1. Sets up a plugin. This plugin registers itself so nose can use it. 2. Runs nose programmatically giving it the plugin nose loads the tests via the plugin. when the plugin loads the tests, it injects the web2py environment. """ import sys from types import ModuleType import nose import glob import os.path import os import copy from gluon.globals import Request import unittest def load_module(application_relative_module_path): import os web2py_relative_module_path = ".".join(( "applications", request.application, application_relative_module_path )) imported_module = __import__(web2py_relative_module_path) for step in web2py_relative_module_path.split(".")[1:]: imported_module = getattr(imported_module, step) return imported_module web2py_environment["load_module"] = load_module web2py_env_module = ModuleType("web2py_env") web2py_env_module.__dict__.update(web2py_environment) sys.modules["web2py_env"] = web2py_env_module application_name = request.application application_folder_path = os.path.join("applications",application_name) application = application_name controller = "controller" function = "function" folder = os.path.join(os.getcwd(), "applications", application_name) web2py_environment["Request"] = Request request = Request() request.application = application request.controller = controller request.function = function request.folder = folder web2py_environment["request"] = request current.request = request controller_configuration = OrderedDict() for controller_name in ["default"]+glob.glob( os.path.join(application_folder_path, "controllers", "*.py") ): controller_configuration[controller_name] = Storage( name_nice = controller_name, description = controller_name, restricted = False, module_type = 0 ) current.deployment_settings.modules = controller_configuration test_folders = set() argv = [] # folder in which tests are kept # non-option arguments (test paths) are made relative to this test_root = os.path.join(application_folder_path, "tests", "unit_tests") current_working_directory = os.getcwd() disallowed_options = {} disallowed_options["-w"] = disallowed_options["--where"] = ( "web2py does not allow changing directory" ) for arg in sys.argv[1:]: if arg.startswith("-"): if not arg.startswith("--"): print ( "\nSorry, please use verbose option names " "(currently need this to distinguish options from paths)" ) sys.exit(1) else: try: reason = disallowed_options[arg] except KeyError: pass else: print "\nSorry, %s option is not accepted as %s" % (arg, reason) sys.exit(1) argv.append(arg) else: test_path = arg test_folder_fuller_path = os.path.join(test_root, test_path) test_folders.add(test_folder_fuller_path) if not os.path.exists(test_folder_fuller_path): print "\n", test_folder_fuller_path, "not found" #sys.exit(1) # test paths in command line aren't passed, just added to test_folders # the plugin does the testing # nose just searches everything from the test_root # so we give it the test root argv.append(test_root) # if no test folders are given, assume we test everything from the test_root if len(test_folders) == 0: test_folders.add(test_root) sys.argv[1:] = argv test_utils = local_import("test_utils") nose.main( # seems at least this version of nose ignores passed in argv # argv = argv, addplugins = nose.plugins.PluginManager([ test_utils.Web2pyNosePlugin( application_name, web2py_environment, re.compile( re.escape(os.path.sep).join( ( "web2py(?:", "applications(?:", application_name+"(?:", "tests(?:", "[^","]*)*)?)?)?$" ) ) ), test_folders ) ]) )
# Copyright (C) 2010-2011 Richard Lincoln # # 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. from CIM15.CDPSM.Geographical.IEC61970.Core.ConductingEquipment import ConductingEquipment class Fuse(ConductingEquipment): """An overcurrent protective device with a circuit opening fusible part that is heated and severed by the passage of overcurrent through it. A fuse is considered a switching device because it breaks current. """ def __init__(self, *args, **kw_args): """Initialises a new 'Fuse' instance. """ super(Fuse, self).__init__(*args, **kw_args) _attrs = [] _attr_types = {} _defaults = {} _enums = {} _refs = [] _many_refs = []
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://www.xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include <list> #include "system.h" #include "DllAvFormat.h" #include "DllAvCodec.h" #include "DllAvUtil.h" #include "DVDAudioCodec.h" class CDVDAudioCodecPassthroughFFmpeg : public CDVDAudioCodec { public: CDVDAudioCodecPassthroughFFmpeg(); virtual ~CDVDAudioCodecPassthroughFFmpeg(); virtual bool Open(CDVDStreamInfo &hints, CDVDCodecOptions &options); virtual void Dispose(); virtual int Decode(uint8_t* pData, int iSize); virtual int GetData(uint8_t** dst); virtual void Reset(); virtual int GetChannels(); virtual CAEChannelInfo GetChannelMap(); virtual int GetSampleRate(); virtual int GetEncodedSampleRate(); virtual enum AEDataFormat GetDataFormat(); virtual int GetBitsPerSample(); virtual bool NeedPassthrough() { return true; } virtual const char* GetName() { return "PassthroughFFmpeg"; } virtual int GetBufferSize(); private: DllAvFormat m_dllAvFormat; DllAvUtil m_dllAvUtil; DllAvCodec m_dllAvCodec; typedef struct { int size; uint8_t *data; } DataPacket; typedef struct { AVFormatContext *m_pFormat; AVStream *m_pStream; std::list<DataPacket*> m_OutputBuffer; unsigned int m_OutputSize; bool m_WroteHeader; unsigned char m_BCBuffer[AVCODEC_MAX_AUDIO_FRAME_SIZE]; unsigned int m_Consumed; unsigned int m_BufferSize; uint8_t *m_Buffer; } Muxer; Muxer m_SPDIF, m_ADTS; bool SetupMuxer(CDVDStreamInfo &hints, CStdString muxerName, Muxer &muxer); static int MuxerReadPacket(void *opaque, uint8_t *buf, int buf_size); void WriteFrame(Muxer &muxer, uint8_t *pData, int iSize); int GetMuxerData(Muxer &muxer, uint8_t** dst); void ResetMuxer(Muxer &muxer); void DisposeMuxer(Muxer &muxer); bool m_bSupportsAC3Out; bool m_bSupportsDTSOut; bool m_bSupportsAACOut; CDVDAudioCodec *m_Codec; uint8_t *m_DecodeBuffer; unsigned int m_DecodeSize; bool SupportsFormat(CDVDStreamInfo &hints); uint8_t m_NeededBuffer[AVCODEC_MAX_AUDIO_FRAME_SIZE]; unsigned int m_NeededUsed; unsigned int m_Needed; bool m_LostSync; int m_SampleRate; AVCodecID m_codec; unsigned int (CDVDAudioCodecPassthroughFFmpeg::*m_pSyncFrame)(uint8_t* pData, unsigned int iSize, unsigned int *fSize); unsigned int SyncAC3(uint8_t* pData, unsigned int iSize, unsigned int *fSize); unsigned int SyncDTS(uint8_t* pData, unsigned int iSize, unsigned int *fSize); unsigned int SyncAAC(uint8_t* pData, unsigned int iSize, unsigned int *fSize); };
'use strict'; angular.module('myApp.view3', ['ui.router']) .config(['$stateProvider', function($stateProvider) { $stateProvider.state({ name: 'step3', url: '/step3', templateUrl: 'views/step3.html', controller: 'View3Ctrl' }); }]) .controller('View3Ctrl', [ '$scope', function($scope) { /** * * @param arr<Array> * @param obj<Object> * @param attr<String> * @param type<String> */ function createObjectsArray(arr, obj, attr, type) { for(var i = 0; i < arr.length; i++){ if(angular.isUndefined(obj[arr[i][attr]])){ obj[arr[i][attr]] = {}; obj[arr[i][attr]].prices = []; if(type === 'wall'){ obj[arr[i][attr]].sizes = $scope.series.tile_sizes.wall; obj[arr[i][attr]].size = $scope.series.tile_sizes.wall.width + 'x' + $scope.series.tile_sizes.wall.height; obj[arr[i][attr]].layout = $scope.series.layout.wall; } else if(type === 'flor'){ obj[arr[i][attr]].sizes = $scope.series.tile_sizes.flor; obj[arr[i][attr]].size = $scope.series.tile_sizes.flor.width + 'x' + $scope.series.tile_sizes.flor.height; obj[arr[i][attr]].layout = $scope.series.layout.flor; } } } } function getDataTable() { var arr = []; for (var i in $scope.tableState.dataTable) arr.push($scope.tableState.dataTable[i]); return arr; } function sum(obj, param) { var sum = 0; for(var k in obj) sum += obj[k][param]; return sum; } $scope.gridData = JSON.parse(localStorage.getItem('gridInfo')); $scope.series = JSON.parse(localStorage.getItem('series')); $scope.tableState = {}; if( !localStorage.getItem('score') ){ $scope.tableState.tableHeaders = [ {id: 0, title:'#', sortParam: 'id', arrowState: 'arrow_drop_down', isActive: false}, {id: 1, title:'Цвет', sortParam: 'color', arrowState: 'arrow_drop_down', isActive: false}, {id: 2, title: 'Цена за 1шт.', sortParam: 'price', arrowState: 'arrow_drop_down', isActive: false}, {id: 3, title:'Розмеры', sortParam: 'size', arrowState: 'arrow_drop_down', isActive: false}, {id: 4, title: 'Количество', sortParam: 'quantity', arrowState: 'arrow_drop_down', isActive: false}, {id: 5, title:'Сумма', sortParam: 'sum', arrowState: 'arrow_drop_down', isActive: false} ]; $scope.tableState.dataTable = {}; if( $scope.gridData.wall ) createObjectsArray($scope.series.colors.wall, $scope.tableState.dataTable, 'color', 'wall'); if( $scope.gridData.flor ) createObjectsArray($scope.series.colors.flor, $scope.tableState.dataTable, 'color', 'flor'); if( $scope.gridData.wall ){ angular.forEach($scope.series.colors.wall, function (obj,i) { angular.forEach( $scope.gridData.wall.grid, function (grid, k) { angular.forEach( grid, function (row, index) { angular.forEach( row, function (cell, id) { cell.id = undefined; if ( angular.equals( cell.color, obj.color ) ) $scope.tableState.dataTable[obj.color].prices.push(cell.price); } ); }); }); }); } if( $scope.gridData.flor ){ angular.forEach($scope.series.colors.flor, function (obj,i) { angular.forEach( $scope.gridData.flor.grid, function (row, k) { angular.forEach( row, function (cell, id) { cell.id = undefined; if ( angular.equals( cell.color, obj.color ) ) $scope.tableState.dataTable[obj.color].prices.push(cell.price); }); }); }); } var id = 0; angular.forEach($scope.tableState.dataTable, function (value, key, dt ) { if(dt[key].prices.length > 0){ dt[key]['sum'] = value.prices[0] * value.prices.length; dt[key]['quantity'] = value.prices.length; dt[key]['price'] = value.prices[0]; dt[key]['color'] = key; dt[key]['id'] = id++; } else { delete dt[key]; } }); $scope.tableState.sum = sum($scope.tableState.dataTable, 'sum'); $scope.tableState.tableOfData = getDataTable(); $scope.tableState.sortVar = 'id'; localStorage.setItem( 'score', JSON.stringify($scope.tableState) ); } else { $scope.tableState = JSON.parse( localStorage.getItem('score') ); } $scope.sortColumnBy = function (sortParam, id) { for(var i = 0; i < $scope.tableState.tableHeaders.length; i++){ $scope.tableState.tableHeaders[i].arrowState = 'arrow_drop_down'; $scope.tableState.tableHeaders[i].isActive = false; } $scope.tableState.tableHeaders[id].isActive = true; if($scope.tableState.sortVar.indexOf('-') === -1){ $scope.tableState.sortVar = '-' + sortParam; $scope.tableState.tableHeaders[id].arrowState = 'arrow_drop_up'; } else { $scope.tableState.tableHeaders[id].arrowState = 'arrow_drop_down'; $scope.tableState.sortVar = sortParam.replace('-', ''); } }; /** * Save State */ function saveScore() { if ( localStorage.getItem('score') ) localStorage.setItem( 'score', JSON.stringify($scope.tableState) ); } $scope.$on('$destroy' , saveScore); window.onunload = saveScore; $scope.$on('restart', function () { $scope.tableState = {}; }); }]);
'use strict'; /** * Controller for the admin page. */ const co = require('co'); const _ = require('lodash'); const api = require('../services/api-proxy'); const Promise = require('bluebird'); const logger = require('../services/logger'); const config = require('../config/config'); const axios = require('axios'); let admin = {}; let callReasons = [ 'Technical Problem', '5h Update', 'New Transport', 'Finished BreakOut', 'Sickness', 'Emergency', 'Other' ]; const defaultOptions = (req) => { return { error: req.flash('error'), success: req.flash('success'), layout: 'master', isLoggedIn: req.user, language: req.language }; }; admin.showDashboardEmails = function*(req, res) { let options = defaultOptions(req); options.view = 'admin-emails'; let emailAddress = req.query.emailAddress; if(emailAddress) { options.data = {}; const emails = yield admin.getAllEmailsTo(emailAddress); // Date in JS is in ms but api response is in s options.data.emails = emails.map(email => { email.create_date = email.create_date * 1000; return email; }); } res.render('static/admin/dashboard', options); }; admin.showDashboardUsers = function*(req, res) { let options = defaultOptions(req); options.view = 'admin-users'; res.render('static/admin/dashboard', options); }; function getAccessTokenFromRequest(req) { return req.user.access_token; } admin.getSponsoringInvoicesByEventId = function(tokens, eventId) { return api.getModel(`/sponsoringinvoice/${eventId}/`, tokens); }; admin.addPayment = function *(req, res) { logger.info(`Trying to add payment for invoice ${req.body.invoice}`); let body = { amount: req.body.amount, fidorId: req.body.fidorId, date: Math.round(new Date().getTime() / 1000) }; try { yield api.postModel(`invoice/${req.body.invoice}/payment/`, req.user, body); res.sendStatus(200); } catch (err) { res.status(500); logger.error(`An error occured while trying to add a payment to invoice ${req.body.invoice}: `, err); if (err.message) { res.json({message: err.message}); } else { res.json({message: 'An unknown error occured'}); } } }; admin.setTeamSleepStatus = function *(req, res) { try { let team = yield api.putModel(`event/${req.body.eventid}/team`, req.body.teamid, req.user, { asleep: req.body.asleep }); res.redirect('/admin/event/teamoverview/'); } catch (err) { res.status(500); logger.error(`An error occured while trying to update the last contact ${req.body.update}: `, err); if (err.message) { res.json({message: err.message}); } else { res.json({message: 'An unknown error occured'}); } } }; admin.updateLastContact = function *(req, res) { try { let comment = yield api.postModel(`teamoverview/${req.body.teamid}/lastContactWithHeadquarters/`, req.user, { comment: req.body.update, reason: req.body.reason }); res.redirect('/admin/event/teamoverview/'); } catch (err) { res.status(500); logger.error(`An error occured while trying to update the last contact ${req.body.update}: `, err); if (err.message) { res.json({message: err.message}); } else { res.json({message: 'An unknown error occured'}); } } }; admin.getAllEmailsTo = function(emailAddress) { return axios.get(`https://mail.break-out.org/get/to/${emailAddress}`, { headers: { 'X-AUTH-TOKEN': config.mailer.x_auth_token } }).then(resp => resp.data); }; admin.checkinTeam = function *(req, res) { const tokens = req.user; const update = {hasStarted: true}; let checkin = yield api.putModel(`event/${req.body.event}/team`, req.body.team, tokens, update); if (!checkin) return res.sendStatus(500); return res.sendStatus(200); }; admin.getAllInvoices = (req) => co(function*() { let rawInvoices = yield api.invoice.getAll(req.user); var teams = []; var invoices = rawInvoices.map(i => { if (i.payments.length) { i.payed = i.payments.reduce((prev, curr) => { return prev + curr.amount; }, 0); i.open = i.amount - i.payed; if (i.open < 0) i.open = 0; } else { i.payed = 0; i.open = i.amount; } return i; }); invoices.forEach(i => { if (!teams[i.teamId]) teams[i.teamId] = 0; teams[i.teamId] += i.payed; }); // TODO: This is unused, what is the reason? var depositTeams = teams.map((t, index) => { if (t > 100) { return { teamId: index, amount: t }; } }); return invoices; }).catch((ex) => { throw ex; }); admin.addAmountToInvoice = function *(req, res) { let addAmount = yield api.invoice.addAmount(req.user, req.body.invoiceId, req.body.amount); if (!addAmount) return res.sendStatus(500); return res.sendStatus(200); }; admin.addInvoice = function *(req, res) { var body = { firstname: req.body.firstname, lastname: req.body.lastname, company: req.body.company, teamId: parseFloat(req.body.teamId), amount: parseFloat(req.body.amount) }; let addAmount = yield api.invoice.create(req.user, body); if (!addAmount) return res.sendStatus(500); return res.status(200).send(addAmount); }; admin.challengeProof = function *(req, res) { let challenge = yield api.admin.challengeProof(req.user.access_token, req.body.challengeId, req.body.postingId); if (!challenge) return res.sendStatus(500); return res.status(200).send(challenge); }; module.exports = admin;
import os import numpy def createMemmapFileFn(path, prefix, elementDim, dataTypeDim, dataType): return path + os.sep + prefix + \ ( ('.' + str( max(1, elementDim)) ) if elementDim is not None else '' ) + \ ( ('.' + str(dataTypeDim)) if dataTypeDim > 1 or elementDim is not None else '' ) + \ '.' + dataType.replace('|', '') def parseMemmapFileFn(fn): fn = os.path.basename(fn) splittedFn = fn.split('.') prefix = splittedFn[0] elementDim = int(splittedFn[1]) if len(splittedFn)==4 else None dtypeDim = int(splittedFn[-2]) if len(splittedFn) in [3,4] else 1 dtype = splittedFn[-1] return prefix, elementDim, dtypeDim, dtype def calcShape(fn, elementDim, dtypeDim, dtype): dTypeSize = numpy.dtype(dtype).itemsize elementSize = dTypeSize * (elementDim if elementDim is not None else 1) * dtypeDim shape = [(os.path.getsize(fn) / elementSize)] + \ ([elementDim] if elementDim is not None else []) + \ ([dtypeDim] if dtypeDim > 1 else []) return shape def calcShapeFromMemmapFileFn(fn): prefix, elementDim, dtypeDim, dtype = parseMemmapFileFn(fn) return calcShape(fn, elementDim, dtypeDim, dtype) def findEmptyVal(valDataType): if any(x in valDataType for x in ['str', 'S']): baseVal = '' elif 'int' in valDataType: from gtrackcore.util.CommonConstants import BINARY_MISSING_VAL baseVal = BINARY_MISSING_VAL elif 'float' in valDataType: baseVal = numpy.nan elif 'bool' in valDataType: baseVal = False else: from gtrackcore.util.CustomExceptions import ShouldNotOccurError raise ShouldNotOccurError('Error: valDataType (%s) not supported.' % valDataType) return baseVal
import { browser, by, protractor, $, element, ProtractorExpectedConditions } from 'protractor'; describe('basic e2e test with loading', function(): void { let EC: ProtractorExpectedConditions = protractor.ExpectedConditions; describe('home', function(): void { browser.get('/'); it('should load home page', function(): void { expect(browser.getTitle()).toBe('TestManagement Blog'); // Waits for the element 'td-loading' to not be present on the dom. browser.wait(EC.not(EC.presenceOf($('td-loading'))), 10000) .then(() => { // checks if elements were rendered expect(element(by.id('dashboard-favorites-card')).isPresent()).toBe(true); }); }); }); });
<?php /** * dynamic-comments (https://github.com/PotatoPowered/dynamic-types) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE * Redistributions of files must retain the above copyright notice. * * @author Blake Sutton <blake@potatopowered.net> * @copyright Copyright (c) Potato Powered Software * @link http://potatopowered.net * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace DynamicComments\Model\Entity; use Cake\ORM\Entity; /** * DynamicComment Entity. */ class DynamicComment extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * @var array */ protected $_accessible = [ '*' => true, 'id' => false, ]; }
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 Etienne Noreau-Hebert <e@zncb.io> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Trace http transactions and asset dependencies involved in loading a web page """ from wtrace.workers import Requester,Harvester from wtrace.traces import TraceTarget,TraceDesc class WebTracer: def __init__(self): self.traces = [] def trace(self,target_list): harvester = Harvester() harvester.start() # launch proxy process and monit thread requester = Requester(proxy_addr=harvester.proxy_address()) tracedescs = [] for target in target_list: tracedesc = TraceDesc(target) harvester.start_trace(tracedesc) requester.trace(tracedesc) harvester.end_trace() tracedescs.append(tracedesc) harvester.stop() self.traces += tracedescs return tracedescs def serialize_traces_to_dir(self,path): import cPickle, os for t in self.traces: try: fp = open(os.path.join(path,t.target.name+'.wt'),'w+') cPickle.dump(t,fp,cPickle.HIGHEST_PROTOCOL) fp.close() except OSError as e: print('err> error serializing trace: {}\n'.format(e)) def load_trace_from_file(self,path): import cPickle, os try: fp = open(path,'r') t = cPickle.load(fp) fp.close() if isinstance(t,TraceDesc): self.traces.append(t) else: print(u'discarding invalid trace {}\n'.format(unicode(t))) except OSError as e: print('err> error loading trace: {}\n'.format(e)) def load_traces_from_dir(self,path): import cPickle, os, glob files = glob.glob(os.path.join(path,'*.wt')) for fp in files: self.load_trace_from_file(fp) def list_traces(self): print(u"\n".join(unicode(t) for t in self.traces))
import random import math import statsmodels.api as sm import numpy as np #team dict # # strength = "some numerical measure of the (true) team strength # # #upperbound log 2 def ceillog2(x): return math.ceil(math.log(x)/math.log(2)) #a safe approx to ratio def saferatio(x,y): if x==0: x = 0.5 if y==0: y = 0.5 return float(x)/y def update_rankings(teams, result_rounds, wl=1,ss=0.1, massey=-1): #various kinds of updates - win/loss, score_share, etc tmp_wl = {t['name']:0 for t in teams} if wl > 0: for rr in result_rounds: for r in rr: vals = win_loss(r[0],r[1]) tmp_wl[r[0]['name']]+= vals[0] tmp_wl[r[1]['name']]+= vals[1] tmp_ss = {t['name']:0 for t in teams} if ss > 0: for rr in result_rounds: for r in rr: vals = score_share(r[0],r[1]) tmp_ss[r[0]['name']]+= vals[0] tmp_ss[r[1]['name']]+= vals[1] #LeagueVine uses Massey ratings as "Power Rankings" for Swiss tournaments in Ultimate Frisbee! tmp_massey = {t['name']:0 for t in teams} if massey > 0: tot_cols = sum([len(rr) for rr in result_rounds]) #total number of results tot_rows = len(teams) #indexing function, maps teamnames to row idx = { i[0]['name']:i[1] for i in zip(teams,range(len(teams)))} col = 0 A = np.zeros([tot_cols,tot_rows]) Y = np.zeros(tot_cols) for rr in result_rounds: for r in rr: #make A, Y matrices A[col][idx[r[0]['name']]] = 1 A[col][idx[r[1]['name']]] = -1 Y[col] = math.log(saferatio(r[0]['score'],r[1]['score'])) col += 1 #and solve by least squares for B #tmp_massey = lsqrssolve(A,Y) res = sm.OLS(Y,A).fit() #L2 regression #res = sm.QuantReg(Y,A).fit(q=0.5) #L1 regression #res = sm.OLS(Y,A).fit_regularized(L1_wt=1.0) #Lasso (L2 w/ L1 reg) for t,p in zip(teams,res.params): tmp_massey[t['name']] = p #res.params => tmp_massey values, in the same ordering, I think tmp_ratings = { t['name']:wl*tmp_wl[t['name']]+ss*tmp_ss[t['name']]+massey*tmp_massey[t['name']] for t in teams} #some combination above, gives us tmp_rankings for t in teams: t['oldrating']=t['rating'] #for fontes ranks t['rating'] = tmp_ratings[t['name']]
namespace CohesionAndCoupling { using System; using Utils; public class PathExtensionsExample { public static void Start() { const string FileWithoutExtension = "example"; const string FileWithExtension = "example.pdf"; const string FileWithSeveralExtensions = "example.new.pdf"; Console.WriteLine(PathExtensions.GetFileExtension(FileWithoutExtension)); Console.WriteLine(PathExtensions.GetFileExtension(FileWithExtension)); Console.WriteLine(PathExtensions.GetFileExtension(FileWithSeveralExtensions)); Console.WriteLine(PathExtensions.GetFileNameWithoutExtension(FileWithoutExtension)); Console.WriteLine(PathExtensions.GetFileNameWithoutExtension(FileWithExtension)); Console.WriteLine(PathExtensions.GetFileNameWithoutExtension(FileWithSeveralExtensions)); } } }
// @flow import freeze from '../freeze'; import typeNameFromValue from '../type-name-from-value'; test('null', () => { expect(typeNameFromValue(null)).toBe('null'); }); test('[]', () => { expect(typeNameFromValue(freeze([]))).toBe('[]'); }); test('[0]', () => { expect(typeNameFromValue(freeze([0]))).toBe('number[]'); }); test('[0, 1, 2, 3]', () => { expect(typeNameFromValue(freeze([0, 1, 2, 3]))).toBe('number[]'); }); test('[0, true]', () => { expect(typeNameFromValue(freeze([0, true]))).toBe('(boolean | number)[]'); }); test('{}', () => { expect(typeNameFromValue(freeze({}))).toBe('{}'); }); test('0', () => { expect(typeNameFromValue(0)).toBe('number'); });
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace Utilisateurs\UtilisateursBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Utilisateurs\UtilisateursBundle\Entity\Utilisateurs; class UtilisateursData extends AbstractFixture implements FixtureInterface, ContainerAwareInterface, OrderedFixtureInterface { private $container; public function setContainer(ContainerInterface $container = null) { $this->container = $container; } public function load(ObjectManager $manager) { $utilisateur1 = new Utilisateurs(); $utilisateur1->setUsername('Coco'); $utilisateur1->setEmail('coco@test.com'); $utilisateur1->setEnabled('1'); $utilisateur1->setPassword($this->container->get('security.encoder_factory')->getEncoder($utilisateur1)->encodePassword('1234',$utilisateur1->getSalt())); $manager->persist($utilisateur1); $utilisateur2 = new Utilisateurs(); $utilisateur2->setUsername('MoMo'); $utilisateur2->setEmail('momo@test.com'); $utilisateur2->setEnabled('1'); $utilisateur2->setPassword($this->container->get('security.encoder_factory')->getEncoder($utilisateur2)->encodePassword('1234',$utilisateur2->getSalt())); $manager->persist($utilisateur2); $utilisateur3 = new Utilisateurs(); $utilisateur3->setUsername('DoDo'); $utilisateur3->setEmail('Dodo@test.com'); $utilisateur3->setEnabled('1'); $utilisateur3->setPassword($this->container->get('security.encoder_factory')->getEncoder($utilisateur3)->encodePassword('1234',$utilisateur3->getSalt())); $manager->persist($utilisateur3); $utilisateur4 = new Utilisateurs(); $utilisateur4->setUsername('Lulu'); $utilisateur4->setEmail('Lulu@test.com'); $utilisateur4->setEnabled('1'); $utilisateur4->setPassword($this->container->get('security.encoder_factory')->getEncoder($utilisateur4)->encodePassword('1234',$utilisateur4->getSalt())); $manager->persist($utilisateur4); $manager->flush(); $this->addReference('utilisateur1', $utilisateur1); $this->addReference('utilisateur2', $utilisateur2); $this->addReference('utilisateur3', $utilisateur3); $this->addReference('utilisateur4', $utilisateur4); } public function getOrder() { return 5; } }
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Libxfontcache(AutotoolsPackage): """Xfontcache - X-TrueType font cache extension client library.""" homepage = "http://cgit.freedesktop.org/xorg/lib/libXfontcache" url = "https://www.x.org/archive/individual/lib/libXfontcache-1.0.5.tar.gz" version('1.0.5', '5030fc9c7f16dbb52f92a8ba2c574f5c') depends_on('libx11') depends_on('libxext') depends_on('xextproto', type='build') depends_on('fontcacheproto', type='build') depends_on('pkg-config@0.9.0:', type='build') depends_on('util-macros', type='build')
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; namespace Umbraco.Core.Persistence.Factories { // factory for // IContentType (document types) // IMediaType (media types) // IMemberType (member types) // internal class ContentTypeFactory { #region IContentType public IContentType BuildContentTypeEntity(ContentTypeDto dto) { var contentType = new ContentType(dto.NodeDto.ParentId); try { contentType.DisableChangeTracking(); BuildCommonEntity(contentType, dto); //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 contentType.ResetDirtyProperties(false); return contentType; } finally { contentType.EnableChangeTracking(); } } #endregion #region IMediaType public IMediaType BuildMediaTypeEntity(ContentTypeDto dto) { var contentType = new MediaType(dto.NodeDto.ParentId); try { contentType.DisableChangeTracking(); BuildCommonEntity(contentType, dto); //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 contentType.ResetDirtyProperties(false); } finally { contentType.EnableChangeTracking(); } return contentType; } #endregion #region IMemberType public IMemberType BuildMemberTypeEntity(ContentTypeDto dto) { throw new NotImplementedException(); } public IEnumerable<MemberTypeDto> BuildMemberTypeDtos(IMemberType entity) { var memberType = entity as MemberType; if (memberType == null || memberType.PropertyTypes.Any() == false) return Enumerable.Empty<MemberTypeDto>(); var dtos = memberType.PropertyTypes.Select(x => new MemberTypeDto { NodeId = entity.Id, PropertyTypeId = x.Id, CanEdit = memberType.MemberCanEditProperty(x.Alias), ViewOnProfile = memberType.MemberCanViewProperty(x.Alias), IsSensitive = memberType.IsSensitiveProperty(x.Alias) }).ToList(); return dtos; } #endregion #region Common private static void BuildCommonEntity(ContentTypeBase entity, ContentTypeDto dto) { entity.Id = dto.NodeDto.NodeId; entity.Key = dto.NodeDto.UniqueId; entity.Alias = dto.Alias; entity.Name = dto.NodeDto.Text; entity.Icon = dto.Icon; entity.Thumbnail = dto.Thumbnail; entity.SortOrder = dto.NodeDto.SortOrder; entity.Description = dto.Description; entity.CreateDate = dto.NodeDto.CreateDate; entity.Path = dto.NodeDto.Path; entity.Level = dto.NodeDto.Level; entity.CreatorId = dto.NodeDto.UserId.Value; entity.AllowedAsRoot = dto.AllowAtRoot; entity.IsContainer = dto.IsContainer; entity.Trashed = dto.NodeDto.Trashed; } public ContentTypeDto BuildContentTypeDto(IContentTypeBase entity) { Guid nodeObjectType; if (entity is IContentType) nodeObjectType = Constants.ObjectTypes.DocumentTypeGuid; else if (entity is IMediaType) nodeObjectType = Constants.ObjectTypes.MediaTypeGuid; else if (entity is IMemberType) nodeObjectType = Constants.ObjectTypes.MemberTypeGuid; else throw new Exception("Invalid entity."); var contentTypeDto = new ContentTypeDto { Alias = entity.Alias, Description = entity.Description, Icon = entity.Icon, Thumbnail = entity.Thumbnail, NodeId = entity.Id, AllowAtRoot = entity.AllowedAsRoot, IsContainer = entity.IsContainer, NodeDto = BuildNodeDto(entity, nodeObjectType) }; return contentTypeDto; } private static NodeDto BuildNodeDto(IUmbracoEntity entity, Guid nodeObjectType) { var nodeDto = new NodeDto { CreateDate = entity.CreateDate, NodeId = entity.Id, Level = short.Parse(entity.Level.ToString(CultureInfo.InvariantCulture)), NodeObjectType = nodeObjectType, ParentId = entity.ParentId, Path = entity.Path, SortOrder = entity.SortOrder, Text = entity.Name, Trashed = false, UniqueId = entity.Key, UserId = entity.CreatorId }; return nodeDto; } #endregion } }
# (c) Copyright 2018 ZTE Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import falcon from unittest import mock from freezer_api.api.v2 import clients as v2_clients from freezer_api.common import exceptions from freezer_api.tests.unit import common class TestClientsCollectionResource(common.FreezerBaseTestCase): def setUp(self): super(TestClientsCollectionResource, self).setUp() self.mock_db = mock.Mock() self.mock_req = mock.MagicMock() self.mock_req.env.__getitem__.side_effect = common.get_req_items self.mock_req.get_header.return_value = common.fake_data_0_user_id self.mock_req.status = falcon.HTTP_200 self.resource = v2_clients.ClientsCollectionResource(self.mock_db) self.mock_json_body = mock.Mock() self.mock_json_body.return_value = {} self.resource.json_body = self.mock_json_body def test_on_get_return_empty_list(self): self.mock_db.get_client.return_value = [] expected_result = {'clients': []} self.resource.on_get(self.mock_req, self.mock_req, common.fake_client_info_0['project_id']) result = self.mock_req.body self.assertEqual(expected_result, result) self.assertEqual(falcon.HTTP_200, self.mock_req.status) def test_on_get_return_correct_list(self): self.mock_db.get_client.return_value = [common.fake_client_entry_0, common.fake_client_entry_1] expected_result = {'clients': [common.fake_client_entry_0, common.fake_client_entry_1]} self.resource.on_get(self.mock_req, self.mock_req, common.fake_client_info_0['project_id']) result = self.mock_req.body self.assertEqual(expected_result, result) self.assertEqual(falcon.HTTP_200, self.mock_req.status) def test_on_post_raises_when_missing_body(self): self.mock_db.add_client.return_value = common.fake_client_info_0[ 'client_id'] self.assertRaises(exceptions.BadDataFormat, self.resource.on_post, self.mock_req, self.mock_req, common.fake_client_info_0['project_id']) def test_on_post_inserts_correct_data(self): self.mock_json_body.return_value = common.fake_client_info_0 self.mock_db.add_client.return_value = common.fake_client_info_0[ 'client_id'] expected_result = {'client_id': common.fake_client_info_0['client_id']} self.resource.on_post(self.mock_req, self.mock_req, common.fake_client_info_0['project_id']) self.assertEqual(falcon.HTTP_201, self.mock_req.status) self.assertEqual(expected_result, self.mock_req.body) class TestClientsResource(common.FreezerBaseTestCase): def setUp(self): super(TestClientsResource, self).setUp() self.mock_db = mock.Mock() self.mock_req = mock.MagicMock() self.mock_req.env.__getitem__.side_effect = common.get_req_items self.mock_req.get_header.return_value = common.fake_data_0_user_id self.mock_req.status = falcon.HTTP_200 self.resource = v2_clients.ClientsResource(self.mock_db) self.mock_json_body = mock.Mock() self.mock_json_body.return_value = {} self.resource.json_body = self.mock_json_body def test_create_resource(self): self.assertIsInstance(self.resource, v2_clients.ClientsResource) def test_on_get_return_no_result_and_404_when_not_found(self): self.mock_db.get_client.return_value = [] self.mock_req.body = None self.resource.on_get(self.mock_req, self.mock_req, common.fake_client_info_0['project_id'], common.fake_client_info_0['client_id']) self.assertIsNone(self.mock_req.body) self.assertEqual(falcon.HTTP_404, self.mock_req.status) def test_on_get_return_correct_data(self): self.mock_db.get_client.return_value = [common.fake_client_entry_0] expected_result = common.fake_client_entry_0 self.resource.on_get(self.mock_req, self.mock_req, common.fake_client_info_0['project_id'], common.fake_client_info_0['client_id']) result = self.mock_req.body self.assertEqual(expected_result, result) self.assertEqual(falcon.HTTP_200, self.mock_req.status) def test_on_delete_removes_proper_data(self): self.resource.on_delete(self.mock_req, self.mock_req, common.fake_client_info_0['project_id'], common.fake_client_info_0['client_id']) result = self.mock_req.body expected_result = {'client_id': common.fake_client_info_0['client_id']} self.assertEqual(falcon.HTTP_204, self.mock_req.status) self.assertEqual(expected_result, result)
/* APPLE LOCAL file radar 6083129 byref escapes */ /* { dg-do run { target *-*-darwin[1-2][0-9]* } } */ /* { dg-options "-fblocks" } */ /* { dg-skip-if "" { powerpc*-*-darwin* } { "-m64" } { "" } } */ #include <stdio.h> extern "C" void abort(void); static int count; static void _Block_object_dispose(void * arg, int flag) { printf ("%p\n", arg); ++count; } int main() { { __block int O1; int i; int p; for (i = 1; i <= 5; i++) { __block int I1; p = 0; while (p != 10) { __block int II1; if (p == 2) break; ++p; } } } return count-21; }
import { Injectable, EventEmitter } from "@angular/core"; import { Http } from "@angular/http"; import { $WebSocket, WebSocketConfig } from "angular2-websocket/angular2-websocket"; import { JsonConvert, OperationMode, ValueCheckingMode, JsonObject, JsonProperty, Any, JsonCustomConvert, JsonConverter } from "json2typescript"; export const OPEN = "open"; export const CLOSE = "close"; export const MESSAGE = "message"; @Injectable() export class SocketService { private url: string; private socket: $WebSocket; private listener: EventEmitter<any>; private http: Http; private webSocketConfig: WebSocketConfig = { initialTimeout: 100, maxTimeout: 500, reconnectIfNotNormalClose: true }; public screenoff: boolean; public constructor() { this.url = "ws://" + location.hostname + ":8888/websocket"; this.socket = new $WebSocket(this.url, null, this.webSocketConfig); this.listener = new EventEmitter(); this.screenoff = false; const jsonConvert = new JsonConvert(); jsonConvert.ignorePrimitiveChecks = false; this.socket.onMessage( msg => { if (msg.data.includes("keepalive")) { // TODO send a pong back } else if (msg.data.includes("refresh")) { console.log("refreshing!"); location.assign("http://" + location.hostname + ":8888/"); } else if (msg.data.includes("screenoff")) { console.log("adding screenoff element"); this.screenoff = true; } else if (msg.data.includes("websocketTest")) { console.log("socket test"); } else { const data = JSON.parse(msg.data); const event = jsonConvert.deserialize(data, Event); console.debug("received event", event); this.listener.emit({ type: MESSAGE, data: event }); } }, { autoApply: false } ); this.socket.onOpen(msg => { console.log("Websocket opened with", this.url, ":", msg); this.listener.emit({ type: OPEN }); }); this.socket.onError(msg => { console.log("websocket closed.", msg); this.listener.emit({ type: CLOSE }); }); this.socket.onClose(msg => { console.log("trying again", msg); }); } public close() { this.socket.close(false); } public getEventListener() { return this.listener; } } @JsonObject("BasicRoomInfo") export class BasicRoomInfo { @JsonProperty("buildingID", String, true) BuildingID = ""; @JsonProperty("roomID", String, true) RoomID = ""; constructor(roomID: string) { if (roomID == null || roomID === undefined) { return; } const split = roomID.split("-"); if (split.length === 2) { this.BuildingID = split[0]; this.RoomID = split[0] + "-" + split[1]; } } } @JsonObject("BasicDeviceInfo") export class BasicDeviceInfo { @JsonProperty("buildingID", String, true) BuildingID = ""; @JsonProperty("roomID", String, true) RoomID = ""; @JsonProperty("deviceID", String, true) DeviceID = ""; constructor(deviceID: string) { if (deviceID == null || deviceID === undefined) { return; } const split = deviceID.split("-"); if (split.length === 3) { this.BuildingID = split[0]; this.RoomID = split[0] + "-" + split[1]; this.DeviceID = split[0] + "-" + split[1] + "-" + split[2]; } } } @JsonConverter class DateConverter implements JsonCustomConvert<Date> { serialize(date: Date): any { function pad(n) { return n < 10 ? "0" + n : n; } return ( date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + "Z" ); } deserialize(date: any): Date { return new Date(date); } } @JsonObject("Event") export class Event { @JsonProperty("generating-system", String, true) GeneratingSystem = ""; @JsonProperty("timestamp", DateConverter, true) Timestamp: Date = undefined; @JsonProperty("event-tags", [String], true) EventTags: string[] = []; @JsonProperty("target-device", BasicDeviceInfo, true) TargetDevice = new BasicDeviceInfo(undefined); @JsonProperty("affected-room", BasicRoomInfo) AffectedRoom = new BasicRoomInfo(undefined); @JsonProperty("key", String, true) Key = ""; @JsonProperty("value", String, true) Value = ""; @JsonProperty("user", String, true) User = ""; @JsonProperty("data", Any, true) Data: any = undefined; public hasTag(tag: string): boolean { return this.EventTags.includes(tag); } }
import numpy as np import unittest from nose.tools import set_trace from pic3d3v import * from solvers import * from landau import * norm = lambda x: np.max(np.abs(x)) class TestShortRangeCalc(unittest.TestCase): tol = 10e-10 def test_short_range_N_cells(self): """Compare single cell to many cell sr calcs Only checking default screen. This is only to check the short range logic, not the correctness of the screen functions. """ np.random.seed(9999) screen = GaussianScreen N = 16**3 Lz = Ly = Lx = np.pi xp = np.random.rand(N).astype(np.double)*Lx yp = np.random.rand(N).astype(np.double)*Ly zp = np.random.rand(N).astype(np.double)*Lz normalize(zp, Lz) normalize(yp, Ly) normalize(xp, Lx) q = np.ones_like(zp, dtype=np.double) rmax = .2 beta = 5. particles = Species(N, 1., 1., x0=xp, y0=yp, z0=zp) pic = PIC3DP3M([particles], (Lz,Ly,Lx), (32,32,32)) pic.init_run(.1, beta=beta, rmax=rmax) pic.sort_by_cells() zp=pic.zp; yp=pic.yp; xp=pic.xp q=pic.q cell_span = pic.cell_span N_cells = pic.N_cells # Using only one cell Ezp1 = np.zeros(N, dtype=np.double) Eyp1 = np.zeros(N, dtype=np.double) Exp1 = np.zeros(N, dtype=np.double) screen.calc_E_short_range(Ezp1, zp, Lz, Eyp1, yp, Ly, Exp1, xp, Lx, q, 1, cell_span, rmax, beta) # Using the default number of cells Ezp2 = np.zeros(N, dtype=np.double) Eyp2 = np.zeros(N, dtype=np.double) Exp2 = np.zeros(N, dtype=np.double) screen.calc_E_short_range(Ezp2, zp, Lz, Eyp2, yp, Ly, Exp2, xp, Lx, q, N_cells, cell_span, rmax, beta) self.assertTrue(norm(Ezp1-Ezp2)<self.tol) self.assertTrue(norm(Eyp1-Eyp2)<self.tol) self.assertTrue(norm(Exp1-Exp2)<self.tol)
from __future__ import division # confidence high from __future__ import with_statement import numpy as np import pyfits as fits from warnings import catch_warnings from . import PyfitsTestCase class TestDivisionFunctions(PyfitsTestCase): """Test code units that rely on correct integer division.""" def test_rec_from_string(self): t1 = fits.open(self.data('tb.fits')) s = t1[1].data.tostring() a1 = np.rec.array( s, dtype=np.dtype([('c1', '>i4'), ('c2', '|S3'), ('c3', '>f4'), ('c4', '|i1')])) def test_card_with_continue(self): h = fits.PrimaryHDU() with catch_warnings(record=True) as w: h.header['abc'] = 'abcdefg' * 20 assert len(w) == 0 def test_valid_hdu_size(self): t1 = fits.open(self.data('tb.fits')) assert type(t1[1].size) == type(1) def test_hdu_get_size(self): with catch_warnings(record=True) as w: t1 = fits.open(self.data('tb.fits')) assert len(w) == 0 def test_section(self): # section testing fs = fits.open(self.data('arange.fits')) with catch_warnings(record=True) as w: assert np.all(fs[0].section[3, 2, 5] == np.array([357])) assert len(w) == 0
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace Org.Apache.REEF.Common.Catalog.Capabilities { public interface ICapability { } }
#Embedded file name: /usr/lib/enigma2/python/Blackhole/BhInterface.py from Screens.Screen import Screen from Screens.Standby import Standby, TryQuitMainloop from Components.Label import Label from Components.config import config, ConfigBoolean import socket from Tools.Directories import fileExists from urllib2 import Request, urlopen, URLError, HTTPError from random import randint from enigma import eEPGCache, eDVBDB from os import system config.misc.deliteepgpop = ConfigBoolean(default=True) class DeliteInterface: def __init__(self): self.session = None def setSession(self, session): self.session = session self.pop = self.session.instantiateDialog(Nab_debOut) def procCmd(self, cmd): if cmd is not None: if self.session: if cmd.find('extepg') == 0: self.downloadExtEpg(cmd) elif cmd.find('reloadsettings') == 0: self.reloadSettings() elif cmd.find('standby') == 0: self.session.open(Standby) elif cmd.find('shutdown') == 0: self.session.open(TryQuitMainloop, 1) elif cmd.find('reboot') == 0: self.session.open(TryQuitMainloop, 2) elif cmd.find('restartenigma2') == 0: self.session.open(TryQuitMainloop, 3) elif cmd.find('re2') == 0: self.session.open(TryQuitMainloop, 3) elif cmd.find('restartemu') == 0: mydata = 'START_CAMD' client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) client_socket.connect('/tmp/Blackhole.socket') client_socket.send(mydata) client_socket.close() elif cmd.find('popshow') == 0: if config.misc.deliteepgpop.value: self.pop.show() self.pop.setmyText(cmd[8:]) self.pop.mystate = 1 elif cmd.find('popsettext') == 0: if config.misc.deliteepgpop.value: self.pop.setmyText(cmd[11:]) elif cmd.find('popclose') == 0: if self.pop.mystate == 1: self.pop.hide() def reloadSettings(self): settings = eDVBDB.getInstance() settings.reloadServicelist() settings.reloadBouquets() def downloadExtEpg(self, cmd): parts = cmd.split(',') myurl = parts[2] myext = '.gz' if myurl.find('.dat.bz2') != -1: myext = '.bz2' myepgpath = config.misc.epgcache_filename.value myepgfile = myepgpath + myext randurl = self.selecturL() myurl0 = myurl.replace('http://www.vuplus-community.net/rytec', randurl) online = self.checkOnLine(myurl0) if online == True: myurl = myurl0 try: filein = urlopen(myurl) except HTTPError as e: pass except URLError as e: pass else: fileout = open(myepgfile, 'wb') while True: bytes = filein.read(1024000) fileout.write(bytes) if bytes == '': break filein.close() fileout.close() if fileExists(myepgfile): cmd = 'gunzip -f ' + myepgfile if myext == '.bz2': cmd = 'bunzip2 -f ' + myepgfile rc = system(cmd) epgcache = eEPGCache.getInstance() epgcache.load() epgcache.save() def checkOnLine(self, url): try: filein = urlopen(url, timeout=1) except URLError as e: online = False except HTTPError as e: online = False else: filein.close() online = True return online def selecturL(self): url = 'http://www.xmltvepg.nl' nm = randint(1, 3) if nm == 2: url = 'http://www.xmltvepg.be' elif nm == 3: url = 'http://enigma2.world-of-satellite.com/epg_data' return url class Nab_debOut(Screen): skin = '\n\t<screen position="380,150" size="520,240" title="Black Hole Message">\n\t\t<widget name="outlabel" position="10,10" size="500,230" font="Regular;20" halign="center" valign="center" transparent="1"/>\n\t</screen>' def __init__(self, session): Screen.__init__(self, session) self['outlabel'] = Label('') self.mystate = 0 def setmyText(self, myt): self['outlabel'].setText(myt) def MyClose(self): self.close()
# Copyright (c) 2016-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest from caffe2.python import workspace, brew, model_helper from caffe2.python.modeling.compute_statistics_for_blobs import ( ComputeStatisticsForBlobs ) import numpy as np class ComputeStatisticsForBlobsTest(unittest.TestCase): def test_compute_statistics_for_blobs(self): model = model_helper.ModelHelper(name="test") data = model.net.AddExternalInput("data") fc1 = brew.fc(model, data, "fc1", dim_in=4, dim_out=2) # no operator name set, will use default brew.fc(model, fc1, "fc2", dim_in=2, dim_out=1) net_modifier = ComputeStatisticsForBlobs( blobs=['fc1_w', 'fc2_w'], logging_frequency=10, ) net_modifier(model.net) workspace.FeedBlob('data', np.random.rand(10, 4).astype(np.float32)) workspace.RunNetOnce(model.param_init_net) workspace.RunNetOnce(model.net) fc1_w = workspace.FetchBlob('fc1_w') fc1_w_summary = workspace.FetchBlob('fc1_w_summary') # std is unbiased here stats_ref = np.array([fc1_w.flatten().min(), fc1_w.flatten().max(), fc1_w.flatten().mean(), fc1_w.flatten().std(ddof=1)]) self.assertAlmostEqual(np.linalg.norm(stats_ref - fc1_w_summary), 0, delta=1e-5) self.assertEqual(fc1_w_summary.size, 4) self.assertEqual(len(model.net.Proto().op), 8) assert 'fc1_w' + net_modifier.field_name_suffix() in\ model.net.output_record().field_blobs() assert 'fc2_w' + net_modifier.field_name_suffix() in\ model.net.output_record().field_blobs()
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/mini_installer_test/switch_builder.h" #include "chrome/installer/util/install_util.h" namespace installer_test { SwitchBuilder::SwitchBuilder() : switches_(CommandLine::NO_PROGRAM) {} SwitchBuilder::~SwitchBuilder() {} const CommandLine& SwitchBuilder::GetSwitches() const { return switches_; } SwitchBuilder& SwitchBuilder::AddChrome() { switches_.AppendSwitch(installer::switches::kChrome); return *this; } SwitchBuilder& SwitchBuilder::AddChromeFrame() { switches_.AppendSwitch(installer::switches::kChromeFrame); switches_.AppendSwitch(installer::switches::kDoNotLaunchChrome); switches_.AppendSwitch(installer::switches::kDoNotRegisterForUpdateLaunch); return *this; } SwitchBuilder& SwitchBuilder::AddMultiInstall() { switches_.AppendSwitch(installer::switches::kMultiInstall); return *this; } SwitchBuilder& SwitchBuilder::AddSystemInstall() { switches_.AppendSwitch(installer::switches::kSystemLevel); return *this; } } // namespace