text
stringlengths
2
6.14k
#!/usr/bin/python loop_count = 0 # r0 = [ 5, 0, 9, 8, 1, 2, 7, 0, 0 ] r0 = [ 0, 0, 9, 8, 0, 0, 0, 0, 0 ] # r1 = [ 0, 0, 0, 9, 0, 6, 2, 5, 1 ] r1 = [ 0, 0, 0, 0, 0, 0, 2, 5, 1 ] # r2 = [ 0, 0, 2, 0, 3, 0, 0, 6, 0 ] r2 = [ 0, 0, 2, 0, 3, 0, 0, 6, 0 ] # r3 = [ 0, 0, 0, 0, 0, 5, 0, 7, 0 ] r3 = [ 0, 0, 0, 0, 0, 5, 0, 7, 0 ] # r4 = [ 8, 7, 6, 0, 2, 0, 5, 4, 9 ] r4 = [ 0, 0, 6, 0, 2, 0, 0, 4, 9 ] # r5 = [ 0, 4, 0, 7, 0, 0, 0, 0, 0 ] r5 = [ 0, 4, 0, 0, 0, 0, 0, 0, 0 ] # r6 = [ 0, 5, 0, 0, 9, 0, 8, 0, 0 ] r6 = [ 0, 5, 0, 0, 9, 0, 8, 0, 0 ] # r7 = [ 7, 9, 8, 1, 0, 4, 0, 0, 0 ] r7 = [ 7, 0, 8, 0, 0, 0, 0, 0, 0 ] # r8 = [ 0, 0, 1, 2, 7, 8, 4, 0, 5 ] r8 = [ 0, 0, 1, 2, 0, 0, 4, 0, 5 ] g0 = [ r0, r1, r2, r3, r4, r5, r6, r7, r8 ] def print_grid(grid): for x in xrange(9): line = '' for y in xrange(9): line += ' %d' % grid[x][y] print "%s" % line def check_grid_solved(grid): for x in xrange(9): row = {} col = {} for y in xrange(9): rcell = grid[x][y] if rcell in row: return False row[rcell] = 1 ccell = grid[y][x] if ccell in col: return False col[ccell] = 1 for x in xrange(1, 10): if x in row: pass else: return False if x in col: pass else: return False for x1 in xrange(0, 9, 3): for y1 in xrange(0, 9, 3): # print "%d %d" % (x1, y1) sgrid = {} for x2 in xrange(3): line = '' for y2 in xrange(3): cell = grid[x1 + x2][y1 + y2] line += " %d" % cell if cell in sgrid: return False sgrid[cell] = 1 # print line # print "subgrid is ok" for x in xrange(1, 10): if x in sgrid: pass else: return False return True def old_check_grid_solved(grid): for x in xrange(9): row = {} col = {} for y in xrange(9): rcell = grid[x][y] if rcell in row: return False row[rcell] = 1 ccell = grid[y][x] if ccell in col: return False col[ccell] = 1 for x1 in xrange(0, 9, 3): for y1 in xrange(0, 9, 3): # print "%d %d" % (x1, y1) sgrid = {} for x2 in xrange(3): line = '' for y2 in xrange(3): cell = grid[x1 + x2][y1 + y2] line += " %d" % cell if cell in sgrid: return False sgrid[cell] = 1 # print line # print "subgrid is ok" return True def check_grid_consistent(grid): for x in xrange(9): row = {} col = {} for y in xrange(9): rcell = grid[x][y] if rcell != 0 and rcell in row: return False row[rcell] = 1 ccell = grid[y][x] if ccell != 0 and ccell in col: return False col[ccell] = 1 for x1 in xrange(0, 9, 3): for y1 in xrange(0, 9, 3): # print "%d %d" % (x1, y1) sgrid = {} for x2 in xrange(3): line = '' for y2 in xrange(3): cell = grid[x1 + x2][y1 + y2] line += " %d" % cell if cell != 0 and cell in sgrid: return False sgrid[cell] = 1 # print line # print "subgrid is ok" return True def check_available(grid, x, y): # print # print "checking %d %d" % (x, y) used = {} for y1 in xrange(9): cell = grid[x][y1] used[cell] = 1 # print " found %d at %d %d" % (cell, x, y1) for x1 in xrange(9): cell = grid[x1][y] used[cell] = 1 # print " found %d at %d %d" % (cell, x1, y) x1 = x - (x % 3) y1 = y - (y % 3) # print "checking %d %d in grid at %d %d" % (x, y, x1, y1) for x2 in xrange(x1, x1 + 3): for y2 in xrange(y1, y1 + 3): cell = grid[x2][y2] used[cell] = 1 # print " found %d at %d %d" % (cell, x2, y2) # print " used = %s" % str(used) available = [] for a1 in xrange(1, 10): if a1 in used: # print " %d is used" % a1 pass else: available.append(a1) # print "%s, %s available: %s" % (str(x), str(y), str(available)) return available def solve_grid(grid): global loop_count loop_count += 1 print "%d" % loop_count for x in xrange(9): for y in xrange(9): cell = grid[x][y] # check_available(grid, x, y) if cell == 0: a1 = check_available(grid, x, y) if len(a1) == 1: c = a1[0] grid[x][y] = c print "found %d for %d %d" % (c, x, y) if check_grid_solved(grid): return print_grid(g0) solve_grid(grid) def main(): print_grid(g0) solve_grid(g0) print_grid(g0) main()
package cn.jsprun.vo.otherset; import java.text.SimpleDateFormat; import cn.jsprun.utils.Common; public class Advertisement { private String id = null; private boolean userable = false; private String displayorder = null; private String title = null; private String type = null; private String style = null; private int starttime = 0; private int endtime = 0; private String targets = null; private boolean overdue = false; private SimpleDateFormat simpleDateFormat = null; public Advertisement() {} public Advertisement(SimpleDateFormat simpleDateFormat){ this.simpleDateFormat = simpleDateFormat; } public boolean isOverdue() { return overdue; } public void setOverdue(boolean overdue) { this.overdue = overdue; } public String getId() { return id; } public void setId(String id) { this.id = id; } public boolean isUserable() { return userable; } public void setUserable(boolean userable) { this.userable = userable; } public String getDisplayorder() { return displayorder; } public void setDisplayorder(String displayorder) { this.displayorder = displayorder; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getType() { if(null==type){ return ""; }else if(type.equals("headerbanner")){ return "a_other_adv_type_headerbanner"; }else if(type.equals("footerbanner")){ return "a_other_adv_type_footerbanner"; }else if(type.equals("text")){ return "a_other_adv_type_text"; }else if(type.equals("thread")){ return "a_other_adv_type_thread"; }else if(type.equals("interthread")){ return "a_other_adv_type_interthread"; }else if(type.equals("float")){ return "a_other_adv_type_float"; }else if(type.equals("couplebanner")){ return "a_other_adv_type_couplebanner"; }else if(type.equals("intercat")){ return "a_other_adv_type_intercat"; }else{ return ""; } } public void setType(String type) { this.type = type; } public String getStarttime() { return Common.gmdate(simpleDateFormat, starttime); } public void setStarttime(int starttime) { this.starttime = starttime; } public boolean getEndtimeExist(){ return endtime!=0; } public String getEndtime() { return endtime==0?"":Common.gmdate(simpleDateFormat, endtime); } public void setEndtime(int endtime) { this.endtime = endtime; } public String getTargets() { return targets; } public void setTargets(String targets) { this.targets = targets; } public String getStyle() { if(style.equals("text")){ return "a_other_adv_style_text"; }else if(style.equals("code")){ return "a_other_adv_style_code"; }else if(style.equals("flash")){ return "a_other_adv_style_flash"; }else if(style.equals("image")){ return "a_post_smilies_edit_image"; }else{ return ""; } } public void setStyle(String style) { this.style = style; } }
import os from django.utils.translation import ugettext_lazy as _ from openstack_dashboard import exceptions {%- from "horizon/map.jinja" import server with context %} {%- if server.app is defined %} {%- set app = salt['pillar.get']('horizon:server:app:'+app_name) %} {%- else %} {%- set app = salt['pillar.get']('horizon:server') %} {%- endif %} # OpenStack Dashboard configuration. HORIZON_CONFIG = { 'dashboards': ({% if app.plugin is defined %}{% for plugin_name, plugin in app.plugin.iteritems() %}{% if plugin.get('dashboard', False) %}'{{ plugin_name }}', {% endif %}{% endfor %}{% endif %}'admin', 'settings'), 'default_dashboard': '{{ app.get('default_dashboard', 'project') }}', 'user_home': 'helpdesk_dashboard.views.splash', 'ajax_queue_limit': 10, 'auto_fade_alerts': { 'delay': 3000, 'fade_duration': 1500, 'types': ['alert-success', 'alert-info'] }, 'help_url': "{{ app.get('help_url', 'http://docs.openstack.org') }}", 'exceptions': {'recoverable': exceptions.RECOVERABLE, 'not_found': exceptions.NOT_FOUND, 'unauthorized': exceptions.UNAUTHORIZED}, 'password_autocomplete': 'on' } SESSION_TIMEOUT = 3600 * 24 {%- if app.theme is defined or app.plugin.horizon_theme is defined %} {%- if app.theme is defined %} CUSTOM_THEME_PATH = 'dashboards/theme/static/themes/{{ app.theme }}' {%- elif app.plugin.horizon_theme.theme_name is defined %} # Enable custom theme if it is present. try: from openstack_dashboard.enabled._99_horizon_theme import CUSTOM_THEME_PATH except ImportError: pass {%- endif %} {%- endif %} INSTALLED_APPS = ( 'openstack_dashboard', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'compressor', 'horizon', {%- if app.logging is defined %} 'raven.contrib.django.raven_compat', {%- endif %} ) REDACTOR_OPTIONS = {'lang': 'en', 'buttonsHide': ['file', 'image']} REDACTOR_UPLOAD = 'uploads/' ROOT_URLCONF = 'helpdesk_dashboard.url_overrides' {% include "horizon/files/horizon_settings/_keystone_settings.py" %} {% include "horizon/files/horizon_settings/_local_settings.py" %} AUTHENTICATION_BACKENDS = ('helpdesk_auth.backend.HelpdeskBackend',) AUTHENTICATION_URLS = ['helpdesk_auth.urls'] API_RESULT_PAGE_SIZE = 25 {% include "horizon/files/horizon_settings/_horizon_settings.py" %}
import ctypes import functools import windows.generated_def as gdef from .error import ExportNotFound from windows.pycompat import is_py3 # Utils def is_implemented(apiproxy): """Return :obj:`True` if DLL/Api can be found""" try: apiproxy.force_resolution() except ExportNotFound: return False return True def get_target(apiproxy): """POC for newshook""" return apiproxy.target_dll, apiproxy.target_func def resolve(apiproxy): """Resolve the address of ``apiproxy``. Might raise if ``apiproxy`` is not implemented""" apiproxy.force_resolution() func = ctypes.WinDLL(apiproxy.target_dll)[apiproxy.target_func] return ctypes.cast(func, gdef.PVOID).value class NeededParameterType(object): _inst = None def __new__(cls): if cls._inst is None: cls._inst = super(NeededParameterType, cls).__new__(cls) return cls._inst def __repr__(self): return "NeededParameter" NeededParameter = NeededParameterType() sentinel = object() class ApiProxy(object): APIDLL = None """Create a python wrapper around a kernel32 function""" def __init__(self, func_name=None, error_check=sentinel, deffunc_module=None): self.deffunc_module = deffunc_module if deffunc_module is not None else gdef.winfuncs self.func_name = func_name if error_check is sentinel: error_check = self.default_error_check self.error_check = error_check self._cprototyped = None def __call__(self, python_proxy): # Use the name of the sub-function if None was given if self.func_name is None: self.func_name = python_proxy.__name__ errchk = None if self.error_check is not None: errchk = functools.wraps(self.error_check)(functools.partial(self.error_check, self.func_name)) prototype = getattr(self.deffunc_module, self.func_name + "Prototype") params = getattr(self.deffunc_module, self.func_name + "Params") python_proxy.prototype = prototype python_proxy.params = params python_proxy.errcheck = errchk python_proxy.target_dll = self.APIDLL python_proxy.target_func = self.func_name # Give access to the 'ApiProxy' object from the function python_proxy.proxy = self params_name = [param[1] for param in params] if (self.error_check.__doc__): doc = python_proxy.__doc__ doc = doc if doc else "" python_proxy.__doc__ = doc + "\nErrcheck:\n " + self.error_check.__doc__ def generate_ctypes_function(): try: api_dll = ctypes.windll[self.APIDLL] except WindowsError as e: if e.winerror == gdef.ERROR_BAD_EXE_FORMAT: e.strerror = e.strerror.replace("%1", "<{0}>".format(self.APIDLL)) raise try: c_prototyped = prototype((self.func_name, api_dll), params) except (AttributeError, WindowsError): raise ExportNotFound(self.func_name, self.APIDLL) if errchk is not None: c_prototyped.errcheck = errchk self._cprototyped = c_prototyped def perform_call(*args): if self._cprototyped is None: generate_ctypes_function() try: return self._cprototyped(*args) except ctypes.ArgumentError as e: # We just add a conversion ctypes argument fail # We can do some heavy computation if needed # Not a case that normally happen # "argument 2: <type 'exceptions.TypeError'>: wrong type" # Thx ctypes.. argnbstr, ecx, reason = e.args[0].split(":") # py2 / py3 compat :) if not argnbstr.startswith("argument "): raise # Don't knnow if it can happen argnb = int(argnbstr[len("argument "):]) badarg = args[argnb - 1] if badarg is NeededParameter: badargname = params_name[argnb - 1] raise TypeError("{0}: Missing Mandatory parameter <{1}>".format(self.func_name, badargname)) # Not NeededParameter: the caller need to fix the used param :) # raise the real ctypes error raise setattr(python_proxy, "ctypes_function", perform_call) setattr(python_proxy, "force_resolution", generate_ctypes_function) return python_proxy
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta property="og:url" content="http://www.your-domain.com/your-page.html" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Your Website Title" /> <meta property="og:description" content="Your description" /> <meta property="og:image" content="http://www.your-domain.com/path/image.jpg" /> <link rel="stylesheet" href="Estilos.css"> <style> /* body { background-color: blue; color: #fffdde; } h1 { background-color: red; color: #b3a290; } h3 { background-color: yellow; color: black; } div { background-color: black; color: white; } */ /* h1 { background-color: red; color: lightblue; } #uno { background-color: yellow; color: black; } button { background-color: #1fd0ff; color: #ce381c; } #cancelar { background-color: #ce381c; color: #1fd0ff; } */ </style> </head> <body> <div>Holi</div> <h1>Hola mundo</h1> <button class="boton-cuidado"> Destruir Mundo </button> <button class="boton-exito"> Crear Mundo </button> <h1>Universo</h1> <button id="idmalicioso" style="color: yellow;background-color: blue"; class="boton-cuidado"> Destruir Universo </button> <button id="idmalicioso1" class="boton-exito"> Crear Universo </button> <button>Oli</button> <!-- <div> <h1 id="uno">Primer h1</h1> <h1>Segundo h1</h1> <h1>Tercer h1</h1> <button>Aceptar</button> <button id="cancelar">Cancelar</button> </div> --> <!-- <div> <h1>Primer H1</h1> <div> <h1>Segundo H1</h1> <h2>H2</h2> </div> <div> <h1>Tercer H1</h1> <h3>H3</h3> <h4>H4</h4> </div> <h1>Cuarto H1</h1> <h1>H1 <div>OTRO DIV</div> <p>Parrafo</p> </h1> </div> --> <a aria-pressed="true" class="UFILikeLink _4x9- _4x9_ _48-k" data-testid="fb-ufi-likelink" href="#" role="button" tabindex="-1">Me gusta </a> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!-- Your like button code --> <div class="fb-like" data-href="http://www.your-domain.com/your-page.html" data-layout="standard" data-action="like" data-show-faces="true"> </div> </body> </html>
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <ABI41_0_0React/components/view/ConcreteViewShadowNode.h> #include <ABI41_0_0React/components/view/ViewProps.h> namespace ABI41_0_0facebook { namespace ABI41_0_0React { extern const char ViewComponentName[]; /* * `ShadowNode` for <View> component. */ class ViewShadowNode final : public ConcreteViewShadowNode< ViewComponentName, ViewProps, ViewEventEmitter> { public: ViewShadowNode( ShadowNodeFragment const &fragment, ShadowNodeFamily::Shared const &family, ShadowNodeTraits traits); ViewShadowNode( ShadowNode const &sourceShadowNode, ShadowNodeFragment const &fragment); private: void initialize() noexcept; }; } // namespace ABI41_0_0React } // namespace ABI41_0_0facebook
// File generated from our OpenAPI spec package com.stripe.param.issuing; import com.google.gson.annotations.SerializedName; import com.stripe.net.ApiRequestParams; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; @Getter public class DisputeRetrieveParams extends ApiRequestParams { /** Specifies which fields in the response should be expanded. */ @SerializedName("expand") List<String> expand; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; private DisputeRetrieveParams(List<String> expand, Map<String, Object> extraParams) { this.expand = expand; this.extraParams = extraParams; } public static Builder builder() { return new Builder(); } public static class Builder { private List<String> expand; private Map<String, Object> extraParams; /** Finalize and obtain parameter instance from this builder. */ public DisputeRetrieveParams build() { return new DisputeRetrieveParams(this.expand, this.extraParams); } /** * Add an element to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * DisputeRetrieveParams#expand} for the field documentation. */ public Builder addExpand(String element) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.add(element); return this; } /** * Add all elements to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * DisputeRetrieveParams#expand} for the field documentation. */ public Builder addAllExpand(List<String> elements) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.addAll(elements); return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * DisputeRetrieveParams#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link DisputeRetrieveParams#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } } }
class Node(object): def __init__(self,data,next=None): self.data=data self.next=next class Singly(object): def __init__(self): self.head=None self.tail=None self.count=0 ## add new value to back def addBack(self,data): temp=self.tail newNode = Node(data) if self.tail==None: self.head=newNode self.tail=newNode return self temp.next=newNode self.tail=newNode ## add new value to front def addFront(self,data): temp=self.head newNode = Node(data) if self.head==None: self.head=newNode self.tail=newNode return self newNode.next=temp self.head=newNode ## insertBefore def insertBefore(self,nVal,val): if self.isEmpty(): self.addFront(val) elif self.head.data==nVal: temp=self.head while temp: if temp.data==nVal: run=temp.next newNode=Node(val,temp.next) temp.next=newNode temp=temp.next else: temp=self.head.next while temp: if temp.data==nVal: run=temp.next newNode=Node(val,temp.next) temp.next=newNode temp=temp.next ## insert after def insertAfter(self,pVal,val): if self.isEmpty(): self.addFront(val) print "fail" else: temp=self.head print "Closer" while temp: if temp.data==pVal: print "got here" newNode=Node(val,temp.next) temp.next=newNode temp=temp.next def printVal(self): temp=self.head while temp: print temp.data temp=temp.next def ReverseList(self): temp=self.tail while temp: print temp.data temp=temp.nex ## check if list is empty def isEmpty(self): if self.head ==None: return True def removeNode(self,val): temp=self.head.next if self.isEmpty(): print " This list is empty!" else: while temp: if temp.data==val: run=temp.next newNode=Node(val,temp.next) temp.next=newNode temp=temp.next A=Singly() A.addBack(9) A.addBack(8) A.addBack(7) A.addBack(6) A.addFront(5) A.addFront(4) A.addFront(3) A.addFront(2) A.printVal() A.insertBefore(5,10) A.printVal() A.insertAfter(2,11) A.printVal()
"""Test the NEW_NAME config flow.""" from homeassistant import config_entries, setup, data_entry_flow from homeassistant.components.NEW_DOMAIN.const import ( DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN, ) from homeassistant.helpers import config_entry_oauth2_flow CLIENT_ID = "1234" CLIENT_SECRET = "5678" async def test_full_flow(hass, aiohttp_client, aioclient_mock): """Check full flow.""" assert await setup.async_setup_component( hass, "NEW_DOMAIN", { "NEW_DOMAIN": { "type": "oauth2", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, }, "http": {"base_url": "https://example.com"}, }, ) result = await hass.config_entries.flow.async_init( "NEW_DOMAIN", context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]}) assert result["type"] == data_entry_flow.RESULT_TYPE_EXTERNAL_STEP assert result["url"] == ( f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}" "&redirect_uri=https://example.com/auth/external/callback" f"&state={state}" ) client = await aiohttp_client(hass.http.app) resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 assert resp.headers["content-type"] == "text/html; charset=utf-8" aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, }, ) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 entry = hass.config_entries.async_entries(DOMAIN)[0] assert entry.data["type"] == "oauth2"
<?php namespace EPFL\Menus\CLI; if (! defined( 'ABSPATH' )) { die( 'Access denied.' ); } use \WP_CLI; use \WP_CLI_Command; require_once(dirname(__DIR__) . '/lib/i18n.php'); use function EPFL\I18N\___; require_once(__DIR__ . '/epfl-menus.php'); use \EPFL\Menus\ExternalMenuItem; class EPFLMenusCLICommand extends WP_CLI_Command { public static function hook () { WP_CLI::add_command('epfl-menus', get_called_class()); } public function refresh () { WP_CLI::log(___('Enumerating menus on filesystem...')); $local = ExternalMenuItem::load_from_filesystem(); WP_CLI::log(sprintf(___('... Success, found %d local menus'), count($local))); WP_CLI::log(___('Enumerating menus in config file...')); $local = ExternalMenuItem::load_from_config_file(); WP_CLI::log(sprintf(___('... Success, found %d site-configured menus'), count($local))); $all = ExternalMenuItem::all(); WP_CLI::log(sprintf(___('Refreshing %d instances...'), count($all))); foreach ($all as $emi) { try { $emi->refresh(); WP_CLI::log(sprintf(___('✓ %s'), $emi)); } catch (\Throwable $t) { WP_CLI::log(sprintf(___('\u001b[31m✗ %s\u001b[0m'), $emi)); } } } /** * @example wp epfl-menus add_external_menu_item --menu-location-slug=top urn:epfl:labs "laboratoires" */ public function add_external_menu_item ($args, $assoc_args) { list($urn, $title) = $args; $menu_location_slug = $assoc_args['menu-location-slug']; if (!empty($menu_location_slug)) $menu_location_slug = "top"; # todo: check that params is format urn:epfl WP_CLI::log(___('Add a new external menu item...')); $external_menu_item = ExternalMenuItem::get_or_create($urn); $external_menu_item->set_title($title); $external_menu_item->meta()->set_remote_slug($menu_location_slug); $external_menu_item->meta()->set_items_json('[]'); WP_CLI::log(sprintf(___('External menu item ID %d...'),$external_menu_item->ID)); } } EPFLMenusCLICommand::hook();
# -*- coding:utf-8 -*- import os import re import Utils class Spider(object): imageDir = Utils.getHelloPythonDir() index = 0 def __init__(self): pass def downloadImage(self): imageDirMK = 'mkdir ' + Spider.imageDir print('---------------- begin ----------------') print(imageDirMK) os.system(imageDirMK) # 创建保存图片的目录 Utils.sleep(0.1) htmlUrl = "http://m.yaohu.info/meinv/8/1412.html" print('htmlUrl = ' + htmlUrl) htmlContent = Utils.getHtmlContent(htmlUrl) print('\n网页内容:') print(htmlContent) patternStr = r"(?<=data-original=\").+?(?=\">)" pattern = re.compile(patternStr) imageUrlArray = pattern.findall(htmlContent) print('\n解析到的图片列表:') print(imageUrlArray) for imageUrl in imageUrlArray: imageUrl = 'http:' + imageUrl imageName = ("image_%d.jpg" % Spider.index) print('') # Utils.saveImage2(imageUrl, Spider.imageDir, imageName) Utils.saveImage3(imageUrl, Spider.imageDir, imageName) Spider.index += 1 spider = Spider() spider.downloadImage()
#ifndef _CHRONOS_PACKETS_H_ #define _CHRONOS_PACKETS_H_ #include "chronos_config.h" #include "chronos_transactions.h" #include "chronos_cache.h" #include <stdlib.h> typedef struct chronosResponsePacket_t { chronosUserTransaction_t txn_type; int rc; } chronosResponsePacket_t; typedef struct chronosRequestPacket_t { chronosUserTransaction_t txn_type; /* A transaction can affect up to 100 symbols */ int numItems; union { chronosViewPortfolioInfo_t portfolioInfo[CHRONOS_MAX_DATA_ITEMS_PER_XACT]; chronosSymbol_t symbolInfo[CHRONOS_MAX_DATA_ITEMS_PER_XACT]; chronosPurchaseInfo_t purchaseInfo[CHRONOS_MAX_DATA_ITEMS_PER_XACT]; chronosSellInfo_t sellInfo[CHRONOS_MAX_DATA_ITEMS_PER_XACT]; } request_data; } chronosRequestPacket_t; typedef void *chronosRequest; typedef void *chronosResponse; chronosRequest chronosRequestCreate(chronosUserTransaction_t txnType, chronosClientCache clientCacheH, chronosCache chronosCacheH); int chronosRequestFree(chronosRequest requestH); chronosUserTransaction_t chronosRequestTypeGet(chronosRequest requestH); size_t chronosRequestSizeGet(chronosRequest requestH); chronosResponse chronosResponseAlloc(); int chronosResponseFree(chronosResponse responseH); size_t chronosResponseSizeGet(chronosRequest requestH); chronosUserTransaction_t chronosResponseTypeGet(chronosResponse responseH); int chronosResponseResultGet(chronosResponse responseH); #endif
# -*- coding: utf-8 -*- # # Model Checker of HMM Aligner # Simon Fraser University # NLP Lab # # This is the model checker that checks if the model implementation fits the # requirement. It contains information about the APIs of the models. # If you plan to write your own model, upon loading the model # checkAlignmentModel will be called to check if the selected model contains # necessary methods with required parameters. # import os import sys import inspect currentdir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from models.modelBase import AlignmentModelBase as Base __version__ = "0.5a" supportedModels = [ "IBM1", "IBM1WithAlignmentType", "HMM", "HMMWithAlignmentType" ] requiredMethods = { "train": {"self": "instance", "dataset": "list", "iterations": "int"}, "decode": {"self": "instance", "dataset": "list", "showFigure": "int"}, "decodeSentence": {"self": "instance", "sentence": "list"} } def checkAlignmentModel(modelClass, logger=True): ''' This function will examine the model class. If the return value is False, then the model is unrecognisable by this function. @param modelClass: class, a model class @param logger: use loggers or not @return: bool. False for unrecognisable ''' if logger: from loggers import logging, init_logger error = logging.getLogger('CheckModel').error else: def error(msg): print "[ERROR]:", msg if not inspect.isclass(modelClass): error( "Specified Model needs to be a class named AlignmentModel under " + "models/ModelName.py") return False try: from models.cModelBase import AlignmentModelBase as cBase if issubclass(modelClass, cBase): logging.getLogger('CheckModel').info( "Loading Cython model, unable to check further") return True except ImportError: pass if not issubclass(modelClass, Base): error( "Specified Model needs to be a subclass of " + "models.modelBase.AlignmentModelBase ") return False try: model = modelClass() except all: error( "Specified Model instance cannot be created by calling " + "AlignmentModel()") return False for methodName in requiredMethods: method = getattr(modelClass, methodName, None) if not callable(method): error( "Specified Model class needs to have a method called '" + methodName + "', " + "containing at least the following arguments(without Tag): " + str(requiredMethods1[methodName]) + " or the following" + "(with Tag) " + str(requiredMethods2[methodName])) return False args, _, _, _ = inspect.getargspec(method) if [a for a in requiredMethods[methodName] if a not in args]: error( "Specified Model class's '" + methodName + "' method should " + "contain the following arguments(with exact same names): " + str(requiredMethods[methodName])) return False if [a for a in args if a not in requiredMethods[methodName]]: error( "Specified Model class's '" + methodName + "' method should " + "contain only the following arguments: " + str(requiredMethods[methodName])) return False if not [a for a in requiredMethods[methodName] if a not in args]: return True else: error("Unrecognisable model type.") return False return mode if __name__ == '__main__': print "Launching unit test on: models.modelChecker.checkAlignmentModel" print "This test will test the behaviour of checkAlignmentModel on all",\ "supported models:", supportedModels import importlib for name in supportedModels: try: Model = importlib.import_module("models." + name).AlignmentModel except all: print "Model", name, ": failed" mode = checkAlignmentModel(Model, False) if mode: print "Model", name, ": passed" else: print "Model", name, ": failed"
from peewee import * from . import Configs from time import time # Instance of the database (MySQL) db = MySQLDatabase( Configs.DB.NAME, **{ 'host': Configs.DB.HOST, 'port': Configs.DB.PORT, 'user': Configs.DB.USER, 'password': Configs.DB.PASSWORD } ) # Base model for all models class BaseModel(Model): class Meta: database = db # Bot clients model class Client(BaseModel): chat_id = CharField(unique=True) last_checked_time = TimestampField() is_registered = BooleanField() class Meta: table_name = Configs.DB.CLIENTS_TABLE # Initialize database and dao def init(): # Connect to database db.connect() # Create tables if they don't exist db.create_tables([Client]) # Add new client def add_client(chat_id): try: client = Client.get(Client.chat_id == chat_id) client.is_registered = True except DoesNotExist: client = Client(chat_id=chat_id, last_checked_time=time(), is_registered=True) client.save() return client # Switch registration of the client def switch_registration(chat_id): try: client = Client.get(Client.chat_id == chat_id) if client.is_registered: client.is_registered = False else: client.is_registered = True client.last_checked_time = time() client.save() except DoesNotExist: client = None return client # Get list of registered clients def get_registered_clients(): clients = Client.select().where(Client.is_registered) return clients def update_client_last_checked_time(chat_id): Client.update(last_checked_time=time()).where(Client.chat_id == chat_id).execute()
var owl; Template['album'].helpers({ 'album': function(){ return Session.get(this.id) }, }); Template['album'].events({ 'click .img-button': function(e) { e.preventDefault(); owl.goTo(this.index); } }); Template['album'].onRendered(function() { var self = this; if (!Session.get(this.data.id)){ Meteor.call('getFB', self.data.id, function(error, album) { Session.set(self.data.id, album); Session.set('page_name',self.data.name); }); } else { var album = Session.get(this.data.id) Session.set('page_name',album.name); } var owl_options = { autoPlay: true, pagination:false, autoplaySpeed : 400, items : 1, navigation: true, navigationText: ['',''], loop: true, autoHeight: false, singleItem: true }; $(".owl-carousel").owlCarousel(owl_options); owl = $(".owl-carousel").data('owlCarousel'); Meteor.call('getFB', self.data.id+'/photos', function(error, photos) { var album = Session.get(self.data.id); album.photos = photos.data; Session.set(self.data.id, album); _.each(album.photos, function(photo){ owl.addItem('<div class="item"><img src="'+photo.source+'" alt="loading..."></div>'); }); }); });
<?php /** * Author: Phucnh * Date created: Jan 23, 2015 * Company: DNICT */ defined('_JEXEC') or die(); require 'libraries/phpexcel/Classes/PHPExcel.php'; class NhucaudaotaoViewThongkenhucaudaotao extends JViewLegacy { function __construct() { parent::__construct(); } function display($tpl = null) { global $mainframe; $user = JFactory::getUser(); $document = &JFactory::getDocument(); $date = new JDate(); $objPhpExcel = new PHPExcel(); $data = JRequest::get('donvi_id'); $tungay= $data['tungay']; $denngay= $data['denngay']; $b=explode(',',$data['donvi_id']); $model = Core::model('Daotao/Thongkenhucaudaotao'); $ketqua = array(); for ($i=0;$i<sizeof($b);$i++) { array_push($ketqua,$model->excelThongkencdt($b[$i],$tungay,$denngay,$data['stt'])); } $this->assignRef('rows', $ketqua); if(is_null($tpl)) $tpl = 'excel'; parent::display($tpl); } }
<?php // Include Requests only if not already defined if (class_exists('Requests') === false) { require_once __DIR__.'/libs/Requests-1.8.0/library/Requests.php'; } try { Requests::register_autoloader(); if (version_compare(Requests::VERSION, '1.6.0') === -1) { throw new Exception('Requests class found but did not match'); } } catch (\Exception $e) { throw new Exception('Requests class found but did not match'); } spl_autoload_register(function ($class) { // project-specific namespace prefix $prefix = 'Razorpay\Api'; // base directory for the namespace prefix $base_dir = __DIR__ . '/src/'; // does the class use the namespace prefix? $len = strlen($prefix); if (strncmp($prefix, $class, $len) !== 0) { // no, move to the next registered autoloader return; } // get the relative class name $relative_class = substr($class, $len); // // replace the namespace prefix with the base directory, // replace namespace separators with directory separators // in the relative class name, append with .php // $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; // if the file exists, require it if (file_exists($file)) { require $file; } });
#!/usr/bin/env python # # Copyright 2009 Peter Prohaska # # This file is part of tagfs utils. # # tagfs utils 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. # # tagfs utils 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 tagfs utils. If not, see <http://www.gnu.org/licenses/>. # from distutils.core import setup, Command import sys import os from os.path import ( basename, dirname, abspath, splitext, join as pjoin ) from glob import glob from unittest import TestLoader, TextTestRunner projectdir = dirname(abspath(__file__)) srcdir = pjoin(projectdir, 'src') moddir = pjoin(srcdir, 'modules') testdir = pjoin(projectdir, 'test') testdatadir = pjoin(projectdir, 'etc', 'test', 'events') testmntdir = pjoin(projectdir, 'mnt') class test(Command): description = 'run tests' user_options = [] def initialize_options(self): self._cwd = os.getcwd() self._verbosity = 2 def finalize_options(self): pass def run(self): import re testPyMatcher = re.compile('(.*/)?test[^/]*[.]py', re.IGNORECASE) tests = ['.'.join([ basename(testdir), splitext(basename(f))[0] ]) for f in glob(pjoin( testdir, '*.py' )) if testPyMatcher.match(f)] print "..using:" print " testdir:", testdir print " testdatadir:", testdatadir print " testmntdir:", testmntdir print " tests:", tests print " sys.path:", sys.path print sys.path.insert(0, moddir) sys.path.insert(0, srcdir) # configure logging from tag_utils import log_config log_config.setUpLogging() suite = TestLoader().loadTestsFromNames(tests) TextTestRunner(verbosity = self._verbosity).run(suite) # Overrides default clean (which cleans from build runs) # This clean should probably be hooked into that somehow. class clean_pyc(Command): description = 'remove *.pyc files from source directory' user_options = [] def initialize_options(self): self._delete = [] for cwd, dirs, files in os.walk(projectdir): self._delete.extend( pjoin(cwd, f) for f in files if f.endswith('.pyc') ) def finalize_options(self): pass def run(self): for f in self._delete: try: os.unlink(f) except OSError, e: print "Strange '%s': %s" % (f, e) # Could be a directory. # Can we detect file in use errors or are they OSErrors # as well? # Shall we catch all? setup( cmdclass = { 'test': test, 'clean_pyc': clean_pyc, }, name = 'tagfs-utils', version = '0.1', url = 'http://wiki.github.com/marook/tagfs-utils', description = '', long_description = '', author = 'Markus Pielmeier', author_email = '[email protected]', license = 'GPLv3', platforms = 'Linux', requires = [], classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: System :: Filesystems' ], data_files = [ (pjoin('share', 'doc', 'tagfs-utils'), ['AUTHORS', 'COPYING', 'README']) ], scripts = [ pjoin('src', 'tag'), pjoin('src', 'find_item'), pjoin('src', 'gmail_to_tags') ], packages = ['tag_utils'], package_dir = {'': pjoin('src', 'modules')}, )
namespace Northwind.Repository { public class PageInfo { public int PageSize { get; set; } public int PageNumber { get; set; } } }
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.examples.permalink; import javax.enterprise.context.SessionScoped; import java.io.Serializable; /** * User session holder. * * @author <a href="mailto:[email protected]">Ales Justin</a> */ @SessionScoped public class Users implements Serializable { private static final long serialVersionUID = 1L; private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
#ifndef __XTHREAD_UTILS__H__ #define __XTHREAD_UTILS__H__ /* * Copyright (C) 2005-2009 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, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include <stdlib.h> HANDLE WINAPI CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); HANDLE _beginthreadex( void *security, unsigned stack_size, int ( *start_address )( void * ), void *arglist, unsigned initflag, unsigned *thrdaddr ); uintptr_t _beginthread( void( *start_address )( void * ), unsigned stack_size, void *arglist ); #if 0 // Deprecated, use CThread::GetCurrentThreadId() instead DWORD WINAPI GetCurrentThreadId(void); #endif HANDLE WINAPI GetCurrentThread(void); HANDLE WINAPI GetCurrentProcess(void); BOOL WINAPI GetThreadTimes ( HANDLE hThread, LPFILETIME lpCreationTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime ); int GetThreadPriority( HANDLE hThread ); BOOL WINAPI SetThreadPriority( HANDLE hThread, int nPriority ); // helper class for TLS handling class TLS { public: TLS() { pthread_key_create(&m_key, free); } ~TLS() { pthread_key_delete(m_key); } void *Get() { if (pthread_getspecific(m_key) == NULL) pthread_setspecific(m_key, calloc(8, 1)); return pthread_getspecific(m_key); } pthread_key_t m_key; }; #endif
using Nethereum.JsonRpc.Client; using Nethereum.RPC.Shh.DTOs; using System; using System.Threading.Tasks; namespace Nethereum.RPC.Shh.MessageFilter { public interface IShhNewMessageFilter { RpcRequest BuildRequest(MessageFilterInput input, object id = null); Task<string> SendRequestAsync(MessageFilterInput input, object id = null); } public class ShhNewMessageFilter : RpcRequestResponseHandler<string>, IShhNewMessageFilter { public ShhNewMessageFilter(IClient client) : base(client, ApiMethods.shh_newMessageFilter.ToString()) { } public RpcRequest BuildRequest(MessageFilterInput input, object id = null) { if (input == null) throw new ArgumentNullException(nameof(input)); if (string.IsNullOrEmpty(input.PrivateKeyID) && string.IsNullOrEmpty(input.SymKeyID)) throw new ArgumentNullException($"{nameof(input.SymKeyID)} Or {nameof(input.PrivateKeyID)}"); return base.BuildRequest(id, input); } public Task<string> SendRequestAsync(MessageFilterInput input, object id = null) { if (input == null) throw new ArgumentNullException(nameof(input)); if (string.IsNullOrEmpty(input.PrivateKeyID) && string.IsNullOrEmpty(input.SymKeyID)) throw new ArgumentNullException($"{nameof(input.SymKeyID)} Or {nameof(input.PrivateKeyID)}"); return base.SendRequestAsync(id, input); } } }
import re from livestreamer.plugin import Plugin from livestreamer.plugin.api import http, validate from livestreamer.stream import RTMPStream, HLSStream CHANNEL_INFO_URL = "http://live.afreeca.com:8057/api/get_broad_state_list.php" KEEP_ALIVE_URL = "{server}/stream_keepalive.html" STREAM_INFO_URLS = { "rtmp": "http://sessionmanager01.afreeca.tv:6060/broad_stream_assign.html", "hls": "http://resourcemanager.afreeca.tv:9090/broad_stream_assign.html" } HLS_KEY_URL = "http://api.m.afreeca.com/broad/a/watch" CHANNEL_RESULT_ERROR = 0 CHANNEL_RESULT_OK = 1 _url_re = re.compile("http(s)?://(\w+\.)?afreeca.com/(?P<username>\w+)") _channel_schema = validate.Schema( { "CHANNEL": { "RESULT": validate.transform(int), "BROAD_INFOS": [{ "list": [{ "nBroadNo": validate.text }] }] } }, validate.get("CHANNEL") ) _stream_schema = validate.Schema( { validate.optional("view_url"): validate.url( scheme=validate.any("rtmp", "http") ) } ) class AfreecaTV(Plugin): @classmethod def can_handle_url(self, url): return _url_re.match(url) def _get_channel_info(self, username): headers = { "Referer": self.url } data = { "uid": username } res = http.post(CHANNEL_INFO_URL, data=data, headers=headers) return http.json(res, schema=_channel_schema) def _get_hls_key(self, broadcast, username): headers = { "Referer": self.url } data = { "bj_id": username, "broad_no": broadcast } res = http.post(HLS_KEY_URL, data=data, headers=headers) return http.json(res) def _get_stream_info(self, broadcast, type): params = { "return_type": "gs_cdn", "use_cors": "true", "cors_origin_url": "m.afreeca.com", "broad_no": "{broadcast}-mobile-hd-{type}".format(**locals()), "broad_key": "{broadcast}-flash-hd-{type}".format(**locals()) } res = http.get(STREAM_INFO_URLS[type], params=params) return http.json(res, schema=_stream_schema) def _get_hls_stream(self, broadcast, username): keyjson = self._get_hls_key(broadcast, username) if keyjson["result"] != CHANNEL_RESULT_OK: return key = keyjson["data"]["hls_authentication_key"] info = self._get_stream_info(broadcast, "hls") if "view_url" in info: return HLSStream(self.session, info["view_url"], params=dict(aid=key)) def _get_rtmp_stream(self, broadcast): info = self._get_stream_info(broadcast, "rtmp") if "view_url" in info: params = dict(rtmp=info["view_url"]) return RTMPStream(self.session, params=params, redirect=True) def _get_streams(self): match = _url_re.match(self.url) username = match.group("username") channel = self._get_channel_info(username) if channel["RESULT"] != CHANNEL_RESULT_OK: return broadcast = channel["BROAD_INFOS"][0]["list"][0]["nBroadNo"] if not broadcast: return flash_stream = self._get_rtmp_stream(broadcast) if flash_stream: yield "live", flash_stream mobile_stream = self._get_hls_stream(broadcast, username) if mobile_stream: yield "live", mobile_stream __plugin__ = AfreecaTV
# -*- coding: utf-8 -*- import sys sys.path.append('../') from coscupbot import db, model, utils, modules import os import pytest import redis should_skip = 'REDIS' not in os.environ if not should_skip: REDIS_URL = os.environ['REDIS'] def get_dao(): return db.Dao(REDIS_URL) def gen_test_commands(num, language='zh_TW'): commands = [] for i in range(0, num): response = [model.CommandResponse(['Yooo'], 'resp%s-1' % i), model.CommandResponse(['Yooo'], 'resp%s-2' % i)] cmd = model.Command(language, 'CMD%s' % i, response) commands.append(cmd) return commands @pytest.mark.skipif(should_skip, reason="Redis connection url not configured") class TestDb: def teardown_method(self, test_method): r = redis.from_url(REDIS_URL) r.flushall() def test_ping(self): get_dao().test_connection() def test_add_command_one_lang(self): get_dao().add_commands(gen_test_commands(10, 'zh_TW')) r = redis.from_url(REDIS_URL) assert 10 == len(r.keys('COMMAND::zh_TW::*')) def test_add_command_two_lang(self): get_dao().add_commands(gen_test_commands(10, 'zh_TW')) get_dao().add_commands(gen_test_commands(20, 'en')) r = redis.from_url(REDIS_URL) assert 10 == len(r.keys('COMMAND::zh_TW::*')) assert 20 == len(r.keys('COMMAND::en::*')) assert 30 == len(r.keys('COMMAND::*')) def test_delete_command(self): self.test_add_command_two_lang() get_dao().clear_all_command() r = redis.from_url(REDIS_URL) assert 0 == len(r.keys('COMMAND::*')) def test_get_command_response(self): cmd1 = model.Command('zh_TW', 'help', [model.CommandResponse(['No', 'No2'], 'hi'), model.CommandResponse(['No3', 'No4'], 'Hello')]) cmd2 = model.Command('zh_TW', 'hello', [model.CommandResponse(['Yes', 'Yes2'], 'Hello'), model.CommandResponse(['Yes3', 'Yes4'], 'Wrold')]) get_dao().add_commands([cmd1, cmd2]) result = modules.random_get_result(get_dao().get_command_responses('help', 'zh_TW')) cr = model.CommandResponse.de_json(result) assert 'hi' == cr.response_msg or 'Hello' == cr.response_msg def test_get_command_response_no_data(self): try: get_dao().get_command_responses('help', 'zh_TW') except db.CommandError as ce: assert True except Exception as ex: assert False def test_update_command(self): r = redis.from_url(REDIS_URL) get_dao().add_commands(gen_test_commands(10, 'zh_TW')) assert 10 == len(r.keys('COMMAND::zh_TW::*')) get_dao().update_commands(gen_test_commands(20, 'en')) assert 0 == len(r.keys('COMMAND::zh_TW::*')) assert 20 == len(r.keys('COMMAND::en::*')) assert 20 == len(r.keys('COMMAND::*')) def test_add_mid(self): r = redis.from_url(REDIS_URL) get_dao().add_user_mid('11111') get_dao().add_user_mid('22222') assert 2 == len(r.hgetall('MID')) def test_get_mid(self): get_dao().add_user_mid('11111') get_dao().add_user_mid('22222') get_dao().add_user_mid('ufasfsafsdfsaf') result = get_dao().get_all_user_mid() assert '11111' in result assert '22222' in result assert 'ufasfsafsdfsaf' in result def test_delete_no_command(self): get_dao().clear_all_command() def test_init_ground_data(self): get_dao().init_ground_data('test') data = get_dao().get_ground_data('test') for k, v in data.items(): assert v == False def test_check_in_ground(self): get_dao().init_ground_data('test') get_dao().checkin_ground('vedkoprjdi', 'test') data = get_dao().get_ground_data('test') print(data) assert data['vedkoprjdi'] == True assert data['dkmjijoji'] == False def test_check_in_not_friedn(self): get_dao().checkin_ground('vedkoprjdi', 'test') data = get_dao().get_ground_data('test') print(data) assert data['vedkoprjdi'] == True assert data['dkmjijoji'] == False get_dao().checkin_ground('dkmjijoji', 'test') data = get_dao().get_ground_data('test') assert data['vedkoprjdi'] == True assert data['dkmjijoji'] == True def test_num_of_photo(self): mid = '1123' result = get_dao().get_num_of_photo(mid) assert result == 0 def test_num_of_photo_inc(self): mid = '1123' get_dao().increase_num_of_photo(mid) result = get_dao().get_num_of_photo(mid) assert result == 1 get_dao().increase_num_of_photo(mid) get_dao().increase_num_of_photo(mid) get_dao().increase_num_of_photo(mid) result = get_dao().get_num_of_photo(mid) assert result == 4
<?php namespace Drupal\devel\Plugin\Devel\Dumper; use Doctrine\Common\Util\Debug; use Drupal\Component\Utility\Xss; use Drupal\devel\DevelDumperBase; /** * Provides a DoctrineDebug dumper plugin. * * @DevelDumper( * id = "default", * label = @Translation("Default"), * description = @Translation("Wrapper for <a href='https://www.doctrine-project.org/api/common/latest/Doctrine/Common/Util/Debug.html'>Doctrine</a> debugging tool.") * ) */ class DoctrineDebug extends DevelDumperBase { /** * {@inheritdoc} */ public function export($input, $name = NULL) { $name = $name ? $name . ' => ' : ''; $variable = Debug::export($input, 6); ob_start(); print_r($variable); $dump = ob_get_contents(); ob_end_clean(); // Run Xss::filterAdmin on the resulting string to prevent // cross-site-scripting (XSS) vulnerabilities. $dump = Xss::filterAdmin($dump); $config = \Drupal::config('devel.settings'); $debug_pre = $config->get('debug_pre'); $dump = ($debug_pre ? '<pre>' : '') . $name . $dump . ($debug_pre ? '</pre>' : ''); return $this->setSafeMarkup($dump); } /** * {@inheritdoc} */ public function exportAsRenderable($input, $name = NULL) { $output['container'] = [ '#type' => 'details', '#title' => $name ?: $this->t('Variable'), '#attached' => [ 'library' => ['devel/devel'], ], '#attributes' => [ 'class' => ['container-inline', 'devel-dumper', 'devel-selectable'], ], 'export' => [ '#markup' => $this->export($input), ], ]; return $output; } /** * {@inheritdoc} */ public static function checkRequirements() { return TRUE; } }
#!/usr/bin/python # Copyright (C) 2007 Google 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. """ This package provides implementation of a converter from a kml file format into Google transit feed format. The KmlParser class is the main class implementing the parser. Currently only information about stops is extracted from a kml file. The extractor expects the stops to be represented as placemarks with a single point. """ import re import string import sys import transitfeed from transitfeed import util import xml.dom.minidom as minidom import zipfile class Placemark(object): def __init__(self): self.name = "" self.coordinates = [] def IsPoint(self): return len(self.coordinates) == 1 def IsLine(self): return len(self.coordinates) > 1 class KmlParser(object): def __init__(self, stopNameRe = '(.*)'): """ Args: stopNameRe - a regular expression to extract a stop name from a placemaker name """ self.stopNameRe = re.compile(stopNameRe) def Parse(self, filename, feed): """ Reads the kml file, parses it and updated the Google transit feed object with the extracted information. Args: filename - kml file name feed - an instance of Schedule class to be updated """ dom = minidom.parse(filename) self.ParseDom(dom, feed) def ParseDom(self, dom, feed): """ Parses the given kml dom tree and updates the Google transit feed object. Args: dom - kml dom tree feed - an instance of Schedule class to be updated """ shape_num = 0 for node in dom.getElementsByTagName('Placemark'): p = self.ParsePlacemark(node) if p.IsPoint(): (lon, lat) = p.coordinates[0] m = self.stopNameRe.search(p.name) feed.AddStop(lat, lon, m.group(1)) elif p.IsLine(): shape_num = shape_num + 1 shape = transitfeed.Shape("kml_shape_" + str(shape_num)) for (lon, lat) in p.coordinates: shape.AddPoint(lat, lon) feed.AddShapeObject(shape) def ParsePlacemark(self, node): ret = Placemark() for child in node.childNodes: if child.nodeName == 'name': ret.name = self.ExtractText(child) if child.nodeName == 'Point' or child.nodeName == 'LineString': ret.coordinates = self.ExtractCoordinates(child) return ret def ExtractText(self, node): for child in node.childNodes: if child.nodeType == child.TEXT_NODE: return child.wholeText # is a unicode string return "" def ExtractCoordinates(self, node): coordinatesText = "" for child in node.childNodes: if child.nodeName == 'coordinates': coordinatesText = self.ExtractText(child) break ret = [] for point in coordinatesText.split(): coords = point.split(',') ret.append((float(coords[0]), float(coords[1]))) return ret def main(): usage = \ """%prog <input.kml> <output GTFS.zip> Reads KML file <input.kml> and creates GTFS file <output GTFS.zip> with placemarks in the KML represented as stops. """ parser = util.OptionParserLongError( usage=usage, version='%prog '+transitfeed.__version__) (options, args) = parser.parse_args() if len(args) != 2: parser.error('You did not provide all required command line arguments.') if args[0] == 'IWantMyCrash': raise Exception('For testCrashHandler') parser = KmlParser() feed = transitfeed.Schedule() feed.save_all_stops = True parser.Parse(args[0], feed) feed.WriteGoogleTransitFeed(args[1]) print "Done." if __name__ == '__main__': util.RunWithCrashHandler(main)
namespace Xilium.CefGlue.Platform.Windows; using System; using System.Collections.Generic; using System.Text; [Flags] public enum LoadLibraryFlags : uint { DONT_RESOLVE_DLL_REFERENCES = 0x00000001, LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010, LOAD_LIBRARY_AS_DATAFILE = 0x00000002, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040, LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020, LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008 }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrderedBankingSystem { class Program { static void Main(string[] args) { var banksAndAccounts = new Dictionary<string, Dictionary<string, decimal>>(); string input = Console.ReadLine(); while (input != "end") { string[] inputParams = input .Split(new[] {' ', '-', '>'} , StringSplitOptions.RemoveEmptyEntries); string bankName = inputParams[0]; string bankAccountName = inputParams[1]; decimal bankAccountBalance = decimal.Parse(inputParams[2]); if (!banksAndAccounts.ContainsKey(bankName)) { banksAndAccounts.Add(bankName, new Dictionary<string, decimal>()); } if (!banksAndAccounts[bankName].ContainsKey(bankAccountName)) { banksAndAccounts[bankName].Add(bankAccountName, 0); } banksAndAccounts[bankName][bankAccountName] += bankAccountBalance; input = Console.ReadLine(); } foreach (var bank in banksAndAccounts.OrderByDescending(bank => bank.Value.Sum(account => account.Value)) .ThenByDescending(bank => bank.Value.Max(account => account.Value))) { foreach (var account in bank.Value.OrderByDescending(account => account.Value)) { Console.WriteLine($"{account.Key} -> {account.Value} ({bank.Key})"); } } } } }
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from celery.signals import import_modules from indico.core import signals from indico.core.celery.core import IndicoCelery from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.menu import SideMenuItem __all__ = ('celery',) #: The Celery instance for all Indico tasks celery = IndicoCelery('indico') @signals.app_created.connect def _load_default_modules(app, **kwargs): celery.loader.import_default_modules() # load all tasks @import_modules.connect def _import_modules(*args, **kwargs): import indico.util.tasks signals.import_tasks.send() @signals.menu.items.connect_via('admin-sidemenu') def _extend_admin_menu(sender, **kwargs): return SideMenuItem('celery', _("Tasks"), url_for('celery.index'), 20, icon='time')
# encoding: UTF-8 """ Test rules built-in functions """ from __future__ import absolute_import import unittest from mock import patch from tml.rules.engine import * from tml.rules.functions import SUPPORTED_FUNCTIONS from tml.rules.parser import parse def die_op(): raise Exception('dummy exception') class EngineTest(unittest.TestCase): """ Test of rules engine """ def setUp(self): """ Use mock engine """ self.engine = RulesEngine(SUPPORTED_FUNCTIONS) def test_number_rules(self): self.assertEquals( 1, self.engine.execute( parse('(mod @n 10)'), {'n': 1}), '@n = 1 -> (mod @n 10)') self.assertTrue( self.engine.execute( parse('(= 1 @n)'), {'n': 1}), '@n = 1 -> (= 1 @n)') self.assertTrue( self.engine.execute( parse('(= 1 (mod @n 10))'), {'n': 1}), '@n = 1 -> (= 1 (mod @n 10))') self.assertTrue( self.engine.execute( parse('(&& (= 1 (mod @n 10)) (!= 11 (mod @n 100)))'), {'n': 1})) def test_execution(self): """ Test rules engine""" self.assertEquals(5, self.engine.execute(['+', '2', '3'], {}), '(+ 2 3)') def test_arguments(self): """ Pass arguments """ self.assertEquals(5, self.engine.execute(['+', '@a', '@b'], {'a':2, 'b':3}), '(+ @a @b)') self.assertTrue( self.engine.execute( parse('(&& (= @a (mod @n @b)) (!= @c (mod @n @d)))'), {'n': 1, 'a': 1, 'b': 10, 'c': 2, 'd': 100})) def test_inner(self): """ Inner expression """ self.assertEquals(3, self.engine.execute(['mod', ['+', '8', '5'], '10'], {}), '(mod (+ 8 5) 10)') self.assertEquals(3, self.engine.execute(['mod', ['+', '@a', '5'], '@b'], {'a':18, 'b':10}), '(mod (+ @a 5) @b)') def test_function_not_suported(self): with self.assertRaises(FunctionDoesNotExists) as context: self.engine.execute(['xor', '2', '3'], {}) def test_argument_does_not_exists(self): with self.assertRaises(ArgumentDoesNotExists) as context: self.engine.execute(['+', '@e', '3'], {}) self.assertEquals('@e', context.exception.argument_name, 'Store argument name') self.assertEquals(1, context.exception.part_number, 'In first argument') @patch.dict(SUPPORTED_FUNCTIONS, {'die': die_op}) def test_function_error(self): """ Check that engine handle function error """ with self.assertRaises(FunctionCallFault) as context: self.engine.execute(['die'], {}) with self.assertRaises(FunctionCallFault) as context: # Pass invalid argument: self.engine.execute(['mod', 'a', '10'], {}) self.assertEquals(ValueError, context.exception.exception.__class__, 'Store original exception') with self.assertRaises(FunctionCallFault) as context: # Pass wrong count argument: self.engine.execute(['mod', '1', '10', '100'], {}) self.assertEquals(TypeError, context.exception.exception.__class__, 'Store original exception') @patch.dict(SUPPORTED_FUNCTIONS, {'die': die_op}) def test_inner_function_call(self): with self.assertRaises(InnerExpressionCallFault) as context: self.engine.execute(['mod', '10', ['die']], {}) self.assertEquals(FunctionCallFault, context.exception.parent_error.__class__, 'Handle information about original error') self.assertEquals(2, context.exception.part_number, 'Store part number') def test_compare(self): engine = RulesEngine(SUPPORTED_FUNCTIONS) self.assertTrue(engine.execute(['<', '@value', '10'], {'value': 8}), '8 < 10') self.assertFalse(engine.execute(['<', '@value', '7'], {'value': 8}), '! 8 < 7') self.assertTrue(engine.execute(['<', '7', '@value'], {'value': 8}), '7 < 8') q = parse('(&& (< 3 @value) (> 12 @value))') self.assertTrue(engine.execute(q, {'value': 8})) self.assertFalse(engine.execute(q, {'value': 3})) self.assertFalse(engine.execute(q, {'value': 14})) if __name__ == '__main__': unittest.main()
/* * Copyright (c) 2013 Android Alliance LTD * * 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 uk.co.androidalliance.fsm.client.actiontypes; import uk.co.androidalliance.fsm.interfaces.ActionType; public class UnlockActionTypes implements ActionType{ public static final String ACTION_TYPE = UnlockActionTypes.class.getSimpleName(); private final Object payload; public UnlockActionTypes (Object payload) { this.payload = payload; } @Override public Object getPayload() { return payload; } @Override public String toString() { return ACTION_TYPE + ", payload : " + payload; } }
/*jshint node:true*/ module.exports = { "framework": "qunit", "test_page": "tests/index.html?hidepassed", "disable_watching": true, "launch_in_ci": [ "Firefox" ], "launch_in_dev": [ "Firefox", "Chrome" ] };
# -*- coding: utf-8 -*- from __future__ import absolute_import import errno import os import socket import sys from .transport import TTransportBase, TTransportException class TSocketBase(TTransportBase): def _resolveAddr(self): if self._unix_socket is not None: return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None, self._unix_socket)] else: return socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE | socket.AI_ADDRCONFIG) def close(self): if self.handle: self.handle.close() self.handle = None class TSocket(TSocketBase): """Socket implementation of TTransport base.""" def __init__(self, host='localhost', port=9090, unix_socket=None): """Initialize a TSocket @param host(str) The host to connect to. @param port(int) The (TCP) port to connect to. @param unix_socket(str) The filename of a unix socket to connect to. (host and port will be ignored.) """ self.host = host self.port = port self.handle = None self._unix_socket = unix_socket self._timeout = None def set_handle(self, h): self.handle = h def is_open(self): return bool(self.handle) def set_timeout(self, ms): self._timeout = ms / 1000.0 if ms else None if self.handle: self.handle.settimeout(self._timeout) def open(self): try: res0 = self._resolveAddr() for res in res0: self.handle = socket.socket(res[0], res[1]) self.handle.settimeout(self._timeout) try: self.handle.connect(res[4]) except socket.error as e: if res is not res0[-1]: continue else: raise e break except socket.error as e: if self._unix_socket: message = 'Could not connect to socket %s' % self._unix_socket else: message = 'Could not connect to %s:%d' % (self.host, self.port) raise TTransportException(type=TTransportException.NOT_OPEN, message=message) def read(self, sz): try: buff = self.handle.recv(sz) except socket.error as e: if (e.args[0] == errno.ECONNRESET and (sys.platform == 'darwin' or sys.platform.startswith('freebsd'))): # freebsd and Mach don't follow POSIX semantic of recv # and fail with ECONNRESET if peer performed shutdown. # See corresponding comment and code in TSocket::read() # in lib/cpp/src/transport/TSocket.cpp. self.close() # Trigger the check to raise the END_OF_FILE exception below. buff = '' else: raise if len(buff) == 0: raise TTransportException(type=TTransportException.END_OF_FILE, message='TSocket read 0 bytes') return buff def write(self, buff): if not self.handle: raise TTransportException(type=TTransportException.NOT_OPEN, message='Transport not open') self.handle.sendall(buff) def flush(self): pass class TServerSocket(TSocketBase): """Socket implementation of TServerTransport base.""" def __init__(self, host=None, port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC): self.host = host self.port = port self._unix_socket = unix_socket self._socket_family = socket_family self.handle = None def listen(self): res0 = self._resolveAddr() socket_family = self._socket_family == socket.AF_UNSPEC and ( socket.AF_INET6 or self._socket_family) for res in res0: if res[0] is socket_family or res is res0[-1]: break # We need remove the old unix socket if the file exists and # nobody is listening on it. if self._unix_socket: tmp = socket.socket(res[0], res[1]) try: tmp.connect(res[4]) except socket.error as err: eno, message = err.args if eno == errno.ECONNREFUSED: os.unlink(res[4]) self.handle = socket.socket(res[0], res[1]) self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(self.handle, 'settimeout'): self.handle.settimeout(None) self.handle.bind(res[4]) self.handle.listen(128) def accept(self): client, addr = self.handle.accept() result = TSocket() result.set_handle(client) return result
//------------------------------------------------------------------------------------------------- // <copyright file="UserGroup.cs" company="Allors bvba"> // Copyright 2002-2016 Allors bvba. // // Dual Licensed under // a) the Lesser General Public Licence v3 (LGPL) // b) the Allors License // // The LGPL License is included in the file lgpl.txt. // The Allors License is an addendum to your contract. // // Allors Platform 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. // // For more information visit http://www.allors.com/legal // </copyright> // <summary>Defines the Extent type.</summary> //------------------------------------------------------------------------------------------------- namespace Allors.Repository { using System; using Attributes; #region Allors [Id("60065f5d-a3c2-4418-880d-1026ab607319")] #endregion public partial class UserGroup : UniquelyIdentifiable, AccessControlledObject { #region inherited properties public Guid UniqueId { get; set; } public Permission[] DeniedPermissions { get; set; } public SecurityToken[] SecurityTokens { get; set; } #endregion #region Allors [Id("585bb5cf-9ba4-4865-9027-3667185abc4f")] [AssociationId("1e2d1e31-ed80-4435-8850-7663d9c5f41d")] [RoleId("c552f0b7-95ce-4d45-aaea-56bc8365eee4")] #endregion [Multiplicity(Multiplicity.ManyToMany)] [Indexed] public User[] Members { get; set; } #region Allors [Id("e94e7f05-78bd-4291-923f-38f82d00e3f4")] [AssociationId("75859e2c-c1a3-4f4c-bb37-4064d0aa81d0")] [RoleId("9d3c1eec-bf10-4a79-a37f-bc6a20ff2a79")] #endregion [Indexed] [Required] [Unique] [Size(256)] public string Name { get; set; } #region inherited methods public void OnBuild(){} public void OnPostBuild(){} public void OnPreDerive(){} public void OnDerive(){} public void OnPostDerive(){} #endregion } }
import os from flask import Flask from flask.ext.heroku import Heroku #from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy import * debug = True app = Flask(__name__) heroku = Heroku(app) db = create_engine(os.environ.get('HEROKU_POSTGRESQL_WHITE_URL', 'sqlite:///testing.db')) metadata = MetaData(db) scores = Table('scores', metadata, Column('id', Integer, primary_key=True), Column('name', String(30)), Column('score', Integer)) metadata.create_all() @app.route('/') def hello(): return "HELLO!" @app.route('/add/<name>/<int:score>') def add(name, score): r = scores.insert().execute({'name': name, 'score': score}) return "OK" @app.route('/get/<int:score>') def get(score): i = select([func.count()]).where(scores.c.score < score).select_from(scores).execute().scalar() # returns a python list literal. Use ast.literal_eval to read v = [] for row in scores.select().order_by("score").offset(max(0, i-3)).limit(6).execute(): v.append("('%s', %d)" % (row['name'], row['score'])) return "[%s]" % ', '.join(v) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug = debug)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace VirtualSales.Wpf.Views.Tools.LifetimeEconomicValue { /// <summary> /// Interaction logic for Page1.xaml /// </summary> public partial class Page1 : UserControl { public Page1() { InitializeComponent(); } } }
#!/usr/bin/env python """ 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. """ from resource_management import * import sys from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl from ambari_commons import OSConst @OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY) def hcat(): import params XmlConfig("hive-site.xml", conf_dir = params.hive_conf_dir, configurations = params.config['configurations']['hive-site'], owner=params.hive_user, configuration_attributes=params.config['configuration_attributes']['hive-site'] ) @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT) def hcat(): import params Directory(params.hive_conf_dir, create_parents = True, owner=params.hcat_user, group=params.user_group, ) Directory(params.hcat_conf_dir, create_parents = True, owner=params.hcat_user, group=params.user_group, ) Directory(params.hcat_pid_dir, owner=params.webhcat_user, create_parents = True ) XmlConfig("hive-site.xml", conf_dir=params.hive_client_conf_dir, configurations=params.hive_site_config, configuration_attributes=params.config['configuration_attributes']['hive-site'], owner=params.hive_user, group=params.user_group, mode=0644) File(format("{hcat_conf_dir}/hcat-env.sh"), owner=params.hcat_user, group=params.user_group, content=InlineTemplate(params.hcat_env_sh_template) )
/* * Copyright (C) 2011-2012 BlizzLikeCore <http://blizzlike.servegame.com/> * Please, read the credits file. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Emperor_Dagran_Thaurissan SD%Complete: 99 SDComment: SDCategory: Blackrock Depths EndScriptData */ #include "ScriptPCH.h" enum Yells { SAY_AGGRO = -1230001, SAY_SLAY = -1230002 }; enum Spells { SPELL_HANDOFTHAURISSAN = 17492, SPELL_AVATAROFFLAME = 15636 }; struct boss_draganthaurissanAI : public ScriptedAI { boss_draganthaurissanAI(Creature *c) : ScriptedAI(c) {} uint32 HandOfThaurissan_Timer; uint32 AvatarOfFlame_Timer; //uint32 Counter; void Reset() { HandOfThaurissan_Timer = 4000; AvatarOfFlame_Timer = 25000; //Counter= 0; } void EnterCombat(Unit * /*who*/) { DoScriptText(SAY_AGGRO, me); me->CallForHelp(VISIBLE_RANGE); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_SLAY, me); } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; if (HandOfThaurissan_Timer <= diff) { if (Unit *pTarget = SelectUnit(SELECT_TARGET_RANDOM,0)) DoCast(pTarget, SPELL_HANDOFTHAURISSAN); //3 Hands of Thaurissan will be casted //if (Counter < 3) //{ // HandOfThaurissan_Timer = 1000; // ++Counter; //} //else //{ HandOfThaurissan_Timer = 5000; //Counter = 0; //} } else HandOfThaurissan_Timer -= diff; //AvatarOfFlame_Timer if (AvatarOfFlame_Timer <= diff) { DoCast(me->getVictim(), SPELL_AVATAROFFLAME); AvatarOfFlame_Timer = 18000; } else AvatarOfFlame_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_draganthaurissan(Creature* pCreature) { return new boss_draganthaurissanAI (pCreature); } void AddSC_boss_draganthaurissan() { Script *newscript; newscript = new Script; newscript->Name = "boss_emperor_dagran_thaurissan"; newscript->GetAI = &GetAI_boss_draganthaurissan; newscript->RegisterSelf(); }
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'stylescombo', 'pt-br', { label: 'Estilo', panelTitle: 'Estilos de Formatação', panelTitle1: 'Estilos de bloco', panelTitle2: 'Estilos de texto corrido', panelTitle3: 'Estilos de objeto' } );
package org.bouncycastle.asn1; import java.io.IOException; import java.util.Enumeration; /** * Carrier class for an indefinite-length SET. */ public class BERSet extends ASN1Set { /** * Create an empty SET. */ public BERSet() { } /** * Create a SET containing one object. * * @param obj - a single object that makes up the set. */ public BERSet( ASN1Encodable obj) { super(obj); } /** * Create a SET containing multiple objects. * @param v a vector of objects making up the set. */ public BERSet( ASN1EncodableVector v) { super(v, false); } /** * Create a SET from an array of objects. * @param a an array of ASN.1 objects. */ public BERSet( ASN1Encodable[] a) { super(a, false); } int encodedLength() throws IOException { int length = 0; for (Enumeration e = getObjects(); e.hasMoreElements();) { length += ((ASN1Encodable)e.nextElement()).toASN1Primitive().encodedLength(); } return 2 + length + 2; } void encode( ASN1OutputStream out) throws IOException { out.write(BERTags.SET | BERTags.CONSTRUCTED); out.write(0x80); Enumeration e = getObjects(); while (e.hasMoreElements()) { out.writeObject((ASN1Encodable)e.nextElement()); } out.write(0x00); out.write(0x00); } }
using System; namespace Assembler.Instructions { public struct LabelInstruction : IInstruction, IEquatable<LabelInstruction> { private readonly string _label; public LabelInstruction(string label) { _label = label; } public string Label { get { return _label; } } public T Accept<T>(IInstructionVisitor<T> instructionVisitor) { return instructionVisitor.VisitInstruction(this); } public bool Equals(LabelInstruction other) { return string.Equals(other.Label, Label); } } }
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: t -*- #include <FastSerial.h> #define GPS_DEBUGGING 0 #if GPS_DEBUGGING #include <FastSerial.h> # define Debug(fmt, args ...) do {Serial.printf("%s:%d: " fmt "\n", __FUNCTION__, __LINE__, ## args); delay(0); } while(0) #else # define Debug(fmt, args ...) #endif #include <AP_Common.h> #include <AP_Math.h> #include "GPS.h" #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif void GPS::update(void) { bool result; uint32_t tnow; // call the GPS driver to process incoming data result = read(); tnow = millis(); // if we did not get a message, and the idle timer has expired, re-init if (!result) { if ((tnow - _idleTimer) > idleTimeout) { Debug("gps read timeout %lu %lu", (unsigned long)tnow, (unsigned long)_idleTimer); _status = NO_GPS; init(_nav_setting); // reset the idle timer _idleTimer = tnow; } } else { // we got a message, update our status correspondingly _status = fix ? GPS_OK : NO_FIX; valid_read = true; new_data = true; // reset the idle timer _idleTimer = tnow; if (_status == GPS_OK) { last_fix_time = _idleTimer; _last_ground_speed_cm = ground_speed; if (_have_raw_velocity) { // the GPS is able to give us velocity numbers directly _velocity_north = _vel_north * 0.01; _velocity_east = _vel_east * 0.01; _velocity_down = _vel_down * 0.01; } else { float gps_heading = ToRad(ground_course * 0.01); float gps_speed = ground_speed * 0.01; float sin_heading, cos_heading; cos_heading = cos(gps_heading); sin_heading = sin(gps_heading); _velocity_north = gps_speed * cos_heading; _velocity_east = gps_speed * sin_heading; // no good way to get descent rate _velocity_down = 0; } } } } void GPS::setHIL(uint32_t _time, float _latitude, float _longitude, float _altitude, float _ground_speed, float _ground_course, float _speed_3d, uint8_t _num_sats) { } // XXX this is probably the wrong way to do it, too void GPS::_error(const char *msg) { Serial.println(msg); } /// /// write a block of configuration data to a GPS /// void GPS::_write_progstr_block(Stream *_fs, const prog_char *pstr, uint8_t size) { while (size--) { _fs->write(pgm_read_byte(pstr++)); } } /* a prog_char block queue, used to send out config commands to a GPS in 16 byte chunks. This saves us having to have a 128 byte GPS send buffer, while allowing us to avoid a long delay in sending GPS init strings while waiting for the GPS auto detection to happen */ // maximum number of pending progstrings #define PROGSTR_QUEUE_SIZE 3 struct progstr_queue { const prog_char *pstr; uint8_t ofs, size; }; static struct { FastSerial *fs; uint8_t queue_size; uint8_t idx, next_idx; struct progstr_queue queue[PROGSTR_QUEUE_SIZE]; } progstr_state; void GPS::_send_progstr(Stream *_fs, const prog_char *pstr, uint8_t size) { progstr_state.fs = (FastSerial *)_fs; struct progstr_queue *q = &progstr_state.queue[progstr_state.next_idx]; q->pstr = pstr; q->size = size; q->ofs = 0; progstr_state.next_idx++; if (progstr_state.next_idx == PROGSTR_QUEUE_SIZE) { progstr_state.next_idx = 0; } } void GPS::_update_progstr(void) { struct progstr_queue *q = &progstr_state.queue[progstr_state.idx]; // quick return if nothing to do if (q->size == 0 || progstr_state.fs->tx_pending()) { return; } uint8_t nbytes = q->size - q->ofs; if (nbytes > 16) { nbytes = 16; } _write_progstr_block(progstr_state.fs, q->pstr+q->ofs, nbytes); q->ofs += nbytes; if (q->ofs == q->size) { q->size = 0; progstr_state.idx++; if (progstr_state.idx == PROGSTR_QUEUE_SIZE) { progstr_state.idx = 0; } } }
# Copyright (C) 2013 Equinor ASA, Norway. # # The file 'analysis_iter_config.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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. # # ERT 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 at <http://www.gnu.org/licenses/gpl.html> # for more details. from cwrap import BaseCClass from res import ResPrototype from res.enkf import ConfigKeys class AnalysisIterConfig(BaseCClass): TYPE_NAME = "analysis_iter_config" _alloc = ResPrototype("void* analysis_iter_config_alloc( )", bind = False) _alloc_full = ResPrototype("void* analysis_iter_config_alloc_full( char*, int, int )", bind = False) _free = ResPrototype("void analysis_iter_config_free( analysis_iter_config )") _set_num_iterations = ResPrototype("void analysis_iter_config_set_num_iterations(analysis_iter_config, int)") _get_num_iterations = ResPrototype("int analysis_iter_config_get_num_iterations(analysis_iter_config)") _get_num_retries = ResPrototype("int analysis_iter_config_get_num_retries_per_iteration(analysis_iter_config)") _num_iterations_set = ResPrototype("bool analysis_iter_config_num_iterations_set(analysis_iter_config)") _set_case_fmt = ResPrototype("void analysis_iter_config_set_case_fmt( analysis_iter_config , char* )") _get_case_fmt = ResPrototype("char* analysis_iter_config_get_case_fmt( analysis_iter_config)") _case_fmt_set = ResPrototype("bool analysis_iter_config_case_fmt_set(analysis_iter_config)") def __init__(self, config_dict=None): if config_dict is None: c_ptr = self._alloc() if c_ptr: super(AnalysisIterConfig , self).__init__(c_ptr) else: raise ValueError('Failed to construct AnalysisIterConfig instance.') else: c_ptr = self._alloc_full( config_dict[ConfigKeys.ITER_CASE], config_dict[ConfigKeys.ITER_COUNT], config_dict[ConfigKeys.ITER_RETRY_COUNT] ) if c_ptr: super(AnalysisIterConfig, self).__init__(c_ptr) else: raise ValueError('Failed to construct AnalysisIterConfig instance for dictionary.') def getNumIterations(self): """ @rtype: int """ return self._get_num_iterations() def __len__(self): """Returns number of iterations.""" return self.getNumIterations() def setNumIterations(self, num_iterations): self._set_num_iterations(num_iterations) def numIterationsSet(self): return self._num_iterations_set() def getNumRetries(self): """ @rtype: int """ return self._get_num_retries() def getCaseFormat(self): """ @rtype: str """ return self._get_case_fmt() def setCaseFormat(self, case_fmt): self._set_case_fmt(case_fmt) def caseFormatSet(self): return self._case_fmt_set() def free(self): self._free() def _short_case_fmt(self, maxlen=10): fmt = self.getCaseFormat() if len(fmt) <= maxlen: return fmt return fmt[:maxlen-2] + ".." def __repr__(self): cfs = 'format = False' if self.caseFormatSet(): cfs = 'format = True' fmt = self._short_case_fmt() ret = 'AnalysisIterConfig(iterations = %d, retries = %d, fmt = %s, %s) at 0x%x' its = len(self) rets = self.getNumRetries() return ret % (its, rets, fmt, cfs, self._address) def __ne__(self, other): return not self == other def __eq__(self, other): if self.getCaseFormat()!=other.getCaseFormat(): return False if self.getNumIterations()!=other.getNumIterations(): return False if self.getNumRetries()!=other.getNumRetries(): return False return True
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # 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 trainer_lib.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensor2tensor.data_generators import algorithmic from tensor2tensor.data_generators import problem as problem_lib from tensor2tensor.models import transformer # pylint: disable=unused-import from tensor2tensor.utils import registry from tensor2tensor.utils import trainer_lib import tensorflow as tf class TrainerLibTest(tf.test.TestCase): @classmethod def setUpClass(cls): algorithmic.TinyAlgo.setup_for_test() def testExperiment(self): exp_fn = trainer_lib.create_experiment_fn( "transformer", "tiny_algo", algorithmic.TinyAlgo.data_dir, train_steps=1, eval_steps=1, min_eval_frequency=1, use_tpu=False) run_config = trainer_lib.create_run_config( model_name="transformer", model_dir=algorithmic.TinyAlgo.data_dir, num_gpus=0, use_tpu=False) hparams = registry.hparams("transformer_tiny_tpu") exp = exp_fn(run_config, hparams) exp.test() def testExperimentWithClass(self): exp_fn = trainer_lib.create_experiment_fn( "transformer", algorithmic.TinyAlgo(), algorithmic.TinyAlgo.data_dir, train_steps=1, eval_steps=1, min_eval_frequency=1, use_tpu=False) run_config = trainer_lib.create_run_config( model_name="transformer", model_dir=algorithmic.TinyAlgo.data_dir, num_gpus=0, use_tpu=False) hparams = registry.hparams("transformer_tiny_tpu") exp = exp_fn(run_config, hparams) exp.test() def testModel(self): # HParams hparams = trainer_lib.create_hparams( "transformer_tiny", data_dir=algorithmic.TinyAlgo.data_dir, problem_name="tiny_algo") # Dataset problem = hparams.problem dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, algorithmic.TinyAlgo.data_dir) dataset = dataset.repeat(None).padded_batch(10, dataset.output_shapes) features = dataset.make_one_shot_iterator().get_next() features = problem_lib.standardize_shapes(features) # Model model = registry.model("transformer")(hparams, tf.estimator.ModeKeys.TRAIN) logits, losses = model(features) self.assertTrue("training" in losses) loss = losses["training"] with self.test_session() as sess: sess.run(tf.global_variables_initializer()) logits_val, loss_val = sess.run([logits, loss]) logits_shape = list(logits_val.shape) logits_shape[1] = None self.assertAllEqual(logits_shape, [10, None, 1, 1, 4]) self.assertEqual(loss_val.shape, tuple()) def testMultipleTargetModalities(self): # Use existing hparams and override target modality. hparams = trainer_lib.create_hparams( "transformer_tiny", data_dir=algorithmic.TinyAlgo.data_dir, problem_name="tiny_algo") # Manually turn off sharing. It is not currently supported for multitargets. hparams.shared_embedding_and_softmax_weights = 0 # pylint: disable=line-too-long hparams.problem_hparams.modality = { "targets": hparams.problem_hparams.modality["targets"], "targets_A": hparams.problem_hparams.modality["targets"], "targets_B": hparams.problem_hparams.modality["targets"], } hparams.problem._hparams = hparams.problem_hparams # Dataset problem = hparams.problem dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, algorithmic.TinyAlgo.data_dir) dataset = dataset.repeat(None).padded_batch(10, dataset.output_shapes) features = dataset.make_one_shot_iterator().get_next() features = problem_lib.standardize_shapes(features) features["targets_A"] = features["targets_B"] = features["targets"] # Model model = registry.model("transformer")(hparams, tf.estimator.ModeKeys.TRAIN) def body(args, mb=model.body): out = mb(args) return {"targets": out, "targets_A": out, "targets_B": out} model.body = body logits, losses = model(features) self.assertTrue("training" in losses) loss = losses["training"] with self.test_session() as sess: sess.run(tf.global_variables_initializer()) sess.run([logits, loss]) def testCreateHparams(self): # Get json_path pkg, _ = os.path.split(__file__) pkg, _ = os.path.split(pkg) json_path = os.path.join( pkg, "test_data", "transformer_test_ckpt", "hparams.json") # Create hparams hparams = trainer_lib.create_hparams("transformer_big", "hidden_size=1", hparams_path=json_path) self.assertEqual(2, hparams.num_hidden_layers) # from json self.assertEqual(1, hparams.hidden_size) # from hparams_overrides_str # Compare with base hparams base_hparams = trainer_lib.create_hparams("transformer_big") self.assertEqual(len(base_hparams.values()), len(hparams.values())) def testCreateHparamsFromJson(self): # Get json_path pkg, _ = os.path.split(__file__) pkg, _ = os.path.split(pkg) json_path = os.path.join( pkg, "test_data", "transformer_test_ckpt", "hparams.json") # Create hparams hparams = trainer_lib._create_hparams_from_json(json_path) self.assertEqual(75, len(hparams.values())) if __name__ == "__main__": tf.test.main()
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>windows::basic_stream_handle::close (2 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../close.html" title="windows::basic_stream_handle::close"> <link rel="prev" href="overload1.html" title="windows::basic_stream_handle::close (1 of 2 overloads)"> <link rel="next" href="../get_implementation.html" title="windows::basic_stream_handle::get_implementation"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../close.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../get_implementation.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.windows__basic_stream_handle.close.overload2"></a><a class="link" href="overload2.html" title="windows::basic_stream_handle::close (2 of 2 overloads)">windows::basic_stream_handle::close (2 of 2 overloads)</a> </h5></div></div></div> <p> <span class="emphasis"><em>Inherited from windows::basic_handle.</em></span> </p> <p> Close the handle. </p> <pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">close</span><span class="special">(</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> </pre> <p> This function is used to close the handle. Any asynchronous read or write operations will be cancelled immediately, and will complete with the <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_aborted</span></code> error. </p> <h6> <a name="boost_asio.reference.windows__basic_stream_handle.close.overload2.h0"></a> <span class="phrase"><a name="boost_asio.reference.windows__basic_stream_handle.close.overload2.parameters"></a></span><a class="link" href="overload2.html#boost_asio.reference.windows__basic_stream_handle.close.overload2.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl class="variablelist"> <dt><span class="term">ec</span></dt> <dd><p> Set to indicate what error occurred, if any. </p></dd> </dl> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2014 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../close.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../get_implementation.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
''' Console Widget, used for sending json messages to NOX @author Kyriakos Zarifis ''' from PyQt4 import QtGui, QtCore from communication import ConsoleInterface import simplejson class ConsoleWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.parent = parent # Handle to logDisplay self.logDisplay = self.parent.logWidget.logDisplay # Handle to sqldb ###self.curs = self.parent.logWidget.curs # Configure Widget self.label = QtGui.QLabel('Send JSON command to NOX component') self.consoleEdit = QtGui.QLineEdit() self.consoleEdit.setText("{\"type\":\"lavi\",\"command\":\"request\",\"node_type\":\"all\"}") ''' p = QtGui.QPalette() p.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, QtCore.Qt.black) p.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Base, QtCore.Qt.black) self.consoleEdit.setPalette(p) #self.consoleEdit.setTextColor(QtCore.Qt.darkGreen) ''' sendCmdBtn = QtGui.QPushButton("&Send") self.connect(sendCmdBtn, QtCore.SIGNAL('clicked()'), self.send_cmd) grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(self.label, 1, 0) grid.addWidget(self.consoleEdit, 2, 0) grid.addWidget(sendCmdBtn, 2, 1) self.setLayout(grid) self.consoleInterface = ConsoleInterface(self) def send_cmd(self): self.curs.execute("select distinct component from messages") comps = [] for c in self.curs: comps.append(str(c)[3:len(str(c))-3]) if "jsonmessenger" not in comps: self.parent.logWidget.logDisplay.parent.freezeLog = True self.logDisplay.setText("jsonmessenger is not running") else: cmd = str(self.consoleEdit.text()) valid_json = True try: jsonmsg = simplejson.loads(cmd) except: self.parent.logWidget.logDisplay.parent.freezeLog = True self.logDisplay.setText("invalid json command") valid = False if valid_json: self.consoleInterface.send_cmd(cmd) #self.parent.logWidget.logDisplay.parent.freezeLog = False def keyPressEvent(self, event): key = event.key() if key == QtCore.Qt.Key_Enter: self.send_cmd()
/* Copyright (c) 2015, Lipen */ #include <iostream> #include <vector> #include <limits> #include <iomanip> #include <algorithm> // TAGS: matrix chain order, matrix multiply order, dp, dynamic programming using std::cout; using std::cin; using std::endl; using I = int; using VI = std::vector<I>; using VVI = std::vector<VI>; template<typename T> void show(const std::vector<std::vector<T>> &v, size_t start = 0, size_t width = 5) { size_t n = v.size(); for (size_t i = start; i < n; ++i) { cout << '\t'; for (size_t j = start; j < n; ++j) { cout << std::setw(width) << v[i][j]; } cout << endl; } } void print_optimal_parens(const VVI &s, size_t i, size_t j) { if (i == j) { cout << "A"; if (i == 0) cout << "₀"; else if (i == 1) cout << "₁"; else if (i == 2) cout << "₂"; else if (i == 3) cout << "₃"; else if (i == 4) cout << "₄"; else if (i == 5) cout << "₅"; else if (i == 6) cout << "₆"; else if (i == 7) cout << "₇"; else if (i == 8) cout << "₈"; else if (i == 9) cout << "₉"; else cout << "?"; cout << ""; } else { cout << "("; print_optimal_parens(s, i, s[i][j]); print_optimal_parens(s, s[i][j]+1, j); cout << ")"; } } // Cormen`s void matrix_chain_order(const VI &p, VVI &m, VVI &s) { size_t n = p.size() - 1; cout << "n = " << n << endl; for (size_t l = 2; l <= n; ++l) { for (size_t i = 1; i <= n-l+1; ++i) { size_t j = i + l - 1; m[i][j] = std::numeric_limits<I>::max(); for (size_t k = i; k <= j-1; ++k) { I q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]; if (q < m[i][j]) { m[i][j] = q; s[i][j] = k; } } } } } // Bottom Up dp int matrix_mult_BU(const VI &m) { // m_0 .. m_n (n+1 total) size_t n = m.size() - 1; VVI D(n, VI(n, std::numeric_limits<int>::max())); for (size_t i = 0; i < n; ++i) { D[i][i] = 0; } for (size_t s = 1; s <= n-1; ++s) { for (size_t i = 1; i <= n-s; ++i) { size_t j = i + s; for (size_t k = i; k <= j-1; ++k) { D[i-1][j-1] = std::min( D[i-1][j-1], D[i-1][k-1] + D[k+1-1][j-1] + m[i-1]*m[k]*m[j] ); } } } cout << "D:" << endl; show(D, 0, 10); return D[0][n-1]; } int main() { VI p { 5, 10, 3, 12, 5, 50, 6 }; // VI p { 30, 35, 15, 5, 10, 20, 25 }; // VI p {40, 20, 30, 10, 30}; size_t n = p.size(); VVI m(n, VI(n)); VVI s(n, VI(n)); cout << "matrix_chain_order() .." << endl; matrix_chain_order(p, m, s); cout << "Done." << endl; cout << "Matrix m:" << endl; show(m, 1, 6); cout << "Matrix s:" << endl; show(s, 1, 3); cout << "Optimal multiplications:" << endl; cout << '\t' << m[1][n-1] << endl; cout << "Optimal parens:" << endl; print_optimal_parens(s, 1, n-1); cout << endl; int x = matrix_mult_BU(p); cout << "dp: x = " << x << endl; }
<!DOCTYPE html> <html> <body> <div>A shadow element without an element</div> <div>before1 before0 host-child after0 after1</div> <div>A shadow element with an element</div> <div>before1 before0 host-child after0 after1</div> <div>A shadow element with a content element and an element</div> <div>before1 before0 host-child after0 after1</div> <div>A shadow element as a descendant of a content element</div> <div>before1 host-child after1</div> <div>A shadow element as a descendant of a shadow element</div> <div>before1 before0 host-child after0 after1</div> <div>A complex case</div> <div>before2 before1 before0 host-child after0 after1 after2</div> </body> </html>
# coding=utf-8 """ #------------------------------------------------------------------------------- # Name: FloodRiskExceptions # Purpose: Custom exception classes for the FloodRisk plug-in # # Created: 19/03/2015 # Copyright: (c) RSE 2015 # email: [email protected] #------------------------------------------------------------------------------- /*************************************************************************** * * * 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. * * * ***************************************************************************/ """ class HelpFileMissingError(Exception): """Raised if a help file cannot be found.""" pass
#!/usr/bin/python # # Description: libcollections python extension to be used inside python plugins. # # Author: Rodrigo Freitas # Date: Wed Aug 12 12:56:01 BRT 2015 # # Copyright (C) 2015 Rodrigo Freitas # # 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 library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # USA # """ Libcollections python extension to be used inside python plugins. """ import sys from abc import ABCMeta, abstractmethod VERSION = "0.1" __FUNCTION__ = lambda n=0: sys._getframe(n + 1).f_code.co_name def version(): """ Gets the module version. """ return VERSION class CpluginEntryAPI(object): """ A class to be inherited by the mandatory plugin class named as 'CpluginMainEntry', so that a plugin manager may get all plugin information and its API. """ __metaclass__ = ABCMeta @abstractmethod def get_name(self): """ Function to return the module name. """ pass @abstractmethod def get_version(self): """ Function to return the module version. """ pass @abstractmethod def get_author(self): """ Function to return the module author name. """ pass @abstractmethod def get_description(self): """ Function to return the module description. """ pass @abstractmethod def get_api(self): """ Function to return the module description. """ pass @abstractmethod def get_startup(self): """ Function to return the name of the function called when the plugin is loaded. """ pass @abstractmethod def get_shutdown(self): """ Function to return the name of the function called when the plugin is unloaded. """ pass
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>DIF_LISTWRAPMODE</title> <meta http-equiv="Content-Type" Content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../../../styles/styles.css"> <script language="javascript" src='../../links.js' type="text/javascript"></script> </head> <body> <h1>DIF_LISTWRAPMODE</h1> <div class=navbar> <a href="../../index.html">главная</a> | <a href="index.html">флаги элементов диалога</a> | <a href="../index.html">Dialog API</a> </div> <div class=shortdescr> Если указан <code>DIF_LISTWRAPMODE</code>, то попытка перемещения курсора в списке выше первого пункта или ниже последнего будет приводить к перемещению соответственно к последнему или к первому пункту. </div> <h3>Элементы</h3> <div class=descr> Флаг <code>DIF_LISTWRAPMODE</code> имеет смысл для следующих элементов диалога: <table class="cont"> <tr class="cont"><th class="cont" width="40%">Элемент</th><th class="cont" width="60%">Описание</th></tr> <tr class="cont"><td class="cont" width="40%"><a href="../controls/di_listbox.html">DI_LISTBOX</a></td> <td class="cont" width="60%">список</td></tr> <!-- <tr class="cont"><td class="cont" width="40%"><a href="../controls/di_combobox.html">DI_COMBOBOX</a></td> <td class="cont" width="60%">комбинированный список</td></tr> --> </table> </div> <h3>Замечания</h3> <div class=descr> </div> <div class=see>Смотрите также:</div> <div class=seecont> </div> </body> </html>
<?php /** * @package Joomla * @subpackage Event Booking * @author Tuan Pham Ngoc * @copyright Copyright (C) 2010 - 2021 Ossolution Team * @license GNU/GPL, see LICENSE.php */ defined( '_JEXEC' ) or die; use Joomla\CMS\Language\Text; use Joomla\CMS\Router\Route; ?> <table class="table table-striped table-bordered"> <thead> <tr> <th class="title"><?php echo Text::_('EB_FIRST_NAME')?></th> <th class="title"><?php echo Text::_('EB_LAST_NAME')?></th> <th class="title"><?php echo Text::_('EB_EVENT')?></th> <th class="title"><?php echo Text::_('EB_EMAIL')?></th> <th class="center title"><?php echo Text::_('EB_NUMBER_REGISTRANTS')?></th> </tr> </thead> <tbody> <?php foreach ($this->latestRegistrants as $row) { ?> <tr> <td><a href="<?php echo Route::_('index.php?option=com_eventbooking&view=registrant&id='.(int)$row->id); ?>"><?php echo $row->first_name; ?></a></td> <td><?php echo $row->last_name; ?></td> <td><a href="<?php echo Route::_('index.php?option=com_eventbooking&view=event&id='.(int)$row->event_id); ?>"> <?php echo $row->title; ?></a></td> <td><?php echo $row->email; ?></td> <td class="center"><?php echo $row->number_registrants; ?></td> </tr> <?php } ?> </tbody> </table>
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2013 Steven Lovegrove * * 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. */ #include <pangolin/video/firewire_deinterlace.h> #include <dc1394/conversions.h> namespace pangolin { FirewireDeinterlace::FirewireDeinterlace(VideoInterface* videoin) : videoin(videoin), buffer(0) { if(videoin->Streams().size() != 1) throw VideoException("FirewireDeinterlace input must have exactly one stream"); const StreamInfo& stmin = videoin->Streams()[0]; StreamInfo stm1(VideoFormatFromString("GRAY8"), stmin.Width(), stmin.Height(), stmin.Width(), 0); StreamInfo stm2(VideoFormatFromString("GRAY8"), stmin.Width(), stmin.Height(), stmin.Width(), (unsigned char*)0 + stmin.Width()*stmin.Height()); streams.push_back(stm1); streams.push_back(stm2); buffer = new unsigned char[videoin->SizeBytes()]; std::cout << videoin->Streams()[0].Width() << ", " << videoin->Streams()[0].Height() << std::endl; } FirewireDeinterlace::~FirewireDeinterlace() { delete[] buffer; delete videoin; } size_t FirewireDeinterlace::SizeBytes() const { return videoin->SizeBytes(); } const std::vector<StreamInfo>& FirewireDeinterlace::Streams() const { return streams; } void FirewireDeinterlace::Start() { videoin->Start(); } void FirewireDeinterlace::Stop() { videoin->Stop(); } bool FirewireDeinterlace::GrabNext( unsigned char* image, bool wait ) { if(videoin->GrabNext(buffer, wait)) { return ( dc1394_deinterlace_stereo(buffer,image, videoin->Streams()[0].Width(), 2*videoin->Streams()[0].Height() ) == DC1394_SUCCESS ); } return false; } bool FirewireDeinterlace::GrabNewest( unsigned char* image, bool wait ) { if(videoin->GrabNewest(buffer, wait)) { return ( dc1394_deinterlace_stereo(buffer,image, videoin->Streams()[0].Width(), 2*videoin->Streams()[0].Height() ) == DC1394_SUCCESS ); } return false; } }
{% extends 'dashboard/layout.html' %} {% load currency_filters %} {% load i18n %} {% block body_class %}{{ block.super }} orders home{% endblock %} {% block extrahead %} {{ block.super }} <meta http-equiv="refresh" content="300"> {% endblock %} {% block breadcrumbs %} {% endblock %} {% block headertext %} {% trans "Dashboard" %} {% endblock %} {% block dashboard_content %} <div class='row-fluid'> <div class="span12"> <table class="table table-striped table-bordered table-hover"> <caption> <div class="btn-toolbar pull-right"> <div class="btn-group"> <a href="{% url 'dashboard:catalogue-product-list' %}" class="btn"> <i class="icon-sitemap"></i> {% trans "Manage" %} </a> </div> </div> <i class="icon-sitemap icon-large"></i>{% trans "Catalogue and stock" %} </caption> <tr> <th class="span10">{% trans "Total products" %}</th> <td class="span2" >{{ total_products }}</td> </tr> <tr> <th class="span10">{% trans "<em>Open</em> stock alerts" %}</th> <td class="span2" >{{ total_open_stock_alerts }}</td> </tr> <tr> <th class="span10">{% trans "<em>Closed</em> stock alerts" %}</th> <td class="span2" >{{ total_closed_stock_alerts }}</td> </tr> </table> </div> </div> {% endblock %}
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest, os, base64 from frappe import safe_decode from frappe.email.receive import Email from frappe.email.email_body import (replace_filename_with_cid, get_email, inline_style_in_html, get_header) from frappe.email.queue import get_email_queue from frappe.email.doctype.email_queue.email_queue import SendMailContext from six import PY3 class TestEmailBody(unittest.TestCase): def setUp(self): email_html = ''' <div> <h3>Hey John Doe!</h3> <p>This is embedded image you asked for</p> <img embed="assets/frappe/images/frappe-favicon.svg" /> </div> ''' email_text = ''' Hey John Doe! This is the text version of this email ''' img_path = os.path.abspath('assets/frappe/images/frappe-favicon.svg') with open(img_path, 'rb') as f: img_content = f.read() img_base64 = base64.b64encode(img_content).decode() # email body keeps 76 characters on one line self.img_base64 = fixed_column_width(img_base64, 76) self.email_string = get_email( recipients=['[email protected]'], sender='[email protected]', subject='Test Subject', content=email_html, text_content=email_text ).as_string().replace("\r\n", "\n") def test_prepare_message_returns_already_encoded_string(self): if PY3: uni_chr1 = chr(40960) uni_chr2 = chr(1972) else: uni_chr1 = unichr(40960) uni_chr2 = unichr(1972) email = get_email_queue( recipients=['[email protected]'], sender='[email protected]', subject='Test Subject', content='<h1>' + uni_chr1 + 'abcd' + uni_chr2 + '</h1>', formatted='<h1>' + uni_chr1 + 'abcd' + uni_chr2 + '</h1>', text_content='whatever') mail_ctx = SendMailContext(queue_doc = email) result = mail_ctx.build_message(recipient_email = '[email protected]') self.assertTrue(b"<h1>=EA=80=80abcd=DE=B4</h1>" in result) def test_prepare_message_returns_cr_lf(self): email = get_email_queue( recipients=['[email protected]'], sender='[email protected]', subject='Test Subject', content='<h1>\n this is a test of newlines\n' + '</h1>', formatted='<h1>\n this is a test of newlines\n' + '</h1>', text_content='whatever') mail_ctx = SendMailContext(queue_doc = email) result = safe_decode(mail_ctx.build_message(recipient_email='[email protected]')) if PY3: self.assertTrue(result.count('\n') == result.count("\r")) else: self.assertTrue(True) def test_image(self): img_signature = ''' Content-Type: image/svg+xml MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: inline; filename="frappe-favicon.svg" ''' self.assertTrue(img_signature in self.email_string) self.assertTrue(self.img_base64 in self.email_string) def test_text_content(self): text_content = ''' Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Hey John Doe! This is the text version of this email ''' self.assertTrue(text_content in self.email_string) def test_email_content(self): html_head = ''' Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.= w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns=3D"http://www.w3.org/1999/xhtml"> ''' html = '''<h3>Hey John Doe!</h3>''' self.assertTrue(html_head in self.email_string) self.assertTrue(html in self.email_string) def test_replace_filename_with_cid(self): original_message = ''' <div> <img embed="assets/frappe/images/frappe-favicon.svg" alt="test" /> <img embed="notexists.jpg" /> </div> ''' message, inline_images = replace_filename_with_cid(original_message) processed_message = ''' <div> <img src="cid:{0}" alt="test" /> <img /> </div> '''.format(inline_images[0].get('content_id')) self.assertEqual(message, processed_message) def test_inline_styling(self): html = ''' <h3>Hi John</h3> <p>This is a test email</p> ''' transformed_html = ''' <h3>Hi John</h3> <p style="margin:5px 0 !important">This is a test email</p> ''' self.assertTrue(transformed_html in inline_style_in_html(html)) def test_email_header(self): email_html = ''' <h3>Hey John Doe!</h3> <p>This is embedded image you asked for</p> ''' email_string = get_email( recipients=['[email protected]'], sender='[email protected]', subject='Test Subject', content=email_html, header=['Email Title', 'green'] ).as_string().replace("\r\n", "\n") # REDESIGN-TODO: Add style for indicators in email self.assertTrue('''<span class=3D"indicator indicator-green"></span>''' in email_string) self.assertTrue('<span>Email Title</span>' in email_string) def test_get_email_header(self): html = get_header(['This is test', 'orange']) self.assertTrue('<span class="indicator indicator-orange"></span>' in html) self.assertTrue('<span>This is test</span>' in html) html = get_header(['This is another test']) self.assertTrue('<span>This is another test</span>' in html) html = get_header('This is string') self.assertTrue('<span>This is string</span>' in html) def test_8bit_utf_8_decoding(self): text_content_bytes = b"\xed\x95\x9c\xea\xb8\x80\xe1\xa5\xa1\xe2\x95\xa5\xe0\xba\xaa\xe0\xa4\x8f" text_content = text_content_bytes.decode('utf-8') content_bytes = b"""MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: 8bit From: [email protected] Reply-To: [email protected] """ + text_content_bytes mail = Email(content_bytes) self.assertEqual(mail.text_content, text_content) def fixed_column_width(string, chunk_size): parts = [string[0 + i:chunk_size + i] for i in range(0, len(string), chunk_size)] return '\n'.join(parts)
using System; namespace Server.Items { [Flipable( 0xC24, 0xC25 )] public class BrokenChestOfDrawersComponent : AddonComponent { public override int LabelNumber { get { return 1076261; } } // Broken Chest of Drawers public BrokenChestOfDrawersComponent() : base( 0xC24 ) { } public BrokenChestOfDrawersComponent( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class BrokenChestOfDrawersAddon : BaseAddon { public override BaseAddonDeed Deed { get { return new BrokenChestOfDrawersDeed(); } } [Constructable] public BrokenChestOfDrawersAddon() : base() { AddComponent( new BrokenChestOfDrawersComponent(), 0, 0, 0 ); } public BrokenChestOfDrawersAddon( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } public class BrokenChestOfDrawersDeed : BaseAddonDeed { public override BaseAddon Addon { get { return new BrokenChestOfDrawersAddon(); } } public override int LabelNumber { get { return 1076261; } } // Broken Chest of Drawers [Constructable] public BrokenChestOfDrawersDeed() : base() { LootType = LootType.Blessed; } public BrokenChestOfDrawersDeed( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } }
using System; using System.Diagnostics.CodeAnalysis; using NUnit.Framework; namespace NetOffice.Tests.NetOffice { [TestFixture] public class StringExTests { [Test] [TestCase("AssemblyName.resources")] [TestCase("AssemblyName.RESOURCES")] [TestCase("AssemblyName.resources, Version=1.0.0.0, Culture=en-US")] [SuppressMessage("ReSharper", "InvokeAsExtensionMethod")] public void ContainsIgnoreCase_MatchingString_ReturnsTrue(string text) { // Arrange // Act bool actualResult = StringEx.ContainsIgnoreCase(text, ".resources"); // Assert Assert.IsTrue(actualResult); } [Test] public void ContainsIgnoreCase_ExtensionMethod_CanBeCalled() { // Arrange string text = "Sample Text"; // Act bool actualResult = text.ContainsIgnoreCase("sample"); // Assert Assert.IsTrue(actualResult); } [Test] [SuppressMessage("ReSharper", "InvokeAsExtensionMethod")] public void ContainsIgnoreCase_NullParameter_ReturnsFalse() { // Arrange // Act bool actualResult = StringEx.ContainsIgnoreCase(null, ".resources"); // Assert Assert.IsFalse(actualResult); } [Test] [SuppressMessage("ReSharper", "InvokeAsExtensionMethod")] public void ContainsIgnoreCase_EmptyStringParameter_ReturnsFalse() { // Arrange // Act bool actualResult = StringEx.ContainsIgnoreCase(String.Empty, ".resources"); // Assert Assert.IsFalse(actualResult); } } }
/* * Copyright (c) 2010 by Cristian Maglie <[email protected]> * * This file is free software; you can redistribute it and/or modify * it under the terms of either the GNU General Public License version 2 * or the GNU Lesser General Public License version 2.1, both as * published by the Free Software Foundation. */ #include <stdio.h> #include <string.h> #include "w5100.h" // W5100 controller instance W5100Class W5100; #define TX_RX_MAX_BUF_SIZE 2048 #define TX_BUF 0x1100 #define RX_BUF (TX_BUF + TX_RX_MAX_BUF_SIZE) #define TXBUF_BASE 0x4000 #define RXBUF_BASE 0x6000 void W5100Class::init(void) { delay(300); #if defined(ARDUINO_ARCH_AVR) SPI.begin(); initSS(); #else SPI.begin(SPI_CS); // Set clock to 4Mhz (W5100 should support up to about 14Mhz) SPI.setClockDivider(SPI_CS, 21); SPI.setDataMode(SPI_CS, SPI_MODE0); #endif SPI.beginTransaction(SPI_ETHERNET_SETTINGS); writeMR(1<<RST); writeTMSR(0x55); writeRMSR(0x55); SPI.endTransaction(); for (int i=0; i<MAX_SOCK_NUM; i++) { SBASE[i] = TXBUF_BASE + SSIZE * i; RBASE[i] = RXBUF_BASE + RSIZE * i; } } uint16_t W5100Class::getTXFreeSize(SOCKET s) { uint16_t val=0, val1=0; do { val1 = readSnTX_FSR(s); if (val1 != 0) val = readSnTX_FSR(s); } while (val != val1); return val; } uint16_t W5100Class::getRXReceivedSize(SOCKET s) { uint16_t val=0,val1=0; do { val1 = readSnRX_RSR(s); if (val1 != 0) val = readSnRX_RSR(s); } while (val != val1); return val; } void W5100Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len) { // This is same as having no offset in a call to send_data_processing_offset send_data_processing_offset(s, 0, data, len); } void W5100Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len) { uint16_t ptr = readSnTX_WR(s); ptr += data_offset; uint16_t offset = ptr & SMASK; uint16_t dstAddr = offset + SBASE[s]; if (offset + len > SSIZE) { // Wrap around circular buffer uint16_t size = SSIZE - offset; write(dstAddr, data, size); write(SBASE[s], data + size, len - size); } else { write(dstAddr, data, len); } ptr += len; writeSnTX_WR(s, ptr); } void W5100Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek) { uint16_t ptr; ptr = readSnRX_RD(s); read_data(s, ptr, data, len); if (!peek) { ptr += len; writeSnRX_RD(s, ptr); } } void W5100Class::read_data(SOCKET s, volatile uint16_t src, volatile uint8_t *dst, uint16_t len) { uint16_t size; uint16_t src_mask; uint16_t src_ptr; src_mask = src & RMASK; src_ptr = RBASE[s] + src_mask; if( (src_mask + len) > RSIZE ) { size = RSIZE - src_mask; read(src_ptr, (uint8_t *)dst, size); dst += size; read(RBASE[s], (uint8_t *) dst, len - size); } else read(src_ptr, (uint8_t *) dst, len); } uint8_t W5100Class::write(uint16_t _addr, uint8_t _data) { #if defined(ARDUINO_ARCH_AVR) setSS(); SPI.transfer(0xF0); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); SPI.transfer(_data); resetSS(); #else SPI.transfer(SPI_CS, 0xF0, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE); SPI.transfer(SPI_CS, _data); #endif return 1; } uint16_t W5100Class::write(uint16_t _addr, const uint8_t *_buf, uint16_t _len) { for (uint16_t i=0; i<_len; i++) { #if defined(ARDUINO_ARCH_AVR) setSS(); SPI.transfer(0xF0); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); _addr++; SPI.transfer(_buf[i]); resetSS(); #else SPI.transfer(SPI_CS, 0xF0, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE); SPI.transfer(SPI_CS, _buf[i]); _addr++; #endif } return _len; } uint8_t W5100Class::read(uint16_t _addr) { #if defined(ARDUINO_ARCH_AVR) setSS(); SPI.transfer(0x0F); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); uint8_t _data = SPI.transfer(0); resetSS(); #else SPI.transfer(SPI_CS, 0x0F, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE); uint8_t _data = SPI.transfer(SPI_CS, 0); #endif return _data; } uint16_t W5100Class::read(uint16_t _addr, uint8_t *_buf, uint16_t _len) { for (uint16_t i=0; i<_len; i++) { #if defined(ARDUINO_ARCH_AVR) setSS(); SPI.transfer(0x0F); SPI.transfer(_addr >> 8); SPI.transfer(_addr & 0xFF); _addr++; _buf[i] = SPI.transfer(0); resetSS(); #else SPI.transfer(SPI_CS, 0x0F, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE); SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE); _buf[i] = SPI.transfer(SPI_CS, 0); _addr++; #endif } return _len; } void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) { // Send command to socket writeSnCR(s, _cmd); // Wait for command to complete while (readSnCR(s)) ; }
#! /usr/bin/python # -*- coding: utf-8 -*- from utils import set_ams, config_loop, start_loop, display_message config_loop(gui=True) from agent import Agent from messages import ACLMessage from protocols import FipaContractNetProtocol from aid import AID from pickle import dumps, loads class InitiatorProtocol(FipaContractNetProtocol): def __init__(self, agent, message): super(InitiatorProtocol, self).__init__(agent, message, is_initiator=True) def handle_propose(self, message): FipaContractNetProtocol.handle_propose(self, message) display_message(self.agent.aid.name, loads(message.content)) def handle_refuse(self, message): FipaContractNetProtocol.handle_refuse(self, message) display_message(self.agent.aid.name, loads(message.content)) def handle_all_proposes(self, proposes): FipaContractNetProtocol.handle_all_proposes(self, proposes) display_message(self.agent.aid.name, 'Analisando Propostas...') better_propose = loads(proposes[0].content) better_propositor = proposes[0] for propose in proposes: power_value = loads(propose.content) if power_value['value'] > better_propose['value']: better_propose = power_value better_propositor = propose response_1 = better_propositor.create_reply() response_1.set_performative(ACLMessage.ACCEPT_PROPOSAL) response_1.set_content('Proposta ACEITA') self.agent.send(response_1) for propose in proposes: if propose != better_propositor: response = propose.create_reply() response.set_performative(ACLMessage.REJECT_PROPOSAL) response.set_content('Proposta RECUSADA') self.agent.send(response) def handle_inform(self, message): FipaContractNetProtocol.handle_inform(self, message) display_message(self.agent.aid.name, message.content) class ParticipantProtocol(FipaContractNetProtocol): def __init__(self, agent, power_values): super(ParticipantProtocol,self).__init__(agent, is_initiator=False) self.power_values = power_values def handle_cfp(self, message): FipaContractNetProtocol.handle_cfp(self, message) display_message(self.agent.aid.name, loads(message.content)) response = message.create_reply() response.set_performative(ACLMessage.PROPOSE) response.set_content(dumps(self.power_values)) self.agent.send(response) def handle_accept_propose(self, message): FipaContractNetProtocol.handle_accept_propose(self, message) response = message.create_reply() response.set_performative(ACLMessage.INFORM) response.set_content('RECOMPOSICAO AUTORIZADA') self.agent.send(response) display_message(self.agent.aid.name, message.content) def handle_reject_proposes(self, message): FipaContractNetProtocol.handle_reject_proposes(self, message) display_message(self.agent.aid.name, message.content) class InitiatorAgent(Agent): def __init__(self, aid): Agent.__init__(self, aid) pedido = {'tipo' : 'pedido', 'qtd' : 100.0} message = ACLMessage(ACLMessage.CFP) message.set_protocol(ACLMessage.FIPA_CONTRACT_NET_PROTOCOL) message.set_content(dumps(pedido)) message.add_receiver('participant_agent_1') message.add_receiver('participant_agent_2') behaviour = InitiatorProtocol(self, message) self.addBehaviour(behaviour) class ParticipantAgent(Agent): def __init__(self, aid, power_values): Agent.__init__(self, aid) behaviour = ParticipantProtocol(self, power_values) self.addBehaviour(behaviour) if __name__ == '__main__': set_ams('localhost', 8000) agent_participant_1 = ParticipantAgent(AID('participant_agent_1'), {'value' : 100.0}) agent_participant_1.set_ams('localhost', 8000) agent_participant_1.start() agent_participant_2 = ParticipantAgent(AID('participant_agent_2'), {'value' : 200.0}) agent_participant_2.set_ams('localhost', 8000) agent_participant_2.start() agent_initiator = InitiatorAgent(AID('initiator_agent')) agent_initiator.set_ams('localhost', 8000) agent_initiator.start() start_loop()
# @file Math Reverse Integer # @brief Given a 32-bit signed integer, reverse digits of an integer. # https://leetcode.com/problems/reverse-integer/ ''' Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' # Approach 1: Math # time: O(n) # space: # Understand this as dequeue the last digit each time from input and enqueue the last digit into ans # Dequeue: use mod to peek at the last digit and division by base(10) to shift number to right # Enqueue: use multiply by base(10) to make space (shift to left) and addition to insert the last digit # Overflows: Use the max_int and check if addition or multiplication can cause overflow def reverse(self, x): maxInt = 2**31-1 # Maximum positive integer ans = 0 sign = -1 if x < 0 else 1 x = sign * x # Convert negative x to positive x while x: x, lastDigit = x // 10, x % 10 # ans = ans * 10 + lastDigit (with overflow checks) # Do ans = ans * 10 while checking for overflow (a * 10 <= max ---- a <= max / 10) if ans <= maxInt // 10: ans *= 10 else: return 0 # Do ans += lastDigit while checking overflow (a + 10 <= max ---- a <= max - 10) if ans <= maxInt - lastDigit: ans += lastDigit else: return 0 return sign * ans # Approach 2: convert to string def reverse(self, x): sign = 1 if x < 0: sign = -1 x = sign * x return sign * int(str(x)[::-1])
#include <mysql.h> //@func:求三个数的最小值 unsigned min(unsigned x,unsigned y,unsigned z ) { unsigned tmp=(x<y ? x:y); tmp=(tmp<z ? tmp:z); return tmp; } //@func:计算字符串s 和 t之间的levenshtein距离 //@paras:s和t均为c风格字符串 unsigned lev_distance(const char * s,const char *t) { //n:目标单词t的长度 m:源单词s的长度 unsigned m_tmp=0,n_tmp=0; int i=0; //计算源单词长度 while(s[i]) { i++; m_tmp++; } //计算目标单词长度 i=0; while(t[i]) { i++; n_tmp++; } if(m_tmp==0) return n_tmp; if(n_tmp==0) return m_tmp; const unsigned m=m_tmp+1; const unsigned n=n_tmp+1; unsigned matrix[m][n]; //给矩阵的第0行和第0列赋值 for(i=0;i<m;i++) matrix[i][0]=i; for(i=0;i<n;i++) matrix[0][i]=i; //填充矩阵的其他元素,逐行填充 int j; for(i=1;i<m;i++) for(j=1;j<n;j++) { unsigned cost=1; if(s[i-1]==t[j-1]) cost=0; matrix[i][j]=min(matrix[i-1][j]+1,matrix[i][j-1]+1,matrix[i-1][j-1]+cost); } //返回matrix[m-1][n-1],即两个字符串之间的距离 return matrix[m-1][n-1]; } extern "C" unsigned levenshtein(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) { unsigned dis = lev_distance(args->args[0],args->args[1]); return dis; } extern "C" my_bool levenshtein_init(UDF_INIT *initid, UDF_ARGS *args, char *message) { return 0; }
#!/usr/bin/env python import numpy as np import os import tensorflow as tf from tensorflow.contrib.session_bundle import exporter import time flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer("batch_size", 10, "The batch size to train") flags.DEFINE_integer("epoch_number", 10, "Number of epochs to run trainer") flags.DEFINE_integer("steps_to_validate", 1, "Steps to validate and print loss") flags.DEFINE_string("checkpoint_dir", "./checkpoint/", "indicates the checkpoint dirctory") flags.DEFINE_string("model_path", "./model/", "The export path of the model") flags.DEFINE_integer("export_version", 1, "The version number of the model") def main(): # Define training data x = np.ones(FLAGS.batch_size) y = np.ones(FLAGS.batch_size) # Define the model X = tf.placeholder(tf.float32, shape=[None], name="X") Y = tf.placeholder(tf.float32, shape=[None], name="yhat") w = tf.Variable(1.0, name="weight") b = tf.Variable(1.0, name="bias") loss = tf.square(Y - tf.mul(X, w) - b) train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss) predict_op = tf.mul(X, w) + b saver = tf.train.Saver() checkpoint_dir = FLAGS.checkpoint_dir checkpoint_file = checkpoint_dir + "/checkpoint.ckpt" if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) # Start the session with tf.Session() as sess: sess.run(tf.initialize_all_variables()) ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: print("Continue training from the model {}".format(ckpt.model_checkpoint_path)) saver.restore(sess, ckpt.model_checkpoint_path) saver_def = saver.as_saver_def() print(saver_def.filename_tensor_name) print(saver_def.restore_op_name) # Start training start_time = time.time() for epoch in range(FLAGS.epoch_number): sess.run(train_op, feed_dict={X: x, Y: y}) # Start validating if epoch % FLAGS.steps_to_validate == 0: end_time = time.time() print("[{}] Epoch: {}".format(end_time - start_time, epoch)) saver.save(sess, checkpoint_file) tf.train.write_graph(sess.graph_def, checkpoint_dir, 'trained_model.pb', as_text=False) tf.train.write_graph(sess.graph_def, checkpoint_dir, 'trained_model.txt', as_text=True) start_time = end_time # Print model variables w_value, b_value = sess.run([w, b]) print("The model of w: {}, b: {}".format(w_value, b_value)) # Export the model print("Exporting trained model to {}".format(FLAGS.model_path)) model_exporter = exporter.Exporter(saver) model_exporter.init( sess.graph.as_graph_def(), named_graph_signatures={ 'inputs': exporter.generic_signature({"features": X}), 'outputs': exporter.generic_signature({"prediction": predict_op}) }) model_exporter.export(FLAGS.model_path, tf.constant(FLAGS.export_version), sess) print('Done exporting!') if __name__ == "__main__": main()
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/waf/model/GeoMatchSetSummary.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WAF { namespace Model { GeoMatchSetSummary::GeoMatchSetSummary() : m_geoMatchSetIdHasBeenSet(false), m_nameHasBeenSet(false) { } GeoMatchSetSummary::GeoMatchSetSummary(JsonView jsonValue) : m_geoMatchSetIdHasBeenSet(false), m_nameHasBeenSet(false) { *this = jsonValue; } GeoMatchSetSummary& GeoMatchSetSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("GeoMatchSetId")) { m_geoMatchSetId = jsonValue.GetString("GeoMatchSetId"); m_geoMatchSetIdHasBeenSet = true; } if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } return *this; } JsonValue GeoMatchSetSummary::Jsonize() const { JsonValue payload; if(m_geoMatchSetIdHasBeenSet) { payload.WithString("GeoMatchSetId", m_geoMatchSetId); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } return payload; } } // namespace Model } // namespace WAF } // namespace Aws
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import datetime import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from zipfile import ZipFile, is_zipfile from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from import_export.utils import import_file class Command(BaseCommand): help = "Import a translation file or a zip of translation files. " \ "X-Pootle-Path header must be present." def add_arguments(self, parser): parser.add_argument( "file", nargs="+", help="file to import" ) parser.add_argument( "--user", action="store", dest="user", help="Import translations as USER", ) def handle(self, **options): user = None if options["user"] is not None: User = get_user_model() try: user = User.objects.get(username=options["user"]) self.stdout.write( 'User %s will be set as author of the import.' % user.username) except User.DoesNotExist: raise CommandError("Unrecognised user: %s" % options["user"]) start = datetime.datetime.now() for filename in options['file']: self.stdout.write('Importing %s...' % filename) if not os.path.isfile(filename): raise CommandError("No such file '%s'" % filename) if is_zipfile(filename): with ZipFile(filename, "r") as zf: for path in zf.namelist(): with zf.open(path, "r") as f: if path.endswith("/"): # is a directory continue try: import_file(f, user=user) except Exception as e: self.stderr.write("Warning: %s" % (e)) else: with open(filename, "r") as f: try: import_file(f, user=user) except Exception as e: raise CommandError(e) end = datetime.datetime.now() self.stdout.write('All done in %s.' % (end - start))
// Import Tinytest from the tinytest Meteor package. import { Tinytest } from "meteor/tinytest"; // Import and rename a variable exported by mongo-counter.js. import { name as packageName } from "meteor/mongo-counter"; // Write your tests here! // Here is an example. Tinytest.add('mongo-counter - example', function (test) { test.equal(packageName, "mongo-counter"); });
# coding=utf-8 import luigi import os import sys import inspect import re import pickle import unicodedata import shutil from textract import * from textclean import clean_text, remove_stopwords, remove_accents # Input PDF directory class InputPDF(luigi.ExternalTask): filename = luigi.Parameter() def output(self): return luigi.LocalTarget(self.filename) # Extract raw text class ReadText(luigi.Task): '''Extraer texto de los PDFs de un libro, pegarlos en un solo archivo en formato crudo y guardar el resultado''' book_name = luigi.Parameter() # Nombre del libro pdf_dir = luigi.Parameter() # Carpeta de PDFs txt_dir = luigi.Parameter() # Carpeta de textos #jpg_dir = luigi.Parameter() # Carpeta de JPGs #image_meta_dir = luigi.Parameter() # Carpeta con archivos de metadatos para definir qué archivos son imágenes meta_dir = luigi.Parameter(default='meta') # Nombre del archivo de metadatos meta_file = luigi.Parameter(default='librosAgregados.tm') # Nombre del archivo de metadatos libro-idioma def requires(self): pdf_bookdir = os.path.join(self.pdf_dir, self.book_name) return InputPDF(pdf_bookdir) def output(self): return luigi.LocalTarget(os.path.join(self.txt_dir,self.meta_dir,self.book_name+'.meta')) def run(self): # Extraer textos ruta_pdfs = self.input().path rutaVolumenes = obtener_rutas(ruta_pdfs, extension='.pdf') contenido = convertirVolumenes(rutaVolumenes) idioma = detectarIdioma(contenido) lang_path = os.path.join(self.txt_dir,idioma) save_content(lang_path, self.book_name, contenido) # Guardar los metadatos with self.output().open('w') as f: f.write(idioma) guardarMetadatos(self.book_name,idioma, os.path.join(self.txt_dir),self.meta_file) # Clean text class CleanText(luigi.Task): '''Limpiar el texto de un libro según el nivel de limpieza deseado y guardarlo en su carpeta correspondiente''' book_name = luigi.Parameter() pdf_dir = luigi.Parameter() txt_dir = luigi.Parameter() # jpg_dir = luigi.Parameter() # image_meta_dir = luigi.Parameter() meta_dir = luigi.Parameter(default='meta') meta_file = luigi.Parameter(default='librosAgregados.tm') clean_level = luigi.Parameter(default='raw,clean,stopwords') # Nivel de limpieza. Cualquier combinación de 'raw', 'clean' y 'stopwords', separados por comas def requires(self): return ReadText(book_name = self.book_name, pdf_dir = self.pdf_dir, txt_dir = os.path.join(self.txt_dir, 'raw'), # jpg_dir = self.jpg_dir, # image_meta_dir = self.image_meta_dir, meta_dir = self.meta_dir, meta_file = self.meta_file) def output(self): flags = self.clean_level.split(',') if not ('raw' in flags or 'clean' in flags): print 'WARNING: No cleaning flags defined. Defaulting to raw format only...' flags = ['raw'] metafiles = {kind:os.path.join(self.txt_dir,kind,'meta',self.book_name+'.meta') for kind in flags} return {kind:luigi.LocalTarget(path) for kind, path in metafiles.iteritems()} def run(self): flags = self.output().keys() if flags == ['raw']: print 'No hacemos limpieza de %s' % (self.book_name) # Leemos el idioma de los metadatos with self.input().open('r') as f: idioma = f.read() if 'clean' in flags: # Leemos el contenido crudo with open(os.path.join(self.txt_dir,'raw',idioma,self.book_name+'.txt'), 'r') as f: contenido = f.read() contenido = clean_text(contenido) lang_path = os.path.join(self.txt_dir,'clean',idioma) save_content(lang_path, self.book_name, contenido) if 'stopwords' in flags: contenido = remove_stopwords(contenido, idioma) lang_path = os.path.join(self.txt_dir,'stopwords',idioma) save_content(lang_path, self.book_name, contenido) elif 'stopwords' in flags: print 'WARNING: Cannot remove stopwords without cleaning first. Ommiting "stopwords" flag.' # Guardar los metadatos for kind, o in self.output().iteritems(): with o.open('w') as f: f.write(idioma) guardarMetadatos(self.book_name,idioma, os.path.join(self.txt_dir,kind),self.meta_file) # Detect languages and write language metadata. Possibly obsolete class DetectLanguages(luigi.Task): '''Detectar idiomas de los libros y escribir archivo con los nombres de todos los idiomas detectados''' pdf_dir = luigi.Parameter() txt_dir = luigi.Parameter() # jpg_dir = luigi.Parameter() # image_meta_dir = luigi.Parameter() meta_dir = luigi.Parameter(default='meta') meta_file = luigi.Parameter(default='librosAgregados.tm') lang_file = luigi.Parameter(default='idiomas.tm') clean_level = luigi.Parameter(default='raw,clean,stopwords') def requires(self): return [CleanText(book_name=book_name, pdf_dir=self.pdf_dir, txt_dir=self.txt_dir, # jpg_dir = self.jpg_dir, # image_meta_dir = self.image_meta_dir, meta_dir=self.meta_dir, meta_file=self.meta_file, clean_level=self.clean_level) for book_name in os.listdir(self.pdf_dir)] def output(self): flags = self.input()[0].keys() metapath = os.path.join(self.txt_dir,self.lang_file) return { 'langs':{ kind:luigi.LocalTarget(os.path.join(self.txt_dir,kind,self.lang_file)) for kind in flags }, 'files':self.input() } def run(self): for kind, target in self.output()['langs'].iteritems(): idiomas = set() txt_kind_meta_dir = os.path.join(self.txt_dir,kind,self.meta_dir) for p in os.listdir(txt_kind_meta_dir): p = os.path.join(txt_kind_meta_dir, p) with open(p, 'r') as f: idiomas.add(f.read()) idiomas = list(idiomas) # Metadatos de salida with target.open('w') as f: f.write('\n'.join(idiomas))
#include "WASAPIWrapper.h" const CLSID WASAPIWrapper::CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID WASAPIWrapper::IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); IMMDeviceEnumerator* WASAPIWrapper::pEnumerator = NULL; IMMDevice* WASAPIWrapper::pDevice = NULL; IAudioSessionManager2* WASAPIWrapper::pSessionManager = NULL; IAudioSessionEnumerator* WASAPIWrapper::pSessionEnumerator = NULL; int WASAPIWrapper::sessionCount = 0; float WASAPIWrapper::PreviousVolumeLevel = 0.05f; bool WASAPIWrapper::ChangeForegroundAppVolume(float value, bool addValue) { HRESULT hr = S_OK; IAudioSessionControl* pSessionControl = NULL; IAudioSessionControl2* pSessionControl2 = NULL; AudioSessionState* pSessionState = NULL; ISimpleAudioVolume* pVolume = NULL; DWORD processId; float volumeLevel; WASAPIWrapper::Setup(); // get active window and its process id DWORD foregroundAppProcessId; GetWindowThreadProcessId(GetForegroundWindow(), &foregroundAppProcessId); // iterate over sessions for (int i = 0; i < sessionCount; i++) { hr = pSessionEnumerator->GetSession(i, &pSessionControl); if (FAILED(hr)) { WASAPIWrapper::Reset(); SAFE_RELEASE(pSessionControl); return false; } hr = pSessionControl->QueryInterface(__uuidof(IAudioSessionControl2), (void**)&pSessionControl2); if (FAILED(hr)) { WASAPIWrapper::Reset(); SAFE_RELEASE(pSessionControl); SAFE_RELEASE(pSessionControl2); return false; } // don't check if it's system sounds if (pSessionControl2->IsSystemSoundsSession() == S_FALSE) { hr = pSessionControl2->GetProcessId(&processId); if (FAILED(hr)) { WASAPIWrapper::Reset(); SAFE_RELEASE(pSessionControl); SAFE_RELEASE(pSessionControl2); return false; } if (processId == foregroundAppProcessId) { hr = pSessionControl2->QueryInterface(_uuidof(ISimpleAudioVolume), (void**)&pVolume); if (FAILED(hr)) { WASAPIWrapper::Reset(); SAFE_RELEASE(pSessionControl); SAFE_RELEASE(pSessionControl2); SAFE_RELEASE(pVolume); return false; } // get volume level hr = pVolume->GetMasterVolume(&volumeLevel); if (FAILED(hr)) { WASAPIWrapper::Reset(); SAFE_RELEASE(pSessionControl); SAFE_RELEASE(pSessionControl2); SAFE_RELEASE(pVolume); return false; } // if value is meant as absolute value reset the base if (addValue) { volumeLevel += value; } else { // save old value WASAPIWrapper::PreviousVolumeLevel = volumeLevel; volumeLevel = value; } // set volume hr = pVolume->SetMasterVolume(max(0.0f, volumeLevel), 0); // free loop resources SAFE_RELEASE(pVolume); } } SAFE_RELEASE(pSessionControl); SAFE_RELEASE(pSessionControl2); } WASAPIWrapper::Reset(); return false; } float WASAPIWrapper::GetPreviousVolumeLevel() { return WASAPIWrapper::PreviousVolumeLevel; } WASAPIWrapper::WASAPIWrapper() { } WASAPIWrapper::~WASAPIWrapper() { } bool WASAPIWrapper::Setup() { HRESULT hr = S_OK; hr = CoCreateInstance(WASAPIWrapper::CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, WASAPIWrapper::IID_IMMDeviceEnumerator, (void**)&WASAPIWrapper::pEnumerator); if (FAILED(hr)) { WASAPIWrapper::Reset(); return false; } // get default audio device hr = WASAPIWrapper::pEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &WASAPIWrapper::pDevice); if (FAILED(hr)) { WASAPIWrapper::Reset(); return false; } // get session manager hr = WASAPIWrapper::pDevice->Activate(__uuidof(IAudioSessionManager2), CLSCTX_ALL, NULL, (void**)&WASAPIWrapper::pSessionManager); if (FAILED(hr)) { WASAPIWrapper::Reset(); return false; } // get session enumerator hr = WASAPIWrapper::pSessionManager->GetSessionEnumerator(&WASAPIWrapper::pSessionEnumerator); if (FAILED(hr)) { WASAPIWrapper::Reset(); return false; } // get session count hr = WASAPIWrapper::pSessionEnumerator->GetCount(&WASAPIWrapper::sessionCount); if (FAILED(hr)) { WASAPIWrapper::Reset(); return false; } return true; } void WASAPIWrapper::Reset() { SAFE_RELEASE(WASAPIWrapper::pEnumerator); SAFE_RELEASE(WASAPIWrapper::pDevice); SAFE_RELEASE(WASAPIWrapper::pSessionManager); SAFE_RELEASE(WASAPIWrapper::pSessionEnumerator); WASAPIWrapper::sessionCount = 0; }
import gtk.gdk, time, os import sys import pyautogui import cv2 import numpy as np # Take a screenshot, format it as a grayscale OpenCV image and return. def screencap(): try: img_width = gtk.gdk.screen_width() img_height = gtk.gdk.screen_height() screencap = gtk.gdk.Pixbuf( gtk.gdk.COLORSPACE_RGB, False, 8, img_width, img_height ) screencap.get_from_drawable( gtk.gdk.get_default_root_window(), gtk.gdk.colormap_get_system(), 0, 0, 0, 0, img_width, img_height ) except: print("Failed taking screenshot") exit() img_arr = screencap.get_pixels_array() image = cv2.cvtColor(img_arr, cv2.COLOR_BGR2GRAY) return image if __name__ == '__main__': # Pass the cascade.xml file as an argument. cascPath = sys.argv[1] villagerCascade = cv2.CascadeClassifier(cascPath) # Continuously take screenshots and process them, looking for objects. while(True): image = screencap() # To be detected, villager must be at least 50x80. villagers = villagerCascade.detectMultiScale( image, scaleFactor=1.1, minNeighbors=25, minSize=(50,80), ) # Check if any villagers were detected. If so, just press 'b' for 100ms. if len(villagers) > 0: # Commented out the rectangle drawing part # for (x, y, w, h) in villagers: # cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) # cv2.imshow("Villagers", image) # cv2.waitKey(0) pyautogui.keyDown('b') time.sleep(0.1) pyautogui.keyUp('b') time.sleep(0.02)
<?php declare(strict_types=1); /** * This file is part of the Happyr Doctrine Specification package. * * (c) Tobias Nyholm <[email protected]> * Kacper Gunia <[email protected]> * Peter Gribanov <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Happyr\DoctrineSpecification\Filter; use Doctrine\ORM\QueryBuilder; use Happyr\DoctrineSpecification\Operand\ArgumentToOperandConverter; use Happyr\DoctrineSpecification\Operand\Operand; final class MemberOfX implements Filter { /** * @var Operand|string */ private $field; /** * @var Operand|string */ private $value; /** * @var string|null */ private $context; /** * @param Operand|mixed $value * @param Operand|string $field * @param string|null $context */ public function __construct($value, $field, ?string $context = null) { $this->value = $value; $this->field = $field; $this->context = $context; } /** * @param QueryBuilder $qb * @param string $context * * @return string */ public function getFilter(QueryBuilder $qb, string $context): string { if (null !== $this->context) { $context = sprintf('%s.%s', $context, $this->context); } $field = ArgumentToOperandConverter::toField($this->field); $value = ArgumentToOperandConverter::toValue($this->value); return (string) $qb->expr()->isMemberOf( $value->transform($qb, $context), $field->transform($qb, $context) ); } }
export * from './manpowerTable.component';
import os import argparse import yaml import datetime from .utils import makedirs, symlink def make_symlinks(target_dir, source_dir=os.path.realpath("./output")): with open("defaults/backends.yaml") as stream: config = yaml.load(stream) makedirs(target_dir) with open(os.path.join(target_dir, ".keep"), "w"): pass for service in config.values(): for name, backend in service.items(): for links in backend.get("links", []): source = os.path.join(source_dir, name, links["source"]) target = os.path.join(os.path.realpath(target_dir), links["target"].lstrip("/")) makedirs(os.path.dirname(target)) if os.path.exists(target) and not os.path.islink(target): suffix = datetime.datetime.now().strftime(".%Y%m%d%H%M%S") os.rename(target, target + suffix) symlink(source, target) def main(): parser = argparse.ArgumentParser() parser.add_argument('target', help="Target directory") options = parser.parse_args() make_symlinks(options.target)
<!-- index html --> <!DOCTYPE HTML> <html id="non-embedded"> <head> <title>StKonrad_170702</title> <meta charset="UTF-8"> <link rel="alternate" href="album.rss" type="application/rss+xml"> </head> <body> <script src="init.js" id="jAlbum"></script> <div id="jalbumwidgetcontainer"></div> <script type="text/javascript"><!--//--><![CDATA[//><!-- _jaSkin = "Responsive"; _jaStyle = "light.css"; _jaVersion = "13.10"; _jaGeneratorType = "desktop"; _jaLanguage = "de"; _jaPageType = "index"; _jaRootPath = ".."; _jaUserId = "1081382"; var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http"+("https:"==document.location.protocol?"s":"")+"://jalbum.net/widgetapi/load.js"; document.getElementById("jalbumwidgetcontainer").appendChild(script); //--><!]]></script> </body> </html>
import {Command, flags} from '@heroku-cli/command' import * as Heroku from '@heroku-cli/schema' import {cli} from 'cli-ux' const METRICS_HOST = 'api.metrics.heroku.com' const isPerfOrPrivateTier = (size: string) => { const applicableTiers = ['performance', 'private', 'shield'] return applicableTiers.some(tier => size.toLowerCase().includes(tier)) } export default class Enable extends Command { static description = 'enable web dyno autoscaling' static flags = { app: flags.app({required: true}), remote: flags.remote(), min: flags.integer({required: true, description: 'minimum number of dynos'}), max: flags.integer({required: true, description: 'maximum number of dynos'}), p95: flags.integer({description: 'desired p95 response time'}), notifications: flags.boolean({description: 'receive email notifications when the max dyno limit is reached'}), } async run() { const {flags} = this.parse(Enable) cli.action.start('Enabling dyno autoscaling') const [appResponse, formationResponse] = await Promise.all([ this.heroku.get<Heroku.App>(`/apps/${flags.app}`), this.heroku.get<Heroku.Formation[]>(`/apps/${flags.app}/formation`), ]) const app = appResponse.body const formations = formationResponse.body const webFormation = formations.find((f: any) => f.type === 'web') if (!webFormation) throw new Error(`${flags.app} does not have any web dynos to scale`) const {size} = webFormation if (!isPerfOrPrivateTier(size || '')) { throw new Error('Autoscaling is only available with Performance or Private dynos') } const {body} = await this.heroku.get<Heroku.Formation[]>(`/apps/${app.id}/formation/web/monitors`, { hostname: METRICS_HOST, }) const scaleMonitor = (body || []).find((m: any) => m.action_type === 'scale') let updatedValues: any = { is_active: true, action_type: 'scale', notification_period: 1440, op: 'GREATER_OR_EQUAL', period: 1, notification_channels: flags.notifications ? ['app'] : [], } if (scaleMonitor) { updatedValues = {...updatedValues, min_quantity: flags.min || scaleMonitor.min_quantity, max_quantity: flags.max || scaleMonitor.max_quantity, value: flags.p95 ? flags.p95 : scaleMonitor.value, } await this.heroku.patch(`/apps/${app.id}/formation/web/monitors/${scaleMonitor.id}`, { body: updatedValues, hostname: METRICS_HOST, }) } else { updatedValues = {...updatedValues, name: 'LATENCY_SCALE', min_quantity: flags.min, max_quantity: flags.max, value: flags.p95 ? flags.p95 : 1000, } await this.heroku.post(`/apps/${app.id}/formation/web/monitors`, { hostname: METRICS_HOST, body: updatedValues, }) } cli.action.stop() } }
<?php include_partial('params', array('spy_form_builder_validators' => $spy_form_builder_validators)); ?> <ul class="sf_admin_actions"> <li><?php echo input_tag(__('Retour au formulaire'), __('Retour au formulaire'), array ( 'class' => 'sf_admin_action_list', 'type'=>'button', 'onClick'=>"document.location='".$_SERVER['SCRIPT_NAME']."/spyFormBuilderInterfaceValidate/doList/field_id/'+$('spy_form_builder_validators_field_id').value", )) ?></li> <li><?php echo submit_tag(__('save'), array ( 'name' => 'save', 'class' => 'sf_admin_action_save', )) ?></li> <li><?php echo submit_tag(__('save and list'), array ( 'name' => 'save_and_list', 'class' => 'sf_admin_action_save_and_list', )) ?></li> </ul>
var searchData= [ ['math_2ejs',['Math.js',['../_math_8js.html',1,'']]] ];
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @if (Auth::check()) <a href="{{ url('/home') }}">Home</a> @else <a href="{{ url('/login') }}">Login</a> <a href="{{ url('/register') }}">Register</a> @endif </div> @endif <div class="content"> <div class="title m-b-md"> Sphinge </div> <div class="links"> <a href="https://sphinge.io" rel="noopener noreferrer" target="_blank">Documentation</a> <a href="https://github.com/alanpilloud/sphinge/issues" rel="noopener noreferrer" target="_blank">Support on GitHub</a> </div> </div> </div> </body> </html>
{% extends "base.html" %} {% block title %}Submit A Game!{% endblock %} {% block extra_includes %} {% load staticfiles %} <script type="text/javascript" src="{% static 'MatchHistory/js/core.js' %}"></script> {% endblock %} <!-- Jumbotron --> {% block jumbotron %} <h1>Submit A Game!</h1> <p class="lead">Select the game you wish to add to the ladder from the text box below.</p> {% endblock %} {% block feature %} <div class="panel panel-default"> <div class="panel-heading"><span class="bold">Selected Games</span></div> <div class="panel-body"> {% if not_valid %} <div id='no_replay_warning' class="alert alert-warning" role="alert"> <strong>Warning!</strong>&nbsp;Please attach a valid SC2 Replay to submit. </div> <div id='bad_file_warning' class="alert alert-warning" role="alert" style='display:none;'> <strong>Warning!</strong>&nbsp;Only .SC2Replays files will be accepted, please remove all other files. </div> {% else %} <div id='no_replay_warning' class="alert alert-warning" role="alert" style='display:none;'> <strong>Warning!</strong>&nbsp;Please attach a valid SC2 Replay to submit. </div> <div id='bad_file_warning' class="alert alert-warning" role="alert" style='display:none;'> <strong>Warning!</strong>&nbsp;Only .SC2Replays files will be accepted, please remove all other files. </div> {% endif %} <form name="ReplayForm" action="{% url 'MatchHistory:SubmitText' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input id = 'file' class="file_btn" style="display:inline; width:600px;" type="file" name="file" multiple="" accept=".SC2Replay"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input class="btn" value="Submit Replay(s)" onclick='SubmitFormReplay();'> </form> </div> </div> {% endblock %} {% block content %} {% endblock %}
import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { SignUpPage } from './sign-up'; @NgModule({ declarations: [ SignUpPage, ], imports: [ IonicPageModule.forChild(SignUpPage), ], exports: [ SignUpPage ] }) export class SignUpPageModule {}
# Copyright (c) 2017 Thierry Kleist # # 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. from config import Macro, ButtonMapping from controllers import controllers import gremlin class HudMode(object): VIEW_MODE_CLEAR = 0 VIEW_MODE_HUDENTRY = 1 VIEW_MODE_HEADLOOK = 2 class HudSystem: def __init__(self): self._hud_headlook_lock = HudMode.VIEW_MODE_CLEAR controllers.joystick.addButtonEvent(self.mode_top, ButtonMapping.joystick_hud_up) controllers.joystick.addButtonEvent(self.mode_right, ButtonMapping.joystick_hud_right) controllers.joystick.addButtonEvent(self.mode_down, ButtonMapping.joystick_hud_down) controllers.joystick.addButtonEvent(self.mode_left, ButtonMapping.joystick_hud_left) controllers.joystick.addButtonEvent(self.mode_press, ButtonMapping.joystick_hud_press) controllers.throttle.addButtonEvent(self.mode_switch, 14) # def switch_hudent(self, joy): # if (joy[controllers.throttle.name].button(24).is_pressed & self._hud_headlook_lock == HudMode.VIEW_MODE_CLEAR) or (joy[controllers.throttle.name].button(24).is_pressed == False & self._hud_headlook_lock == HudMode.VIEW_MODE_HUDENTRY): # Macro.hud_interact_toggle.run() # # self._hud_headlook_lock = self._hud_headlook_lock ^ HudMode.VIEW_MODE_HUDENTRY def mode_switch(self, event, joy): if self._hud_headlook_lock is HudMode.VIEW_MODE_CLEAR and event.is_pressed: self._hud_headlook_lock = HudMode.VIEW_MODE_HEADLOOK Macro.hud_headlock_mode.run() elif self._hud_headlook_lock is HudMode.VIEW_MODE_HEADLOOK and event.is_pressed is False: self._hud_headlook_lock = HudMode.VIEW_MODE_CLEAR Macro.hud_headlock_mode_release.run() def mode_press_fn(self, event, joy, hud_macro, power_macro, shield_macro): if event.is_pressed: if joy[controllers.throttle.name].button(24).is_pressed is False: hud_macro.run() else: if joy[controllers.throttle.name].button(13).is_pressed: power_macro.run() elif self._hud_headlook_lock == HudMode.VIEW_MODE_HEADLOOK: hud_macro.run() else: shield_macro.run() def mode_press(self, event, joy): self.mode_press_fn(event, joy, Macro.hud_panel_confirm, Macro.power_reset, Macro.shield_reset) def mode_top(self, event, joy): self.mode_press_fn(event, joy, Macro.hud_panel_up, Macro.power_increase_weapon_shield, Macro.shield_raise_front) def mode_left(self, event, joy): self.mode_press_fn(event, joy, Macro.hud_panel_left, Macro.power_increase_weapon, Macro.shield_raise_left) def mode_right(self, event, joy): self.mode_press_fn(event, joy, Macro.hud_panel_right, Macro.power_increase_shield, Macro.shield_raise_right) def mode_down(self, event, joy): self.mode_press_fn(event, joy, Macro.hud_panel_down, Macro.power_increase_avionic, Macro.shield_raise_back)
# -*- coding: utf-8 -*- # Copyright (c) 2015 Conwet Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud 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. # Wirecloud 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 Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from uuid import uuid4 from django.contrib.auth.models import User, Group from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from markdown.extensions.toc import slugify __all__ = ('Organization', 'Team') class OrganizationManager(models.Manager): def is_available(self, name): return not User.objects.filter(username=name).exists() and not Group.objects.filter(name=name).exists() def search_available_name(self, username): max_length = 30 uuid_length = 8 short_username = slugify(username, '-')[:max_length - uuid_length] final_username = slugify(username, '-')[:max_length] while not self.is_available(final_username): final_username = short_username + uuid4().hex[:uuid_length] return final_username def create_organization(self, name, owners=[]): user = User.objects.create(username=name) group = Group.objects.create(name=name) org = self.create(user=user, group=group) team = Team.objects.create(organization=org, name='owners') for owner in owners: team.users.add(owner) return org @python_2_unicode_compatible class Organization(models.Model): user = models.OneToOneField(User) group = models.OneToOneField(Group) objects = OrganizationManager() class Meta: app_label = "platform" def __str__(self): return self.user.username class TeamManager(models.Manager): """ The manager for the auth's Team model. """ def get_by_natural_key(self, organization, name): return self.get(organization=organization, name=name) @python_2_unicode_compatible class Team(models.Model): """ Teams are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of teams. """ organization = models.ForeignKey(Organization, on_delete=models.CASCADE) name = models.CharField(_('name'), max_length=80) users = models.ManyToManyField(User, verbose_name=_('users'), blank=True, related_name="teams") objects = TeamManager() class Meta: app_label = "platform" unique_together = ('organization', 'name') verbose_name = _('team') verbose_name_plural = _('teams') def __str__(self): return self.name def natural_key(self): return (self.organization, self.name)
/* * CINELERRA * Copyright (C) 2008 Adam Williams <broadcast at earthling dot net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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 * */ #ifndef OVERLAYFRAME_H #define OVERLAYFRAME_H #include "loadbalance.h" #include "overlayframe.inc" #include "vframe.inc" #define DIRECT_COPY 0 #define BILINEAR 1 #define BICUBIC 2 #define LANCZOS 3 class OverlayKernel { public: OverlayKernel(int interpolation_type); ~OverlayKernel(); float *lookup; float width; int n; int type; }; class DirectEngine; class DirectPackage : public LoadPackage { public: DirectPackage(); int out_row1, out_row2; }; class NNEngine; class NNPackage : public LoadPackage { public: NNPackage(); int out_row1, out_row2; }; class SampleEngine; class SamplePackage : public LoadPackage { public: SamplePackage(); int out_col1, out_col2; }; class DirectUnit : public LoadClient { public: DirectUnit(DirectEngine *server); ~DirectUnit(); void process_package(LoadPackage *package); DirectEngine *engine; }; class NNUnit : public LoadClient { public: NNUnit(NNEngine *server); ~NNUnit(); void process_package(LoadPackage *package); NNEngine *engine; }; class SampleUnit : public LoadClient { public: SampleUnit(SampleEngine *server); ~SampleUnit(); void process_package(LoadPackage *package); SampleEngine *engine; }; class DirectEngine : public LoadServer { public: DirectEngine(int cpus); ~DirectEngine(); void init_packages(); LoadClient* new_client(); LoadPackage* new_package(); VFrame *output; VFrame *input; int in_x1; int in_y1; int out_x1; int out_x2; int out_y1; int out_y2; float alpha; int mode; }; class NNEngine : public LoadServer { public: NNEngine(int cpus); ~NNEngine(); void init_packages(); LoadClient* new_client(); LoadPackage* new_package(); VFrame *output; VFrame *input; float in_x1; float in_x2; float in_y1; float in_y2; float out_x1; float out_x2; int out_x1i; int out_x2i; float out_y1; float out_y2; float alpha; int mode; int *in_lookup_x; int *in_lookup_y; }; class SampleEngine : public LoadServer { public: SampleEngine(int cpus); ~SampleEngine(); void init_packages(); LoadClient* new_client(); LoadPackage* new_package(); VFrame *output; VFrame *input; OverlayKernel *kernel; int col_out1; int col_out2; int row_in; float in1; float in2; float out1; float out2; float alpha; int mode; int *lookup_sx0; int *lookup_sx1; int *lookup_sk; float *lookup_wacc; int kd; }; class OverlayFrame { public: OverlayFrame(int cpus = 1); virtual ~OverlayFrame(); int overlay(VFrame *output, VFrame *input, float in_x1, float in_y1, float in_x2, float in_y2, float out_x1, float out_y1, float out_x2, float out_y2, float alpha, int mode, int interpolation_type); DirectEngine *direct_engine; NNEngine *nn_engine; SampleEngine *sample_engine; VFrame *temp_frame; int cpus; OverlayKernel *kernel[4]; }; #endif
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation 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 INTEL 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. END_LEGAL */ #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include "pin.H" ADDRINT capturedVal; ADDRINT capturedConstVal; ADDRINT capturedRegEspBefore; BOOL badEsp = FALSE; // Make it inlineable ADDRINT CaptureRefWithReturnReg(ADDRINT *ref, ADDRINT *constRef) { capturedVal = *ref; capturedConstVal = *constRef; return (*constRef); } VOID CaptureRef(ADDRINT *ref, ADDRINT *constRef) { capturedVal = *ref; capturedConstVal = *constRef; } VOID CaptureEspBefore(ADDRINT regEsp) { capturedRegEspBefore = regEsp; } int haveBadEsp; VOID CaptureEspAfter(ADDRINT regEsp) { haveBadEsp = (regEsp!=capturedRegEspBefore); badEsp |= haveBadEsp; } VOID Instruction(INS ins, VOID *v) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(CaptureEspBefore), IARG_REG_VALUE, REG_STACK_PTR, IARG_END); INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(CaptureRefWithReturnReg), IARG_REG_REFERENCE, REG_GAX, IARG_REG_CONST_REFERENCE, REG_GAX, IARG_RETURN_REGS, REG_GAX, IARG_END); INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(CaptureRef), IARG_REG_REFERENCE, REG_GAX, IARG_REG_CONST_REFERENCE, REG_GAX, IARG_END); INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(CaptureEspAfter), IARG_REG_VALUE, REG_STACK_PTR, IARG_END); } VOID Fini(INT32 code, VOID *v) { if (badEsp) { printf ("***ERROR is esp value\n"); exit(-1); } } int main(INT32 argc, CHAR **argv) { PIN_Init(argc, argv); INS_AddInstrumentFunction(Instruction, 0); PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0; }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_deadline_timer::cancel_one (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.75.2"> <link rel="home" href="../../../../index.html" title="Asio"> <link rel="up" href="../cancel_one.html" title="basic_deadline_timer::cancel_one"> <link rel="prev" href="../cancel_one.html" title="basic_deadline_timer::cancel_one"> <link rel="next" href="overload2.html" title="basic_deadline_timer::cancel_one (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cancel_one.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../cancel_one.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="asio.reference.basic_deadline_timer.cancel_one.overload1"></a><a class="link" href="overload1.html" title="basic_deadline_timer::cancel_one (1 of 2 overloads)">basic_deadline_timer::cancel_one (1 of 2 overloads)</a> </h5></div></div></div> <p> Cancels one asynchronous operation that is waiting on the timer. </p> <pre class="programlisting"><span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">cancel_one</span><span class="special">();</span> </pre> <p> This function forces the completion of one pending asynchronous wait operation against the timer. Handlers are cancelled in FIFO order. The handler for the cancelled operation will be invoked with the <code class="computeroutput"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_aborted</span></code> error code. </p> <p> Cancelling the timer does not change the expiry time. </p> <h6> <a name="asio.reference.basic_deadline_timer.cancel_one.overload1.h0"></a> <span><a name="asio.reference.basic_deadline_timer.cancel_one.overload1.return_value"></a></span><a class="link" href="overload1.html#asio.reference.basic_deadline_timer.cancel_one.overload1.return_value">Return Value</a> </h6> <p> The number of asynchronous operations that were cancelled. That is, either 0 or 1. </p> <h6> <a name="asio.reference.basic_deadline_timer.cancel_one.overload1.h1"></a> <span><a name="asio.reference.basic_deadline_timer.cancel_one.overload1.exceptions"></a></span><a class="link" href="overload1.html#asio.reference.basic_deadline_timer.cancel_one.overload1.exceptions">Exceptions</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">asio::system_error</span></dt> <dd><p> Thrown on failure. </p></dd> </dl> </div> <h6> <a name="asio.reference.basic_deadline_timer.cancel_one.overload1.h2"></a> <span><a name="asio.reference.basic_deadline_timer.cancel_one.overload1.remarks"></a></span><a class="link" href="overload1.html#asio.reference.basic_deadline_timer.cancel_one.overload1.remarks">Remarks</a> </h6> <p> If the timer has already expired when <code class="computeroutput"><span class="identifier">cancel_one</span><span class="special">()</span></code> is called, then the handlers for asynchronous wait operations will: </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"> have already been invoked; or </li> <li class="listitem"> have been queued for invocation in the near future. </li> </ul></div> <p> These handlers can no longer be cancelled, and therefore are passed an error code that indicates the successful completion of the wait operation. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2013 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cancel_one.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../cancel_one.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a> </div> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Upgrading from 1.6.2 to 1.6.3 : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 2.1.0</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Upgrading from 1.6.2 to 1.6.3 </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Upgrading from 1.6.2 to 1.6.3</h1> <p>Before performing an update you should take your site offline by replacing the index.php file with a static one.</p> <h2>Step 1: Update your CodeIgniter files</h2> <p>Replace these files and directories in your "system" folder with the new versions:</p> <ul> <li><dfn>system/codeigniter</dfn></li> <li><dfn>system/database</dfn></li> <li><dfn>system/helpers</dfn></li> <li><dfn>system/language</dfn></li> <li><dfn>system/libraries</dfn></li> </ul> <p class="important"><strong>Note:</strong> If you have any custom developed files in these folders please make copies of them first.</p> <h2>Step 2: Update your user guide</h2> <p>Please also replace your local copy of the user guide with the new version.</p> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="index.html">Installation Instructions</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="troubleshooting.html">Troubleshooting</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2011 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p> </div> </body> </html>
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import os import re from lib.core.common import singleTimeWarnMessage from lib.core.data import kb from lib.core.enums import DBMS from lib.core.enums import PRIORITY from lib.core.settings import IGNORE_SPACE_AFFECTED_KEYWORDS __priority__ = PRIORITY.HIGHER def dependencies(): singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s < 5.1" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL)) def tamper(payload, **kwargs): """ Adds versioned MySQL comment before each keyword Requirement: * MySQL < 5.1 Tested against: * MySQL 4.0.18, 5.0.22 Notes: * Useful to bypass several web application firewalls when the back-end database management system is MySQL * Used during the ModSecurity SQL injection challenge, http://modsecurity.org/demo/challenge.html >>> tamper("value' UNION ALL SELECT CONCAT(CHAR(58,107,112,113,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,97,110,121,58)), NULL, NULL# AND 'QDWa'='QDWa") "value'/*!0UNION/*!0ALL/*!0SELECT/*!0CONCAT(/*!0CHAR(58,107,112,113,58),/*!0IFNULL(CAST(/*!0CURRENT_USER()/*!0AS/*!0CHAR),/*!0CHAR(32)),/*!0CHAR(58,97,110,121,58)),/*!0NULL,/*!0NULL#/*!0AND 'QDWa'='QDWa" """ def process(match): word = match.group('word') if word.upper() in kb.keywords and word.upper() not in IGNORE_SPACE_AFFECTED_KEYWORDS: return match.group().replace(word, "/*!0%s" % word) else: return match.group() retVal = payload if payload: retVal = re.sub(r"(?<=\W)(?P<word>[A-Za-z_]+)(?=\W|\Z)", lambda match: process(match), retVal) retVal = retVal.replace(" /*!0", "/*!0") return retVal
#!/usr/bin/env python # results2html.py - given standard input, output an HTML table of search results # Eric Lease Morgan <[email protected]> # May 28, 2015 - first investigations # May 30, 2015 - tweaked display, but how do I turn (toggle) off specific columns by default # June 1, 2015 - moved the html template off to a file # June 2, 2015 - added (some) sanity checking # configure HASH = '''{ "id": "##ID##", "shortTitle": "##SHORTTITLE##", "title": "##TITLE##", "date": "##DATE##", "pages": "##PAGES##", "hathitrust": "##HATHITRUST##", "language": "##LANGUAGE##", "marc": "##MARC##", "worldcat": "##WORLDCAT##", "words": "##WORDS##", "color": "##COLOR##", "names": "##NAMES##", "ideas": "##IDEAS##", "count": "##COUNT##", "tfidf": "##TFIDF##", "text": "##TEXT##", "json": "##JSON##" }, ''' TEMPLATE = './etc/template-search-results.txt' # require import sys import re # sanity check if ( len( sys.argv ) != 2 ) | ( sys.stdin.isatty() ) : print( "Usage: ./bin/search.py <query> <name> | " + sys.argv[ 0 ] + ' <name>' ) quit() # get input name = sys.argv[ 1 ] # initialize data = '' # process each record for hit in sys.stdin: # re-initialize hash = HASH # read a record, and split it into fields fields = hit.rstrip().split( '\t' ) # do the substitutions hash = re.sub( '##ID##', fields[ 0 ], hash ) title = re.sub( '\"', '\\"', fields[ 4 ] ) hash = re.sub( '##SHORTTITLE##', title[:50] + '...', hash ) hash = re.sub( '##TITLE##', title, hash ) hash = re.sub( '##DATE##', fields[ 5 ], hash ) hash = re.sub( '##PAGES##', fields[ 6 ], hash ) hash = re.sub( '##HATHITRUST##', fields[ 7 ], hash ) hash = re.sub( '##LANGUAGE##', fields[ 8 ], hash ) hash = re.sub( '##MARC##', fields[ 9 ], hash ) hash = re.sub( '##WORLDCAT##', fields[ 10 ], hash ) hash = re.sub( '##WORDS##', fields[ 2 ], hash ) hash = re.sub( '##COLOR##', fields[ 11 ], hash ) hash = re.sub( '##NAMES##', fields[ 12 ], hash ) hash = re.sub( '##IDEAS##', fields[ 13 ], hash ) hash = re.sub( '##COUNT##', fields[ 1 ], hash ) hash = re.sub( '##TFIDF##', fields[ 3 ], hash ) hash = re.sub( '##TEXT##', fields[ 14 ], hash ) hash = re.sub( '##JSON##', fields[ 15 ], hash ) # update the data data += hash # create the html; do the substitutions with open ( TEMPLATE ) as HTML : html = HTML.read() html = re.sub( '##TITLE##', name, html ) html = re.sub( '##DATA##', data, html ) # output and done print( html ) quit()
<div class="main-title">30, Wednesday <span>2016</span> </div> <ul class="stage clearfix"> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>20:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>21:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Aucas <br><small>vs</small> <br>Independiente ECD</div><em><i class="fa fa-map-marker"></i>Ecuador - Serie A</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-number-hist">2.5</div> <div class="over-under-text-under-hist uppercase">Under<i class="fa fa-angle-down"></i></div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> </ul>
# Copyright (C) 2014 Parker Michaels # # 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. import sys def MethodTracer(cls): class DebugInitializer(object): def decorate(self, method_name, method): decorator = self def decorated_method(self, *args, **kw_args): args_text = [repr(i) for i in args] args_text.extend(["'{0}': {1}".format(k, repr(v)) for k, v in kw_args]) print("{0}Entering {1}({2})".format(' '*decorator.count, method_name, ', '.join(args_text))) decorator.count += 1 results = method.__get__(self, cls)(*args, **kw_args) decorator.count -= 1 print("{0}Exiting {1} = {2}".format(' '*decorator.count, method_name, repr(results))) return results return decorated_method def __init__(self, *args, **kw_args): self.count = 0 self.instance = cls(*args, **kw_args) for method_name, method in cls.__dict__.items(): if callable(method): new_method = self.decorate.__get__(self, DebugInitializer)(method_name, method).__get__(self.instance, cls) setattr(self.instance, method_name, new_method) setattr(self, method_name, new_method) return DebugInitializer
import bpy bl_info = { "name": "Batch Render", "author": "Andrea Calzavacca", "version": (0, 1, 1), "blender": (2, 7, 8), "location": "Render > Batch Render", "description": "Make possible to render more than one camera without manually start every render", "warning": "Beta version: 1.1", "category": "Render"} class CamProp(bpy.types.PropertyGroup): @classmethod def register(cls): bpy.types.Object.custom = bpy.props.PointerProperty( name="Custom properties", description="Custom Properties for Cameras", type=cls, ) cls.isSelected = bpy.props.BoolProperty( description="True if Camera is selected to be used", default=False ) @classmethod def unregister(cls): del bpy.types.Object.custom class BatchRender(bpy.types.Operator): """Batch Render""" bl_idname = "render.batch" bl_label = "Subsequently render all selected cameras" bl_options = {'REGISTER', 'UNDO'} # Define some variables to register _timer = None shots = [] stop = None rendering = None fr = True # needed for break infinite render loop path = "//" # Define the handler functions. I use pre and # post to know if Blender "is rendering" def pre(self, dummy): self.rendering = True def post(self, dummy): self.shots.pop(0) # This is just to render the next # image in another path self.rendering = False def cancelled(self, dummy): self.stop = True def execute(self, context): # Define the variables during execution. This allows # to define when called from a button self.stop = False self.rendering = False while self.fr: for item in bpy.data.objects: if item.type == 'CAMERA' and item.custom.isSelected: self.shots.append(item) self.fr = False # make the loop work only once per instance bpy.context.scene.render.filepath = self.path bpy.app.handlers.render_pre.append(self.pre) bpy.app.handlers.render_post.append(self.post) bpy.app.handlers.render_cancel.append(self.cancelled) # The timer gets created and the modal handler # is added to the window manager self._timer = context.window_manager.event_timer_add(0.5, context.window) context.window_manager.modal_handler_add(self) return {"RUNNING_MODAL"} def modal(self, context, event): if event.type == 'TIMER': # This event is signaled every half a second # and will start the render if available # If cancelled or no more shots to render, finish. if True in (not self.shots, self.stop is True): # We remove the handlers and the modal timer to clean everything bpy.app.handlers.render_pre.remove(self.pre) bpy.app.handlers.render_post.remove(self.post) bpy.app.handlers.render_cancel.remove(self.cancelled) context.window_manager.event_timer_remove(self._timer) return {"FINISHED"} elif self.rendering is False: # Nothing is currently rendering. # Proceed to render. sceneKey = bpy.data.scenes.keys()[0] bpy.data.scenes[sceneKey].camera = self.shots[0] bpy.data.scenes[sceneKey].render.filepath = self.path + self.shots[0].name bpy.ops.render.render("INVOKE_DEFAULT", write_still=True) return {"PASS_THROUGH"} # This is very important! If we used "RUNNING_MODAL", this new modal function # would prevent the use of the X button to cancel rendering, because this # button is managed by the modal function of the render operator, # not this new operator! class BatchRenderPanel(bpy.types.Panel): bl_idname = "PROPERTIES_PT_batch" bl_label = "Batch Render" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "render" bl_options = {'DEFAULT_CLOSED'} @classmethod def pool(cls, context): return context.object is not None def draw(self, context): layout = self.layout split = layout.split() col = split.column() elements = [] for item in bpy.data.objects: if item.type == 'CAMERA': elements.append(item) i = 0 for item in elements: if i < len(elements)/2: col.prop(item.custom, "isSelected", text=item.name) elif i == len(elements)/2 or i == (len(elements)+1)/2: col = split.column() col.prop(item.custom, "isSelected", text=item.name) else: col.prop(item.custom, "isSelected", text=item.name) i += 1 row = layout.row(align=True) row.operator("render.batch", text="Batch Render", icon='RENDER_STILL') def register(): bpy.utils.register_module(__name__) def unregister(): bpy.utils.unregister_module(__name__) # START DEBUG SECTION --------------------------------------------------------------------------------------- # launch addon as script into blender text editor ----------------------------------------------------------- if __name__ == "__main__": register()
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Table with letters</title> <style type="text/css"> table { border-spacing: 0px 0px; } td { border: 1px outset #808080; width: 30px; } .center { text-align: center; } .right { text-align: right; } .rightDown { text-align: right; vertical-align: bottom; } </style> </head> <body> <table> <tr> <td colspan="3">Title goes here</td> <td class="center">A</td> <td class="right">B</td> </tr> <tr> <td rowspan="3">C</td> <td class="center">D</td> <td class="center">E</td> <td class="center">F</td> <td class="right">G</td> </tr> <tr> <td class="center">H</td> <td colspan="2" class="center">I</td> <td rowspan="2" class="rightDown">J</td> </tr> <tr> <td class="center">K</td> <td class="center">L</td> <td class="center">M</td> </tr> <tr> <td class="right">N</td> <td class="center" colspan="4">O</td> </tr> </table> </body> </html>
<p>XipMac4.4.2 was annotated using the Ensembl genebuild pipeline. Gene models are based on</p> <ul> <li>Genewise alignments of UniProt protein sequences from platyfish</li> <li>Models build from platyfish RNASeq data using our in-house RNASeq pipeline</li> <li>Genewise alignments of UniProt protein sequences from other fish and vertebrate species</li> <li>Exonerate alignments of Ensembl Stickleback and Zebrafish proteins from Ensembl release 65</li> </ul> <p>Protein-coding models were extended into their untranslated regions using RNASeq models. In addition to the coding transcript models, non-coding RNAs and pseudogenes were annotated.</p> <ul> <li><a href="/info/genome/genebuild/2012_08_platyfish_genebuild.pdf">Detailed information on genebuild</a> (PDF)</li> </ul>
<h2>Search</h2> <p>By default all searched terms must match. Searches are case-insensitive.</p> <table class="qsearch_help_table"> <tr> <td>quoted phrase<br> <q>"search"</q> </td> <td>Use quotes to search for an exact word or phrase.<br> <q>"george washington"</q></td> </tr> <tr> <td>either term<br> <q>OR search</q><br> </td> <td>Add an OR between words.<br> <q>john OR bill</q></td> </tr> <tr> <td>exclude<br> <q>NOT search</q><br> <q>-search</q> </td> <td>Add a dash (-) or NOT before a word to exclude from search. Note that NOT acts as a filtering operator so you cannot have a search containing only NOT operators. You cannot combine OR with NOT (<q>john OR NOT bill</q> is not valid)<br> <q>george washington NOT bush</q></td> </tr> <tr> <td>grouping<br> <q>()</q><br> </td> <td><br> <q>(mother OR father) AND (daugther OR son)</q></td> </tr> </table> <br> <table class="qsearch_help_table"> <tr> <td><q>tag:</q><br> <q>tags:</q> </td> <td>Searches only in tag names without looking at photo titles or descriptions.<br> <q>tag:john</q>, <q>tag:(john OR bill)</q></td> </tr> <tr> <td><q>photo:</q><br> <q>photos:</q> </td> <td>Searches only for photos with the given words in title or description.<br> <q>photo:John</q></td> </tr> <tr> <td><q>file:</q> </td> <td>Searches by file name.<br> <q>file:DSC_</q></td> </tr> <tr> <td><q>author:</q> </td> <td>Searches by author.<br> <q>author:John</q></td> </tr> <tr> <td><q>created:</q><br> <q>taken:</q> <q>shot:</q> </td> <td>Searches photos by taken date.<br> <q>taken:2003</q> photos taken in 2003<br> <q>taken:20035</q>,<q>taken:2003-5</q>,<q>taken:2003-05</q> photos from may 2003<br> <q>taken:2003..2008</q> photos from 2003 to 2008<br> <q>taken:&gt;2008</q>,<q>taken:2008*</q>,<q>taken:2008..</q> photos afteer Jan 1st 2008<br> </td> </tr> <tr> <td><q>posted:</q> </td> <td>Searches photos by posted date.</td> </tr> <tr> <td><q>width:</q><br> <q>height:</q> </td> <td>Searches photos with a given width or height.</td> </tr> <tr> <td><q>size:</q> </td> <td>Searches photos by size in pixels<br> <q>size:5m</q> returns photos of 5 megapixels<br> <q>size:>12m</q> returns photos of 12 megapixels or more<br></td> </tr> <tr> <td><q>ratio:</q> </td> <td>Searches photos by width/height ratio.<br> <q>ratio:3/4 OR ratio:4/3</q> finds photos from compact cameras in portrait or landscape modes <q>ratio:>16/9</q> finds panoramas </td> </tr> <tr> <td><q>hits:</q> </td> <td></td> </tr> <tr> <td><q>score:</q><br> <q>rating:</q> </td> <td>Hint: <q>score:*</q> will give you all photos with at least one vote. <q>score:</q> will give you photos without votes.</td> </tr> <tr> <td><q>filesize:</q> </td> <td>Searches photos by file size<br> <q>filesize:1m..10m</q> finds files between 1MB and 10MB.</td> </tr> <tr> <td><q>id:</q> </td> <td>Searches photos by its numeric identifier in Piwigo<br> <q>id:123..126</q> finds photo 123 to 126 (it may find between 0 and 4 photos, because photos can be deleted).</td> </tr> </table>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duracellko.WindowsAzureVmManager.Model { public static class AzureManagementHeaders { public const string RequestId = "x-ms-request-id"; public static string GetHeaderValue(this IDictionary<string, string> headers, string name) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } string value = null; if (headers.TryGetValue(name, out value)) { return value; } else { return null; } } } }
__author__ = 'saeedamen' # # Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians # # 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. # """ Seasonality Does simple seasonality calculations on data. """ import pandas import numpy from pythalesians.util.configmanager import ConfigManager from pythalesians.util.loggermanager import LoggerManager from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs from pythalesians.timeseries.calcs.timeseriesfilter import TimeSeriesFilter from pythalesians.util.commonman import CommonMan class Seasonality: def __init__(self): self.config = ConfigManager() self.logger = LoggerManager().getLogger(__name__) return def time_of_day_seasonality(self, data_frame, years = False): tsc = TimeSeriesCalcs() if years is False: return tsc.average_by_hour_min_of_day_pretty_output(data_frame) set_year = set(data_frame.index.year) year = sorted(list(set_year)) intraday_seasonality = None commonman = CommonMan() for i in year: temp_seasonality = tsc.average_by_hour_min_of_day_pretty_output(data_frame[data_frame.index.year == i]) temp_seasonality.columns = commonman.postfix_list(temp_seasonality.columns.values, " " + str(i)) if intraday_seasonality is None: intraday_seasonality = temp_seasonality else: intraday_seasonality = intraday_seasonality.join(temp_seasonality) return intraday_seasonality def bus_day_of_month_seasonality_from_prices(self, data_frame, month_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], cum = True, cal = "FX", partition_by_month = True, add_average = False): return self.bus_day_of_month_seasonality(self, data_frame, month_list = month_list, cum = cum, cal = cal, partition_by_month = partition_by_month, add_average = add_average, price_index = True) def bus_day_of_month_seasonality(self, data_frame, month_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], cum = True, cal = "FX", partition_by_month = True, add_average = False, price_index = False): tsc = TimeSeriesCalcs() tsf = TimeSeriesFilter() if price_index: data_frame = data_frame.resample('B') # resample into business days data_frame = tsc.calculate_returns(data_frame) data_frame.index = pandas.to_datetime(data_frame.index) data_frame = tsf.filter_time_series_by_holidays(data_frame, cal) monthly_seasonality = tsc.average_by_month_day_by_bus_day(data_frame, cal) monthly_seasonality = monthly_seasonality.loc[month_list] if partition_by_month: monthly_seasonality = monthly_seasonality.unstack(level=0) if add_average: monthly_seasonality['Avg'] = monthly_seasonality.mean(axis=1) if cum is True: if partition_by_month: monthly_seasonality.loc[0] = numpy.zeros(len(monthly_seasonality.columns)) # monthly_seasonality.index = monthly_seasonality.index + 1 # shifting index monthly_seasonality = monthly_seasonality.sort() monthly_seasonality = tsc.create_mult_index(monthly_seasonality) return monthly_seasonality def monthly_seasonality_from_prices(self, data_frame, cum = True, add_average = False): return self.monthly_seasonality(data_frame, cum, add_average, price_index=True) def monthly_seasonality(self, data_frame, cum = True, add_average = False, price_index = False): tsc = TimeSeriesCalcs() if price_index: data_frame = data_frame.resample('BM') # resample into month end data_frame = tsc.calculate_returns(data_frame) data_frame.index = pandas.to_datetime(data_frame.index) monthly_seasonality = tsc.average_by_month(data_frame) if add_average: monthly_seasonality['Avg'] = monthly_seasonality.mean(axis=1) if cum is True: monthly_seasonality.loc[0] = numpy.zeros(len(monthly_seasonality.columns)) monthly_seasonality = monthly_seasonality.sort() monthly_seasonality = tsc.create_mult_index(monthly_seasonality) return monthly_seasonality if __name__ == '__main__': # see seasonality_examples pass
<?php /** * @version $Id: categories.php 9764 2007-12-30 07:48:11Z ircmaxell $ * @package Joomla * @subpackage Content * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant to the * GNU General Public License, and as distributed it includes or is derivative * of works licensed under the GNU General Public License or other free or open * source software licenses. See COPYRIGHT.php for copyright notices and * details. */ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die(); jimport('joomla.application.component.model'); /** * Weblinks Component Categories Model * * @author Johan Janssens <[email protected]> * @package Joomla * @subpackage Weblinks * @since 1.5 */ class WeblinksModelCategories extends JModel { /** * Categories data array * * @var array */ var $_data = null; /** * Categories total * * @var integer */ var $_total = null; /** * Constructor * * @since 1.5 */ function __construct() { parent::__construct(); } /** * Method to get weblink item data for the category * * @access public * @return array */ function getData() { // Lets load the content if it doesn't already exist if (empty($this->_data)) { $query = $this->_buildQuery(); $this->_data = $this->_getList($query); } return $this->_data; } /** * Method to get the total number of weblink items for the category * * @access public * @return integer */ function getTotal() { // Lets load the content if it doesn't already exist if (empty($this->_total)) { $query = $this->_buildQuery(); $this->_total = $this->_getListCount($query); } return $this->_total; } function _buildQuery() { $user =& JFactory::getUser(); $aid = $user->get('aid', 0); //Query to retrieve all categories that belong under the web links section and that are published. $query = 'SELECT cc.*, COUNT(a.id) AS numlinks,' .' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(\':\', cc.id, cc.alias) ELSE cc.id END as slug' .' FROM #__categories AS cc' .' LEFT JOIN #__weblinks AS a ON a.catid = cc.id' .' WHERE a.published = 1' .' AND section = \'com_weblinks\'' .' AND cc.published = 1' .' AND cc.access <= '.(int) $aid .' GROUP BY cc.id' .' ORDER BY cc.ordering'; return $query; } } ?>
/* Copyright 2008 (C) Nicira, Inc. * * This file is part of NOX. * * NOX 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. * * NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>. */ #ifndef STABLE_MAP_HH #define STABLE_MAP_HH 1 #include <map> namespace vigil { /* * Stable_map is much like std::map, except that deleting an element does not * in itself invalidate any iterators. Call the purge member function to * finish deletion (and thereby invalidate iterators). * * ("Stable_map" is not a particularly good name. Got a better one?) */ template <class Key, class Value> class Stable_map { private: struct mapped_type { bool erased; Value value; mapped_type(bool erased_, Value value_) : erased(erased_), value(value_) { } }; typedef std::pair<Key, Value> value_type; class value_type_ptr { public: const value_type v; value_type_ptr(const value_type& v_) : v(v_) { } const value_type* operator->() { return &v; } }; typedef std::map<Key, mapped_type> Container; public: struct iterator { public: iterator() { } iterator(const iterator& that) : i(that.i) { } iterator(typename Container::iterator i, typename Container::iterator end); iterator& operator=(const iterator& that) { i = that.i; } bool operator==(const iterator& that) { return i == that.i; } bool operator!=(const iterator& that) { return !(*this == that); } value_type operator*() const { return std::make_pair(i->first, i->second.value); } value_type_ptr operator->() const { return value_type_ptr(**this); } iterator& operator++(); iterator operator++(int); void erase() { i->second.erased = true; } private: typename Container::iterator i; typename Container::iterator end; void skip_erased(); }; bool empty() const { return c.empty(); } bool insert(Key, Value); bool erase(Key); void purge(); iterator find(Key); iterator begin(); iterator end(); private: Container c; }; template <class Key, class Value> bool Stable_map<Key, Value>::insert(Key key, Value value) { typename Container::iterator i = c.find(key); if (i == c.end()) { c.insert(std::make_pair(key, mapped_type(false, value))); return true; } else if (i->second.erased) { i->second.erased = false; i->second.value = value; return true; } else { return false; } } template <class Key, class Value> bool Stable_map<Key, Value>::erase(Key key) { typename Container::iterator i = c.find(key); if (i != c.end() && !i->second.erased) { i->second.erased = true; return true; } else { return false; } } template <class Key, class Value> void Stable_map<Key, Value>::purge() { for (typename Container::iterator i = c.begin(); i != c.end(); ) { typename Container::iterator j = i++; if (j->second.erased) { c.erase(j); } } } template <class Key, class Value> typename Stable_map<Key, Value>::iterator Stable_map<Key, Value>::find(Key key) { typename Container::iterator i = c.find(key); return i != c.end() && !i->second.erased ? iterator(i, c.end()) : end(); } template <class Key, class Value> typename Stable_map<Key, Value>::iterator Stable_map<Key, Value>::begin() { return iterator(c.begin(), c.end()); } template <class Key, class Value> typename Stable_map<Key, Value>::iterator Stable_map<Key, Value>::end() { return iterator(c.end(), c.end()); } template <class Key, class Value> typename Stable_map<Key, Value>::iterator& Stable_map<Key, Value>::iterator::operator++() { ++i; skip_erased(); return *this; } template <class Key, class Value> typename Stable_map<Key, Value>::iterator Stable_map<Key, Value>::iterator::operator++(int) { iterator old(*this); ++*this; return old; } template <class Key, class Value> Stable_map<Key, Value>::iterator::iterator(typename Container::iterator i_, typename Container::iterator end_) : i(i_), end(end_) { skip_erased(); } template <class Key, class Value> void Stable_map<Key, Value>::iterator::skip_erased() { while (i != end && i->second.erased) { ++i; } } } // namespace vigil #endif /* stable_map.hh */
import core from "tokenizer2/core"; /** * Contains a URL tokenizer that is capable of tokenizing a URL structure string. * * @type {Object} */ var urlTokenizer; /** * Contains the tokens as parsed by the urlTokenizer. * * @type {Object[]} */ let tokens; /** * Matches static parts of a URL, because we use %% as placeholder markers we don't support percentage signs in the URL. * * @type {RegExp} */ const staticRegex = /^[^%]+$/; /** * Matches variable parts of a URL, format is %%placeholder%%. * * @type {RegExp} */ const variableRegex = /^%%[^%]+%%$/; /** * Creates a tokenizer to tokenize HTML into blocks. * * @since 1.8.0 * * @returns {void} */ function createTokenizer() { tokens = []; urlTokenizer = core( function( token ) { tokens.push( token ); } ); urlTokenizer.addRule( staticRegex, "static" ); urlTokenizer.addRule( variableRegex, "variable" ); } /** * Represents a URL structure. Placeholders can be defined using %%placeholder%% and can later be filled using the `applyData` method. * * @since 1.8.0 */ class UrlStructure { /** * Sets the structure to the passed structure. * * @since 1.8.0 * * @param {Array} structure The structure of the URL. */ constructor( structure ) { this._structure = structure; } /** * Builds a URL from this URL structure and the given data. * * @since 1.8.0 * * @param {Object} data A key value store of all the variable parts of the URL structure. * @returns {string} A URL with all variables parts filled. */ buildUrl( data ) { return this._structure.reduce( ( url, urlPart ) => { if ( "variable" === urlPart.type ) { urlPart = this._buildVariablePart( data, urlPart ); } else { urlPart = urlPart.value; } return url + urlPart; }, "" ); } /** * Builds a URL part for a small part of the URL. * * @since 1.8.0 * * @private * * @param {Object} data The data to fill the URL parts. * @param {Object} urlPartConfig The config for the URL part. * @returns {string} A URL part. */ _buildVariablePart( data, urlPartConfig ) { if ( ! data.hasOwnProperty( urlPartConfig.name ) ) { throw new TypeError( 'Data doesn\'t have required property "' + urlPartConfig.name + '"' ); } return data[ urlPartConfig.name ]; } /** * Returns the structure. * * @since 1.8.0 * * @returns {Array} The structure of the URL. */ getStructure() { return this._structure; } /** * Parses a URL for static and variable parts. Variables should be surrounded by double percentage signs. * * @since 1.8.0 * * @param {string} url The URL to parse. * @returns {UrlStructure} The parsed url structure. */ static fromUrl( url ) { createTokenizer(); urlTokenizer.onText( url ); urlTokenizer.end(); tokens = tokens.map( ( token ) => { const urlPart = { type: token.type, value: token.src, }; if ( "variable" === token.type ) { // Strip the %% at the start and the end of the variable URL part. urlPart.name = urlPart.value.substr( 2, urlPart.value.length - 4 ); } return urlPart; } ); return new UrlStructure( tokens ); } } export default UrlStructure;
from settings.base import * import sys import urlparse DEBUG = False TEMPLATE_DEBUG = DEBUG SERVE_MEDIA = True INSTALLED_APPS += ['gunicorn'] CACHE_TIMEOUT = 60 * 60 * 24 urlparse.uses_netloc.append('postgres') urlparse.uses_netloc.append('mysql') try: if os.environ.has_key('DATABASE_URL'): url = urlparse.urlparse(os.environ['DATABASE_URL']) DATABASES = {} DATABASES['default'] = { 'NAME': url.path[1:], 'USER': url.username, 'PASSWORD': url.password, 'HOST': url.hostname, 'PORT': url.port, } if url.scheme == 'postgres': DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2' if url.scheme == 'mysql': DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' except Exception as e: print "Unexpected error:", sys.exc_info() LOCAL_INSTALLED_APPS = [] LAUNCHPAD_ACTIVE = False # Analytics ID URCHIN_ID = "" # Email Settings DEFAULT_FROM_EMAIL = \ 'Django Packages <[email protected]>' EMAIL_SUBJECT_PREFIX = '[Django Packages] ' RESTRICT_PACKAGE_EDITORS = False RESTRICT_GRID_EDITORS = False ROOT_URLCONF = "app.urls" EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SECRET_KEY = os.environ['SECRET_KEY'] GITHUB_API_SECRET = os.environ['GITHUB_API_SECRET'] GITHUB_APP_ID = os.environ['GITHUB_APP_ID'] SITE_TITLE = os.environ['SITE_TITLE'] FRAMEWORK_TITLE = os.environ['FRAMEWORK_TITLE'] PIWIK_CODE = """ <!-- Piwik --> <script type="text/javascript"> var pkBaseURL = (("https:" == document.location.protocol) ? "https://manage.cartwheelweb.com/piwik/" : "http://manage.cartwheelweb.com/piwik/"); document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E")); </script><script type="text/javascript"> try { var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 4); piwikTracker.trackPageView(); piwikTracker.enableLinkTracking(); } catch( err ) {} </script><noscript><p><img src="http://manage.cartwheelweb.com/piwik/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript> <!-- End Piwik Tracking Code --> """ ########## STORAGE CONFIGURATION INSTALLED_APPS += ['storages', ] DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_QUERYSTRING_AUTH = False AWS_HEADERS = { 'Expires': 'Thu, 15 Apr 2020 20:00:00 GMT', 'Cache-Control': 'max-age=86400', } # Boto requires subdomain formatting. from S3 import CallingFormat AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN # Amazon S3 configuration. if os.environ.has_key('S3_KEY'): AWS_ACCESS_KEY_ID = os.environ['S3_KEY'] AWS_SECRET_ACCESS_KEY = os.environ['S3_SECRET'] else: AWS_ACCESS_KEY_ID = AWS_KEY AWS_SECRET_ACCESS_KEY = AWS_SECRET_KEY AWS_STORAGE_BUCKET_NAME = 'opencomparison' STATIC_URL = 'https://s3.amazonaws.com/opencomparison/' MEDIA_URL = STATIC_URL ########## END STORAGE CONFIGURATION
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Search ~~~~~ copyright: (c) 2014-2016 by Halfmoon Labs, Inc. copyright: (c) 2016 by Blockstack.org This file is part of Search. Search 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. Search 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 Search. If not, see <http://www.gnu.org/licenses/>. """ import sys import json import threading from time import time from flask import request, jsonify, make_response, render_template, Blueprint from flask_crossdomain import crossdomain from api.config import DEFAULT_HOST, DEFAULT_PORT, DEBUG, DEFAULT_CACHE_TIMEOUT, EMPTY_CACHE_TIMEOUT from api.config import SEARCH_DEFAULT_LIMIT as DEFAULT_LIMIT from .substring_search import search_people_by_name, search_people_by_twitter from .substring_search import search_people_by_username, search_people_by_bio from .substring_search import fetch_profiles searcher = Blueprint('searcher', __name__, url_prefix='') class QueryThread(threading.Thread): """ for performing multi-threaded search on three search sub-systems """ def __init__(self, query, query_type, limit_results): threading.Thread.__init__(self) self.query = query self.query_type = query_type self.results = [] self.limit_results = limit_results self.found_exact_match = False def run(self): if(self.query_type == 'people_search'): self.results = query_people_database(self.query, self.limit_results) elif(self.query_type == 'twitter_search'): self.results = query_twitter_database(self.query, self.limit_results) elif(self.query_type == 'username_search'): self.results = query_username_database(self.query, self.limit_results) def error_reply(msg, code=-1): reply = {} reply['status'] = code reply['message'] = "ERROR: " + msg return jsonify(reply) def query_people_database(query, limit_results=DEFAULT_LIMIT): name_search_results = search_people_by_name(query, limit_results) return fetch_profiles(name_search_results, search_type="name") def query_twitter_database(query, limit_results=DEFAULT_LIMIT): twitter_search_results = search_people_by_twitter(query, limit_results) return fetch_profiles(twitter_search_results, search_type="twitter") def query_username_database(query, limit_results=DEFAULT_LIMIT): username_search_results = search_people_by_username(query, limit_results) return fetch_profiles(username_search_results, search_type="username") def test_alphanumeric(query): """ check if query has only alphanumeric characters or not """ import re valid = re.match(r'^\w+[\s\w]*$', query) is not None return True @searcher.route('/search', methods = ["GET", "POST"], strict_slashes = False) @crossdomain(origin='*') def search_by_name(): query = request.args.get('query') results_people = [] if query is None: return error_reply("No query given") elif query == '' or query == ' ': return json.dumps({}) new_limit = DEFAULT_LIMIT try: new_limit = int(request.values['limit_results']) except: pass if test_alphanumeric(query) is False: pass else: threads = [] t1 = QueryThread(query, 'username_search', new_limit) t2 = QueryThread(query, 'twitter_search', new_limit) t3 = QueryThread(query, 'people_search', new_limit) threads.append(t1) threads.append(t2) threads.append(t3) # start all threads [x.start() for x in threads] # wait for all of them to finish [x.join() for x in threads] # at this point all threads have finished and all queries have been performed results_username = t1.results results_twitter = t2.results results_people = t3.results results_people += results_username + results_twitter # dedup all results before sending out from substring_search import dedup_search_results results_people = dedup_search_results(results_people) results = {} results['results'] = results_people[:new_limit] resp = make_response(jsonify(results)) if len(results['results']) > 0: cache_timeout = DEFAULT_CACHE_TIMEOUT else: cache_timeout = EMPTY_CACHE_TIMEOUT resp.headers['Cache-Control'] = 'public, max-age={:d}'.format(cache_timeout) return resp
/** PURE_IMPORTS_START .._operators_startWith PURE_IMPORTS_END */ import { startWith as higherOrder } from '../operators/startWith'; /* tslint:enable:max-line-length */ /** * Returns an Observable that emits the items you specify as arguments before it begins to emit * items emitted by the source Observable. * * <img src="./img/startWith.png" width="100%"> * * @param {...T} values - Items you want the modified Observable to emit first. * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling * the emissions of the `next` notifications. * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items * emitted by the source Observable. * @method startWith * @owner Observable */ export function startWith() { var array = []; for (var _i = 0; _i < arguments.length; _i++) { array[_i - 0] = arguments[_i]; } return higherOrder.apply(void 0, array)(this); } //# sourceMappingURL=startWith.js.map